diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/hu/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/hu/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..6a6549d4a8873bca21a7e654697e2387debcfda3 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/hu/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..a3ded429b55878be1b8beacd8ee3dd7da58f5dd5 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..7b560462817e66560a3e471d420647af772007c5 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/id/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/it/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/it/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..403cd2c7bb9ee4eaab5fad15e82f3ab268c55897 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/it/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ja/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ja/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..b7cd14f22ef2c060b226109a4ef812b206a62060 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ja/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..0a9a7593da9232b1ae92bd4a3cc56d82779187ea Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..98f371eee976b74cb7a62bdd033e23a6e268e9ad Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ka/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ko/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ko/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..fa4e4aa256ea5cba9b6ce0b7093d5a9bd4241e5d Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ko/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..6f73778c82575f1f6158e2e221f287ed4c7a08fe Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..c085941ca4fda9e6b95449903612456e7909362c Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nb/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..43e5b53458538926ac6eed60fdc26b04838ae452 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..90324cd68843b16519d95ac4d5e2a205c8bd3d2e Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nl/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..bf8d9d306d0cfdcf96f20271c87feeacade905d5 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..9b8a52046f31bebed4220c1d57bcc19c546ca60d Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/nn/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pa/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pa/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..4f9478353dc27be32d3c5aaef56b9caa8168e892 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pa/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pl/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pl/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..0337d4cfe3a778b3407db271e7ca14839fb5a4ba Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pl/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..a5905477f566cd317344f9c80d9b5eabe74966eb Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt_BR/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt_BR/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..ef2172cf57dcfb3a7042e25bd192ff2fd3ab662a Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/pt_BR/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ro/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ro/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..7cfd7aa73afd5a3c8fe63134df0fe290622bba5d Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ro/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ru/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ru/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..6eeae60970e33ec07c8c63fcd5ddd0cfe4c694f3 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/ru/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sk/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sk/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..1e3126cb3726432b597b42450faf13d6cdf86520 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sk/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sl/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sl/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..67465e23241217a2ecb043369bfdd4e6f153b053 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sl/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sr/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sr/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..d87294a7526c57d23855da3fe21c2157a1aea57d Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sr/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sv/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sv/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..1a882d75369b6e9021111cb8d2d26e0a128374a4 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/sv/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..44ba2695454fd7b9f1771e0cd4656c8136f187e6 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-tools.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-tools.mo new file mode 100644 index 0000000000000000000000000000000000000000..8a5b14a7bb97463dbaf78a8cfe946a9d875709d8 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/tr/LC_MESSAGES/gettext-tools.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/uk/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/uk/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..0bad19072042f44517952243675a64e24ed81510 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/uk/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/vi/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/vi/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..acb405b19b3d03fb6eb8fba2d7c8554f99b24e60 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/vi/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_CN/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_CN/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..653ddea4c639d7d0be282c5605ab15c8837209d2 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_CN/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_HK/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_HK/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..b553e0c9e9cc62b2633b98ae606a85ecc9c8da35 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_HK/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_TW/LC_MESSAGES/gettext-runtime.mo b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_TW/LC_MESSAGES/gettext-runtime.mo new file mode 100644 index 0000000000000000000000000000000000000000..a3ffaac5f45b98e7abf8350da20ca7645dbe0f59 Binary files /dev/null and b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/locale/zh_TW/LC_MESSAGES/gettext-runtime.mo differ diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/autopoint.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/autopoint.1 new file mode 100644 index 0000000000000000000000000000000000000000..54054bc0d091304e6e30ef9e5f323eb54b657452 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/autopoint.1 @@ -0,0 +1,47 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH AUTOPOINT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +autopoint \- copies standard gettext infrastructure +.SH SYNOPSIS +.B autopoint +[\fI\,OPTION\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Copies standard gettext infrastructure files into a source package. +.SH OPTIONS +.TP +\fB\-\-help\fR +print this help and exit +.TP +\fB\-\-version\fR +print version information and exit +.TP +\fB\-f\fR, \fB\-\-force\fR +force overwriting of files that already exist +.TP +\fB\-n\fR, \fB\-\-dry\-run\fR +print modifications but don't perform them +.SH AUTHOR +Written by Bruno Haible +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2002\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B autopoint +is maintained as a Texinfo manual. If the +.B info +and +.B autopoint +programs are properly installed at your site, the command +.IP +.B info autopoint +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/envsubst.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/envsubst.1 new file mode 100644 index 0000000000000000000000000000000000000000..37883997b49eb356c26e5464a78301d7c1718354 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/envsubst.1 @@ -0,0 +1,55 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH ENVSUBST "1" "July 2025" "GNU gettext-runtime 0.25.1" "User Commands" +.SH NAME +envsubst \- substitutes environment variables in shell format strings +.SH SYNOPSIS +.B envsubst +[\fI\,OPTION\/\fR] [\fI\,SHELL-FORMAT\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Substitutes the values of environment variables. +.SS "Operation mode:" +.TP +\fB\-v\fR, \fB\-\-variables\fR +output the variables occurring in SHELL\-FORMAT +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.PP +In normal operation mode, standard input is copied to standard output, +with references to environment variables of the form $VARIABLE or ${VARIABLE} +being replaced with the corresponding values. If a SHELL\-FORMAT is given, +only those environment variables that are referenced in SHELL\-FORMAT are +substituted; otherwise all environment variables references occurring in +standard input are substituted. +.PP +When \fB\-\-variables\fR is used, standard input is ignored, and the output consists +of the environment variables that are referenced in SHELL\-FORMAT, one per line. +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2003\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B envsubst +is maintained as a Texinfo manual. If the +.B info +and +.B envsubst +programs are properly installed at your site, the command +.IP +.B info envsubst +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettext.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettext.1 new file mode 100644 index 0000000000000000000000000000000000000000..0dff85479e38c15c5e34c0a5cd107c3d5f66e6c0 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettext.1 @@ -0,0 +1,74 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH GETTEXT "1" "July 2025" "GNU gettext-runtime 0.25.1" "User Commands" +.SH NAME +gettext \- translate message +.SH SYNOPSIS +.B gettext +[\fI\,OPTION\/\fR] [[\fI\,TEXTDOMAIN\/\fR] \fI\,MSGID\/\fR] +.br +.B gettext +[\fI\,OPTION\/\fR] \fI\,-s \/\fR[\fI\,MSGID\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +The \fBgettext\fP program translates a natural language message into the +user's language, by looking up the translation in a message catalog. +.PP +Display native language translation of a textual message. +.TP +\fB\-d\fR, \fB\-\-domain\fR=\fI\,TEXTDOMAIN\/\fR +retrieve translated messages from TEXTDOMAIN +.TP +\fB\-c\fR, \fB\-\-context\fR=\fI\,CONTEXT\/\fR +specify context for MSGID +.TP +\fB\-e\fR +enable expansion of some escape sequences +.TP +\fB\-n\fR +suppress trailing newline +.TP +\fB\-E\fR +(ignored for compatibility) +.TP +[TEXTDOMAIN] MSGID +retrieve translated message corresponding +to MSGID from TEXTDOMAIN +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +display version information and exit +.PP +If the TEXTDOMAIN parameter is not given, the domain is determined from the +environment variable TEXTDOMAIN. If the message catalog is not found in the +regular directory, another location can be specified with the environment +variable TEXTDOMAINDIR. +When used with the \fB\-s\fR option the program behaves like the 'echo' command. +But it does not simply copy its arguments to stdout. Instead those messages +found in the selected catalog are translated. +Standard search directory: /home/task_177204486800161/croot/gettext-split_1772044997948/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeho/share/locale +.SH AUTHOR +Written by Ulrich Drepper. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B gettext +is maintained as a Texinfo manual. If the +.B info +and +.B gettext +programs are properly installed at your site, the command +.IP +.B info gettext +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettextize.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettextize.1 new file mode 100644 index 0000000000000000000000000000000000000000..8767c7272cc814db06fec6be64e093cc65bea9a0 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/gettextize.1 @@ -0,0 +1,56 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH GETTEXTIZE "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +gettextize \- install or upgrade gettext infrastructure +.SH SYNOPSIS +.B gettextize +[\fI\,OPTION\/\fR]... [\fI\,package-dir\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Prepares a source package to use gettext. +.SH OPTIONS +.TP +\fB\-\-help\fR +print this help and exit +.TP +\fB\-\-version\fR +print version information and exit +.TP +\fB\-f\fR, \fB\-\-force\fR +force writing of new files even if old exist +.TP +\fB\-\-po\-dir\fR=\fI\,DIR\/\fR +specify directory with PO files +.TP +\fB\-\-no\-changelog\fR +don't update or create ChangeLog files +.TP +\fB\-\-symlink\fR +make symbolic links instead of copying files +.TP +\fB\-n\fR, \fB\-\-dry\-run\fR +print modifications but don't perform them +.SH AUTHOR +Written by Ulrich Drepper +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B gettextize +is maintained as a Texinfo manual. If the +.B info +and +.B gettextize +programs are properly installed at your site, the command +.IP +.B info gettextize +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgattrib.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgattrib.1 new file mode 100644 index 0000000000000000000000000000000000000000..317a240cf72bb8bf6795a81f01def50b66b5e447 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgattrib.1 @@ -0,0 +1,172 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGATTRIB "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgattrib \- attribute matching and manipulation on message catalog +.SH SYNOPSIS +.B msgattrib +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Filters the messages of a translation catalog according to their attributes, +and manipulates the attributes. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Message selection:" +.TP +\fB\-\-translated\fR +keep translated, remove untranslated messages +.TP +\fB\-\-untranslated\fR +keep untranslated, remove translated messages +.TP +\fB\-\-no\-fuzzy\fR +remove 'fuzzy' marked messages +.TP +\fB\-\-only\-fuzzy\fR +keep 'fuzzy' marked messages +.TP +\fB\-\-no\-obsolete\fR +remove obsolete #~ messages +.TP +\fB\-\-only\-obsolete\fR +keep obsolete #~ messages +.SS "Attribute manipulation:" +.TP +\fB\-\-set\-fuzzy\fR +set all messages 'fuzzy' +.TP +\fB\-\-clear\-fuzzy\fR +set all messages non\-'fuzzy' +.TP +\fB\-\-set\-obsolete\fR +set all messages obsolete +.TP +\fB\-\-clear\-obsolete\fR +set all messages non\-obsolete +.TP +\fB\-\-previous\fR +when setting 'fuzzy', keep previous msgids +of translated messages. +.TP +\fB\-\-clear\-previous\fR +remove the "previous msgid" from all messages +.TP +\fB\-\-empty\fR +when removing 'fuzzy', also set msgstr empty +.TP +\fB\-\-only\-file\fR=\fI\,FILE\/\fR.po +manipulate only entries listed in FILE.po +.TP +\fB\-\-ignore\-file\fR=\fI\,FILE\/\fR.po +manipulate only entries not listed in FILE.po +.TP +\fB\-\-fuzzy\fR +synonym for \fB\-\-only\-fuzzy\fR \fB\-\-clear\-fuzzy\fR +.TP +\fB\-\-obsolete\fR +synonym for \fB\-\-only\-obsolete\fR \fB\-\-clear\-obsolete\fR +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write the .po file using indented style +.TP +\fB\-\-no\-location\fR +do not write '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +generate '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +write out strict Uniforum conforming .po file +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgattrib +is maintained as a Texinfo manual. If the +.B info +and +.B msgattrib +programs are properly installed at your site, the command +.IP +.B info msgattrib +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcat.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcat.1 new file mode 100644 index 0000000000000000000000000000000000000000..421ac77e34232dcba82c62d7af9b111f96d4b863 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcat.1 @@ -0,0 +1,152 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGCAT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgcat \- combines several message catalogs +.SH SYNOPSIS +.B msgcat +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Concatenates and merges the specified PO files. +Find messages which are common to two or more of the specified PO files. +By using the \fB\-\-more\-than\fR option, greater commonality may be requested +before messages are printed. Conversely, the \fB\-\-less\-than\fR option may be +used to specify less commonality before messages are printed (i.e. +\fB\-\-less\-than\fR=\fI\,2\/\fR will only print the unique messages). Translations, +comments, extracted comments, and file positions will be cumulated, except +that if \fB\-\-use\-first\fR is specified, they will be taken from the first PO file +to define them. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE ... +input files +.TP +\fB\-f\fR, \fB\-\-files\-from\fR=\fI\,FILE\/\fR +get list of input files from FILE +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If input file is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Message selection:" +.TP +\-<, \fB\-\-less\-than\fR=\fI\,NUMBER\/\fR +print messages with less than this many +definitions, defaults to infinite if not set +.TP +\->, \fB\-\-more\-than\fR=\fI\,NUMBER\/\fR +print messages with more than this many +definitions, defaults to 0 if not set +.TP +\fB\-u\fR, \fB\-\-unique\fR +shorthand for \fB\-\-less\-than\fR=\fI\,2\/\fR, requests +that only unique messages be printed +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input files are in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input files are in NeXTstep/GNUstep .strings +syntax +.SS "Output details:" +.TP +\fB\-t\fR, \fB\-\-to\-code\fR=\fI\,NAME\/\fR +encoding for output +.TP +\fB\-\-use\-first\fR +use first available translation for each +message, don't merge several translations +.TP +\fB\-\-lang\fR=\fI\,CATALOGNAME\/\fR +set 'Language' field in the header entry +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write the .po file using indented style +.TP +\fB\-\-no\-location\fR +do not write '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +generate '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +write out strict Uniforum conforming .po file +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgcat +is maintained as a Texinfo manual. If the +.B info +and +.B msgcat +programs are properly installed at your site, the command +.IP +.B info msgcat +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcmp.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcmp.1 new file mode 100644 index 0000000000000000000000000000000000000000..cabe1052f582f681b18d3f917b0d37ee363c0169 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcmp.1 @@ -0,0 +1,79 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGCMP "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgcmp \- compare message catalog and template +.SH SYNOPSIS +.B msgcmp +[\fI\,OPTION\/\fR] \fI\,def.po ref.pot\/\fR +.SH DESCRIPTION +.\" Add any additional description here +.PP +Compare two Uniforum style .po files to check that both contain the same +set of msgid strings. The def.po file is an existing PO file with the +translations. The ref.pot file is the last created PO file, or a PO Template +file (generally created by xgettext). This is useful for checking that +you have translated each and every message in your program. Where an exact +match cannot be found, fuzzy matching is used to produce better diagnostics. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +def.po +translations +.TP +ref.pot +references to the sources +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.SS "Operation modifiers:" +.TP +\fB\-m\fR, \fB\-\-multi\-domain\fR +apply ref.pot to each of the domains in def.po +.TP +\fB\-N\fR, \fB\-\-no\-fuzzy\-matching\fR +do not use fuzzy matching +.TP +\fB\-\-use\-fuzzy\fR +consider fuzzy entries +.TP +\fB\-\-use\-untranslated\fR +consider untranslated entries +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input files are in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input files are in NeXTstep/GNUstep .strings +syntax +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Peter Miller. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgcmp +is maintained as a Texinfo manual. If the +.B info +and +.B msgcmp +programs are properly installed at your site, the command +.IP +.B info msgcmp +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcomm.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcomm.1 new file mode 100644 index 0000000000000000000000000000000000000000..b850db1d5d2457daf9282a7b3f28c6643ff379a2 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgcomm.1 @@ -0,0 +1,144 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGCOMM "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgcomm \- match two message catalogs +.SH SYNOPSIS +.B msgcomm +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Find messages which are common to two or more of the specified PO files. +By using the \fB\-\-more\-than\fR option, greater commonality may be requested +before messages are printed. Conversely, the \fB\-\-less\-than\fR option may be +used to specify less commonality before messages are printed (i.e. +\fB\-\-less\-than\fR=\fI\,2\/\fR will only print the unique messages). Translations, +comments and extracted comments will be preserved, but only from the first +PO file to define them. File positions from all PO files will be +cumulated. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE ... +input files +.TP +\fB\-f\fR, \fB\-\-files\-from\fR=\fI\,FILE\/\fR +get list of input files from FILE +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If input file is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Message selection:" +.TP +\-<, \fB\-\-less\-than\fR=\fI\,NUMBER\/\fR +print messages with less than this many +definitions, defaults to infinite if not set +.TP +\->, \fB\-\-more\-than\fR=\fI\,NUMBER\/\fR +print messages with more than this many +definitions, defaults to 1 if not set +.TP +\fB\-u\fR, \fB\-\-unique\fR +shorthand for \fB\-\-less\-than\fR=\fI\,2\/\fR, requests +that only unique messages be printed +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input files are in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input files are in NeXTstep/GNUstep .strings +syntax +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write the .po file using indented style +.TP +\fB\-\-no\-location\fR +do not write '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +generate '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +write out strict Uniforum conforming .po file +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.TP +\fB\-\-omit\-header\fR +don't write header with 'msgid ""' entry +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Peter Miller. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgcomm +is maintained as a Texinfo manual. If the +.B info +and +.B msgcomm +programs are properly installed at your site, the command +.IP +.B info msgcomm +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgconv.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgconv.1 new file mode 100644 index 0000000000000000000000000000000000000000..c7eb3bfaf5dacf3dc71f9594c3e4775ab51b6748 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgconv.1 @@ -0,0 +1,123 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGCONV "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgconv \- character set conversion for message catalog +.SH SYNOPSIS +.B msgconv +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Converts a translation catalog to a different character encoding. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Conversion target:" +.TP +\fB\-t\fR, \fB\-\-to\-code\fR=\fI\,NAME\/\fR +encoding for output +.PP +The default encoding is the current locale's encoding. +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +indented output style +.TP +\fB\-\-no\-location\fR +suppress '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +preserve '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +strict Uniforum output style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgconv +is maintained as a Texinfo manual. If the +.B info +and +.B msgconv +programs are properly installed at your site, the command +.IP +.B info msgconv +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgen.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgen.1 new file mode 100644 index 0000000000000000000000000000000000000000..b456691d9d3b837170ecefa8bdd5a89232f7dc5f --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgen.1 @@ -0,0 +1,123 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGEN "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgen \- create English message catalog +.SH SYNOPSIS +.B msgen +[\fI\,OPTION\/\fR] \fI\,INPUTFILE\/\fR +.SH DESCRIPTION +.\" Add any additional description here +.PP +Creates an English translation catalog. The input file is the last +created English PO file, or a PO Template file (generally created by +xgettext). Untranslated entries are assigned a translation that is +identical to the msgid. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE +input PO or POT file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If input file is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-\-lang\fR=\fI\,CATALOGNAME\/\fR +set 'Language' field in the header entry +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +indented output style +.TP +\fB\-\-no\-location\fR +suppress '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +preserve '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +strict Uniforum output style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgen +is maintained as a Texinfo manual. If the +.B info +and +.B msgen +programs are properly installed at your site, the command +.IP +.B info msgen +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgexec.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgexec.1 new file mode 100644 index 0000000000000000000000000000000000000000..15a55a2bbad781ff34d2c44e7ed7157da7067d13 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgexec.1 @@ -0,0 +1,70 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGEXEC "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgexec \- process translations of message catalog +.SH SYNOPSIS +.B msgexec +[\fI\,OPTION\/\fR] \fI\,COMMAND \/\fR[\fI\,COMMAND-OPTION\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Applies a command to all translations of a translation catalog. +The COMMAND can be any program that reads a translation from standard +input. It is invoked once for each translation. Its output becomes +msgexec's output. msgexec's return code is the maximum return code +across all invocations. +.PP +A special builtin command called '0' outputs the translation, followed by a +null byte. The output of "msgexec 0" is suitable as input for "xargs \fB\-0\fR". +.SS "Command input:" +.TP +\fB\-\-newline\fR +add newline at the end of input +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +\fB\-i\fR, \fB\-\-input\fR=\fI\,INPUTFILE\/\fR +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgexec +is maintained as a Texinfo manual. If the +.B info +and +.B msgexec +programs are properly installed at your site, the command +.IP +.B info msgexec +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfilter.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfilter.1 new file mode 100644 index 0000000000000000000000000000000000000000..87a610c4b54910d1945f3b0d048d96bbfceee0dc --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfilter.1 @@ -0,0 +1,139 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGFILTER "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgfilter \- edit translations of message catalog +.SH SYNOPSIS +.B msgfilter +[\fI\,OPTION\/\fR] \fI\,FILTER \/\fR[\fI\,FILTER-OPTION\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Applies a filter to all translations of a translation catalog. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +\fB\-i\fR, \fB\-\-input\fR=\fI\,INPUTFILE\/\fR +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.PP +The FILTER can be any program that reads a translation from standard input +and writes a modified translation to standard output. +.SS "Filter input and output:" +.TP +\fB\-\-newline\fR +add a newline at the end of input and +remove a newline from the end of output +.SS "Useful FILTER-OPTIONs when the FILTER is 'sed':" +.TP +\fB\-e\fR, \fB\-\-expression\fR=\fI\,SCRIPT\/\fR +add SCRIPT to the commands to be executed +.TP +\fB\-f\fR, \fB\-\-file\fR=\fI\,SCRIPTFILE\/\fR +add the contents of SCRIPTFILE to the commands +to be executed +.TP +\fB\-n\fR, \fB\-\-quiet\fR, \fB\-\-silent\fR +suppress automatic printing of pattern space +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-\-indent\fR +indented output style +.TP +\fB\-\-keep\-header\fR +keep header entry unmodified, don't filter it +.TP +\fB\-\-no\-location\fR +suppress '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +preserve '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +strict Uniforum output style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgfilter +is maintained as a Texinfo manual. If the +.B info +and +.B msgfilter +programs are properly installed at your site, the command +.IP +.B info msgfilter +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfmt.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfmt.1 new file mode 100644 index 0000000000000000000000000000000000000000..bd78f59a99f4e3bbbc1fded91ee0e3ec80f3e9e9 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgfmt.1 @@ -0,0 +1,229 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGFMT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgfmt \- compile message catalog to binary format +.SH SYNOPSIS +.B msgfmt +[\fI\,OPTION\/\fR] \fI\,filename.po \/\fR... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Generate binary message catalog from textual translation description. +.PP +Mandatory arguments to long options are mandatory for short options too. +Similarly for optional arguments. +.SS "Input file location:" +.TP +filename.po ... +input files +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If input file is \-, standard input is read. +.SS "Operation mode:" +.TP +\fB\-j\fR, \fB\-\-java\fR +Java mode: generate a Java ResourceBundle class +.TP +\fB\-\-java2\fR +like \fB\-\-java\fR, and assume Java2 (JDK 1.2 or higher) +.TP +\fB\-\-csharp\fR +C# mode: generate a .NET .dll file +.TP +\fB\-\-csharp\-resources\fR +C# resources mode: generate a .NET .resources file +.TP +\fB\-\-tcl\fR +Tcl mode: generate a tcl/msgcat .msg file +.TP +\fB\-\-qt\fR +Qt mode: generate a Qt .qm file +.TP +\fB\-\-desktop\fR +Desktop Entry mode: generate a .desktop file +.TP +\fB\-\-xml\fR +XML mode: generate XML file +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.TP +\fB\-\-strict\fR +enable strict Uniforum mode +.PP +If output file is \-, output is written to standard output. +.SS "Output file location in Java mode:" +.TP +\fB\-r\fR, \fB\-\-resource\fR=\fI\,RESOURCE\/\fR +resource name +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-\-source\fR +produce a .java file, instead of a .class file +.TP +\fB\-d\fR DIRECTORY +base directory of classes directory hierarchy +.PP +The class name is determined by appending the locale name to the resource name, +separated with an underscore. The \fB\-d\fR option is mandatory. The class is +written under the specified directory. +.SS "Output file location in C# mode:" +.TP +\fB\-r\fR, \fB\-\-resource\fR=\fI\,RESOURCE\/\fR +resource name +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-d\fR DIRECTORY +base directory for locale dependent .dll files +.PP +The \fB\-l\fR and \fB\-d\fR options are mandatory. The .dll file is written in a +subdirectory of the specified directory whose name depends on the locale. +.SS "Output file location in Tcl mode:" +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-d\fR DIRECTORY +base directory of .msg message catalogs +.PP +The \fB\-l\fR and \fB\-d\fR options are mandatory. The .msg file is written in the +specified directory. +.SS "Desktop Entry mode options:" +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.TP +\fB\-\-template\fR=\fI\,TEMPLATE\/\fR +a .desktop file used as a template +.TP +\fB\-d\fR DIRECTORY +base directory of .po files +.TP +\fB\-kWORD\fR, \fB\-\-keyword\fR=\fI\,WORD\/\fR +look for WORD as an additional keyword +.TP +\fB\-k\fR, \fB\-\-keyword\fR +do not to use default keywords +.PP +The \fB\-l\fR, \fB\-o\fR, and \fB\-\-template\fR options are mandatory. If \fB\-D\fR is specified, input +files are read from the directory instead of the command line arguments. +.SS "XML mode options:" +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-L\fR, \fB\-\-language\fR=\fI\,NAME\/\fR +recognise the specified XML language +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.TP +\fB\-\-template\fR=\fI\,TEMPLATE\/\fR +an XML file used as a template +.TP +\fB\-d\fR DIRECTORY +base directory of .po files +.TP +\fB\-\-replace\-text\fR +output XML with translated text replacing the +original text, not augmenting the original text +.PP +The \fB\-l\fR, \fB\-o\fR, and \fB\-\-template\fR options are mandatory. If \fB\-D\fR is specified, input +files are read from the directory instead of the command line arguments. +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input files are in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input files are in NeXTstep/GNUstep .strings +syntax +.SS "Input file interpretation:" +.TP +\fB\-c\fR, \fB\-\-check\fR +perform all the checks implied by +\fB\-\-check\-format\fR, \fB\-\-check\-header\fR, \fB\-\-check\-domain\fR +.TP +\fB\-\-check\-format\fR +check language dependent format strings +.TP +\fB\-\-check\-header\fR +verify presence and contents of the header entry +.TP +\fB\-\-check\-domain\fR +check for conflicts between domain directives +and the \fB\-\-output\-file\fR option +.TP +\fB\-C\fR, \fB\-\-check\-compatibility\fR +check that GNU msgfmt behaves like X/Open msgfmt +.TP +\fB\-\-check\-accelerators\fR[=\fI\,CHAR\/\fR] +check presence of keyboard accelerators for +menu items +.TP +\fB\-f\fR, \fB\-\-use\-fuzzy\fR +use fuzzy entries in output +.SS "Output details:" +.TP +\fB\-\-no\-convert\fR +don't convert the messages to UTF\-8 encoding +.TP +\fB\-\-no\-redundancy\fR +don't pre\-expand ISO C 99 +format string directive macros +.TP +\fB\-a\fR, \fB\-\-alignment\fR=\fI\,NUMBER\/\fR +align strings to NUMBER bytes (default: 1) +.TP +\fB\-\-endianness\fR=\fI\,BYTEORDER\/\fR +write out 32\-bit numbers in the given byte order +(big or little, default depends on platform) +.TP +\fB\-\-no\-hash\fR +binary file will not include the hash table +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.TP +\fB\-\-statistics\fR +print statistics about translations +.TP +\fB\-v\fR, \fB\-\-verbose\fR +increase verbosity level +.SH AUTHOR +Written by Ulrich Drepper. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgfmt +is maintained as a Texinfo manual. If the +.B info +and +.B msgfmt +programs are properly installed at your site, the command +.IP +.B info msgfmt +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msggrep.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msggrep.1 new file mode 100644 index 0000000000000000000000000000000000000000..25f4e81eb5c28b13bbd2336554de1d9f4702cdc8 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msggrep.1 @@ -0,0 +1,182 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGGREP "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msggrep \- pattern matching on message catalog +.SH SYNOPSIS +.B msggrep +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Extracts all messages of a translation catalog that match a given pattern +or belong to some given source files. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Message selection:" +.IP +[\-N SOURCEFILE]... [\-M DOMAINNAME]... +[\-J MSGCTXT\-PATTERN] [\-K MSGID\-PATTERN] [\-T MSGSTR\-PATTERN] +[\-C COMMENT\-PATTERN] [\-X EXTRACTED\-COMMENT\-PATTERN] +.PP +A message is selected if it comes from one of the specified source files, +or if it comes from one of the specified domains, +or if \fB\-J\fR is given and its context (msgctxt) matches MSGCTXT\-PATTERN, +or if \fB\-K\fR is given and its key (msgid or msgid_plural) matches MSGID\-PATTERN, +or if \fB\-T\fR is given and its translation (msgstr) matches MSGSTR\-PATTERN, +or if \fB\-C\fR is given and the translator's comment matches COMMENT\-PATTERN, +or if \fB\-X\fR is given and the extracted comment matches EXTRACTED\-COMMENT\-PATTERN. +.PP +When more than one selection criterion is specified, the set of selected +messages is the union of the selected messages of each criterion. +.PP +MSGCTXT\-PATTERN or MSGID\-PATTERN or MSGSTR\-PATTERN or COMMENT\-PATTERN or +EXTRACTED\-COMMENT\-PATTERN syntax: +.IP +[\-E | \fB\-F]\fR [\-e PATTERN | \fB\-f\fR FILE]... +.PP +PATTERNs are basic regular expressions by default, or extended regular +expressions if \fB\-E\fR is given, or fixed strings if \fB\-F\fR is given. +.TP +\fB\-N\fR, \fB\-\-location\fR=\fI\,SOURCEFILE\/\fR +select messages extracted from SOURCEFILE +.TP +\fB\-M\fR, \fB\-\-domain\fR=\fI\,DOMAINNAME\/\fR +select messages belonging to domain DOMAINNAME +.TP +\fB\-J\fR, \fB\-\-msgctxt\fR +start of patterns for the msgctxt +.TP +\fB\-K\fR, \fB\-\-msgid\fR +start of patterns for the msgid +.TP +\fB\-T\fR, \fB\-\-msgstr\fR +start of patterns for the msgstr +.TP +\fB\-C\fR, \fB\-\-comment\fR +start of patterns for the translator's comment +.TP +\fB\-X\fR, \fB\-\-extracted\-comment\fR +start of patterns for the extracted comment +.TP +\fB\-E\fR, \fB\-\-extended\-regexp\fR +PATTERN is an extended regular expression +.TP +\fB\-F\fR, \fB\-\-fixed\-strings\fR +PATTERN is a set of newline\-separated strings +.TP +\fB\-e\fR, \fB\-\-regexp\fR=\fI\,PATTERN\/\fR +use PATTERN as a regular expression +.TP +\fB\-f\fR, \fB\-\-file\fR=\fI\,FILE\/\fR +obtain PATTERN from FILE +.TP +\fB\-i\fR, \fB\-\-ignore\-case\fR +ignore case distinctions +.TP +\fB\-v\fR, \fB\-\-invert\-match\fR +output only the messages that do not match any +selection criterion +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-\-indent\fR +indented output style +.TP +\fB\-\-no\-location\fR +suppress '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +preserve '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +strict Uniforum output style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msggrep +is maintained as a Texinfo manual. If the +.B info +and +.B msggrep +programs are properly installed at your site, the command +.IP +.B info msggrep +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msginit.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msginit.1 new file mode 100644 index 0000000000000000000000000000000000000000..2b4efd5de4ac6b8a25b26b752aac496d535b7097 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msginit.1 @@ -0,0 +1,95 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGINIT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msginit \- initialize a message catalog +.SH SYNOPSIS +.B msginit +[\fI\,OPTION\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Creates a new PO file, initializing the meta information with values from the +user's environment. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +\fB\-i\fR, \fB\-\-input\fR=\fI\,INPUTFILE\/\fR +input POT file +.PP +If no input file is given, the current directory is searched for the POT file. +If it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified PO file +.PP +If no output file is given, it depends on the \fB\-\-locale\fR option or the user's +locale setting. If it is \-, the results are written to standard output. +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LL_CC[\/\fR.ENCODING] +set target locale +.TP +\fB\-\-no\-translator\fR +assume the PO file is automatically generated +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msginit +is maintained as a Texinfo manual. If the +.B info +and +.B msginit +programs are properly installed at your site, the command +.IP +.B info msginit +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgmerge.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgmerge.1 new file mode 100644 index 0000000000000000000000000000000000000000..fd834e9c3c298ef510eaf329e4cee5ed15acb076 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgmerge.1 @@ -0,0 +1,185 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGMERGE "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgmerge \- merge message catalog and template +.SH SYNOPSIS +.B msgmerge +[\fI\,OPTION\/\fR] \fI\,def.po ref.pot\/\fR +.SH DESCRIPTION +.\" Add any additional description here +.PP +Merges two Uniforum style .po files together. The def.po file is an +existing PO file with translations which will be taken over to the newly +created file as long as they still match; comments will be preserved, +but extracted comments and file positions will be discarded. The ref.pot +file is the last created PO file with up\-to\-date source references but +old translations, or a PO Template file (generally created by xgettext); +any translations or comments in the file will be discarded, however dot +comments and file positions will be preserved. Where an exact match +cannot be found, fuzzy matching is used to produce better results. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +def.po +translations referring to old sources +.TP +ref.pot +references to new sources +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.TP +\fB\-C\fR, \fB\-\-compendium\fR=\fI\,FILE\/\fR +additional library of message translations, +may be specified more than once +.SS "Operation mode:" +.TP +\fB\-U\fR, \fB\-\-update\fR +update def.po, +do nothing if def.po already up to date +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.PP +Output file location in update mode: +The result is written back to def.po. +.TP +\fB\-\-backup\fR=\fI\,CONTROL\/\fR +make a backup of def.po +.TP +\fB\-\-suffix\fR=\fI\,SUFFIX\/\fR +override the usual backup suffix +.PP +The version control method may be selected via the \fB\-\-backup\fR option or through +the VERSION_CONTROL environment variable. Here are the values: +.TP +none, off +never make backups (even if \fB\-\-backup\fR is given) +.TP +numbered, t +make numbered backups +.TP +existing, nil +numbered if numbered backups exist, simple otherwise +.TP +simple, never +always make simple backups +.PP +The backup suffix is '~', unless set with \fB\-\-suffix\fR or the SIMPLE_BACKUP_SUFFIX +environment variable. +.SS "Operation modifiers:" +.TP +\fB\-m\fR, \fB\-\-multi\-domain\fR +apply ref.pot to each of the domains in def.po +.TP +\fB\-\-for\-msgfmt\fR +produce output for 'msgfmt', not for a translator +.TP +\fB\-N\fR, \fB\-\-no\-fuzzy\-matching\fR +do not use fuzzy matching +.TP +\fB\-\-previous\fR +keep previous msgids of translated messages +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input files are in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input files are in NeXTstep/GNUstep .strings +syntax +.SS "Output details:" +.TP +\fB\-\-lang\fR=\fI\,CATALOGNAME\/\fR +set 'Language' field in the header entry +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +indented output style +.TP +\fB\-\-no\-location\fR +suppress '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +preserve '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +strict Uniforum output style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output (deprecated) +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.TP +\fB\-v\fR, \fB\-\-verbose\fR +increase verbosity level +.TP +\fB\-q\fR, \fB\-\-quiet\fR, \fB\-\-silent\fR +suppress progress indicators +.SH AUTHOR +Written by Peter Miller. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgmerge +is maintained as a Texinfo manual. If the +.B info +and +.B msgmerge +programs are properly installed at your site, the command +.IP +.B info msgmerge +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgunfmt.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgunfmt.1 new file mode 100644 index 0000000000000000000000000000000000000000..84ddbaf2e900bf4a8b64c4477b549959828b04a3 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msgunfmt.1 @@ -0,0 +1,147 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGUNFMT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msgunfmt \- uncompile message catalog from binary format +.SH SYNOPSIS +.B msgunfmt +[\fI\,OPTION\/\fR] [\fI\,FILE\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Convert binary message catalog to Uniforum style .po file. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Operation mode:" +.TP +\fB\-j\fR, \fB\-\-java\fR +Java mode: input is a Java ResourceBundle class +.TP +\fB\-\-csharp\fR +C# mode: input is a .NET .dll file +.TP +\fB\-\-csharp\-resources\fR +C# resources mode: input is a .NET .resources file +.TP +\fB\-\-tcl\fR +Tcl mode: input is a tcl/msgcat .msg file +.SS "Input file location:" +.TP +FILE ... +input .mo files +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Input file location in Java mode:" +.TP +\fB\-r\fR, \fB\-\-resource\fR=\fI\,RESOURCE\/\fR +resource name +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.PP +The class name is determined by appending the locale name to the resource name, +separated with an underscore. The class is located using the CLASSPATH. +.SS "Input file location in C# mode:" +.TP +\fB\-r\fR, \fB\-\-resource\fR=\fI\,RESOURCE\/\fR +resource name +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-d\fR DIRECTORY +base directory for locale dependent .dll files +.PP +The \fB\-l\fR and \fB\-d\fR options are mandatory. The .dll file is located in a +subdirectory of the specified directory whose name depends on the locale. +.SS "Input file location in Tcl mode:" +.TP +\fB\-l\fR, \fB\-\-locale\fR=\fI\,LOCALE\/\fR +locale name, either language or language_COUNTRY +.TP +\fB\-d\fR DIRECTORY +base directory of .msg message catalogs +.PP +The \fB\-l\fR and \fB\-d\fR options are mandatory. The .msg file is located in the +specified directory. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write indented output style +.TP +\fB\-\-strict\fR +write strict uniforum style +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.TP +\fB\-v\fR, \fB\-\-verbose\fR +increase verbosity level +.SH AUTHOR +Written by Ulrich Drepper. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msgunfmt +is maintained as a Texinfo manual. If the +.B info +and +.B msgunfmt +programs are properly installed at your site, the command +.IP +.B info msgunfmt +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msguniq.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msguniq.1 new file mode 100644 index 0000000000000000000000000000000000000000..efb71f55582f44314c9ae18d9f37f107b5e30b32 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/msguniq.1 @@ -0,0 +1,138 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH MSGUNIQ "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +msguniq \- unify duplicate translations in message catalog +.SH SYNOPSIS +.B msguniq +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Unifies duplicate translations in a translation catalog. +Finds duplicate translations of the same message ID. Such duplicates are +invalid input for other programs like msgfmt, msgmerge or msgcat. By +default, duplicates are merged together. When using the \fB\-\-repeated\fR option, +only duplicates are output, and all other messages are discarded. Comments +and extracted comments will be cumulated, except that if \fB\-\-use\-first\fR is +specified, they will be taken from the first translation. File positions +will be cumulated. When using the \fB\-\-unique\fR option, duplicates are discarded. +.PP +Mandatory arguments to long options are mandatory for short options too. +.SS "Input file location:" +.TP +INPUTFILE +input PO file +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If no input file is given or if it is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-o\fR, \fB\-\-output\-file\fR=\fI\,FILE\/\fR +write output to specified file +.PP +The results are written to standard output if no output file is specified +or if it is \-. +.SS "Message selection:" +.TP +\fB\-d\fR, \fB\-\-repeated\fR +print only duplicates +.TP +\fB\-u\fR, \fB\-\-unique\fR +print only unique messages, discard duplicates +.SS "Input file syntax:" +.TP +\fB\-P\fR, \fB\-\-properties\-input\fR +input file is in Java .properties syntax +.TP +\fB\-\-stringtable\-input\fR +input file is in NeXTstep/GNUstep .strings syntax +.SS "Output details:" +.TP +\fB\-t\fR, \fB\-\-to\-code\fR=\fI\,NAME\/\fR +encoding for output +.TP +\fB\-\-use\-first\fR +use first available translation for each +message, don't merge several translations +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write the .po file using indented style +.TP +\fB\-\-no\-location\fR +do not write '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +generate '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +write out strict Uniforum conforming .po file +.TP +\fB\-p\fR, \fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2001\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B msguniq +is maintained as a Texinfo manual. If the +.B info +and +.B msguniq +programs are properly installed at your site, the command +.IP +.B info msguniq +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/ngettext.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/ngettext.1 new file mode 100644 index 0000000000000000000000000000000000000000..f71c81e22c5893bc16ddf09552b0893604300109 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/ngettext.1 @@ -0,0 +1,73 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH NGETTEXT "1" "July 2025" "GNU gettext-runtime 0.25.1" "User Commands" +.SH NAME +ngettext \- translate message and choose plural form +.SH SYNOPSIS +.B ngettext +[\fI\,OPTION\/\fR] [\fI\,TEXTDOMAIN\/\fR] \fI\,MSGID MSGID-PLURAL COUNT\/\fR +.SH DESCRIPTION +.\" Add any additional description here +The \fBngettext\fP program translates a natural language message into the +user's language, by looking up the translation in a message catalog, and +chooses the appropriate plural form, which depends on the number \fICOUNT\fP +and the language of the message catalog where the translation was found. +.PP +Display native language translation of a textual message whose grammatical +form depends on a number. +.TP +\fB\-d\fR, \fB\-\-domain\fR=\fI\,TEXTDOMAIN\/\fR +retrieve translated message from TEXTDOMAIN +.TP +\fB\-c\fR, \fB\-\-context\fR=\fI\,CONTEXT\/\fR +specify context for MSGID +.TP +\fB\-e\fR +enable expansion of some escape sequences +.TP +\fB\-E\fR +(ignored for compatibility) +.TP +[TEXTDOMAIN] +retrieve translated message from TEXTDOMAIN +.TP +MSGID MSGID\-PLURAL +translate MSGID (singular) / MSGID\-PLURAL (plural) +.TP +COUNT +choose singular/plural form based on this value +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +display version information and exit +.PP +If the TEXTDOMAIN parameter is not given, the domain is determined from the +environment variable TEXTDOMAIN. If the message catalog is not found in the +regular directory, another location can be specified with the environment +variable TEXTDOMAINDIR. +Standard search directory: /home/task_177204486800161/croot/gettext-split_1772044997948/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeho/share/locale +.SH AUTHOR +Written by Ulrich Drepper. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B ngettext +is maintained as a Texinfo manual. If the +.B info +and +.B ngettext +programs are properly installed at your site, the command +.IP +.B info ngettext +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/recode-sr-latin.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/recode-sr-latin.1 new file mode 100644 index 0000000000000000000000000000000000000000..53edba875c4dbf3ed7c2bff52edbfd6ab18b4bf0 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/recode-sr-latin.1 @@ -0,0 +1,43 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH RECODE-SR-LATIN "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +recode-sr-latin \- convert Serbian text from Cyrillic to Latin script +.SH SYNOPSIS +.B recode-sr-latin +[\fI\,OPTION\/\fR] +.SH DESCRIPTION +.\" Add any additional description here +.PP +Recode Serbian text from Cyrillic to Latin script. +The input text is read from standard input. The converted text is output to +standard output. +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.SH AUTHOR +Written by Danilo Segan and Bruno Haible. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 2006\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B recode-sr-latin +is maintained as a Texinfo manual. If the +.B info +and +.B recode-sr-latin +programs are properly installed at your site, the command +.IP +.B info recode-sr-latin +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/xgettext.1 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/xgettext.1 new file mode 100644 index 0000000000000000000000000000000000000000..f161158265b819f03d9a3ca7805b428e307440a1 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man1/xgettext.1 @@ -0,0 +1,275 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6. +.TH XGETTEXT "1" "July 2025" "GNU gettext-tools 0.25.1" "User Commands" +.SH NAME +xgettext \- extract gettext strings from source +.SH SYNOPSIS +.B xgettext +[\fI\,OPTION\/\fR] [\fI\,INPUTFILE\/\fR]... +.SH DESCRIPTION +.\" Add any additional description here +.PP +Extract translatable strings from given input files. +.PP +Mandatory arguments to long options are mandatory for short options too. +Similarly for optional arguments. +.SS "Input file location:" +.TP +INPUTFILE ... +input files +.TP +\fB\-f\fR, \fB\-\-files\-from\fR=\fI\,FILE\/\fR +get list of input files from FILE +.TP +\fB\-D\fR, \fB\-\-directory\fR=\fI\,DIRECTORY\/\fR +add DIRECTORY to list for input files search +.PP +If input file is \-, standard input is read. +.SS "Output file location:" +.TP +\fB\-d\fR, \fB\-\-default\-domain\fR=\fI\,NAME\/\fR +use NAME.po for output (instead of messages.po) +.TP +\fB\-o\fR, \fB\-\-output\fR=\fI\,FILE\/\fR +write output to specified file +.TP +\fB\-p\fR, \fB\-\-output\-dir\fR=\fI\,DIR\/\fR +output files will be placed in directory DIR +.PP +If output file is \-, output is written to standard output. +.SS "Choice of input file language:" +.TP +\fB\-L\fR, \fB\-\-language\fR=\fI\,NAME\/\fR +recognise the specified language +(C, C++, ObjectiveC, PO, Python, Java, +JavaProperties, C#, JavaScript, TypeScript, TSX, +Scheme, Guile, Lisp, EmacsLisp, librep, Rust, +Go, Ruby, Shell, awk, Lua, Modula\-2, D, +Smalltalk, Vala, Tcl, Perl, PHP, GCC\-source, +YCP, NXStringTable, RST, RSJ, Glade, GSettings, +Desktop) +.TP +\fB\-C\fR, \fB\-\-c\fR++ +shorthand for \fB\-\-language\fR=\fI\,C\/\fR++ +.PP +By default the language is guessed depending on the input file name extension. +.SS "Input file interpretation:" +.TP +\fB\-\-from\-code\fR=\fI\,NAME\/\fR +encoding of input files +(except for Python, Tcl, Glade) +.PP +By default the input files are assumed to be in ASCII. +.SS "Operation mode:" +.TP +\fB\-j\fR, \fB\-\-join\-existing\fR +join messages with existing file +.TP +\fB\-x\fR, \fB\-\-exclude\-file\fR=\fI\,FILE\/\fR.po +entries from FILE.po are not extracted +.TP +\fB\-cTAG\fR, \fB\-\-add\-comments\fR=\fI\,TAG\/\fR +place comment blocks starting with TAG and +preceding keyword lines in output file +.TP +\fB\-c\fR, \fB\-\-add\-comments\fR +place all comment blocks preceding keyword lines +in output file +.TP +\fB\-\-check\fR=\fI\,NAME\/\fR +perform syntax check on messages +(ellipsis\-unicode, space\-ellipsis, +.IP +quote\-unicode, bullet\-unicode) +.TP +\fB\-\-sentence\-end\fR=\fI\,TYPE\/\fR +type describing the end of sentence +(single\-space, which is the default, +.IP +or double\-space) +.SS "Language specific options:" +.TP +\fB\-a\fR, \fB\-\-extract\-all\fR +extract all strings +(only languages C, C++, ObjectiveC, Python, +Java, C#, JavaScript, TypeScript, TSX, Scheme, +Guile, Lisp, EmacsLisp, librep, Rust, Go, Shell, +awk, Lua, Modula\-2, D, Vala, Tcl, Perl, PHP, +GCC\-source, Glade, GSettings) +.TP +\fB\-kWORD\fR, \fB\-\-keyword\fR=\fI\,WORD\/\fR +look for WORD as an additional keyword +.TP +\fB\-k\fR, \fB\-\-keyword\fR +do not to use default keywords +(only languages C, C++, ObjectiveC, Python, +Java, C#, JavaScript, TypeScript, TSX, Scheme, +Guile, Lisp, EmacsLisp, librep, Rust, Go, Shell, +awk, Lua, Modula\-2, D, Vala, Tcl, Perl, PHP, +GCC\-source, Glade, GSettings, Desktop) +.TP +\fB\-\-flag\fR=\fI\,WORD\/\fR:ARG:FLAG +additional flag for strings inside the argument +number ARG of keyword WORD +.TP +(only languages C, C++, ObjectiveC, Python, +Java, C#, JavaScript, TypeScript, TSX, Scheme, +Guile, Lisp, EmacsLisp, librep, Rust, Go, Shell, +awk, Lua, Modula\-2, D, Vala, Tcl, Perl, PHP, +GCC\-source, YCP) +.TP +\fB\-\-tag\fR=\fI\,WORD\/\fR:FORMAT +defines the behaviour of tagged template literals +with tag WORD +.IP +(only language JavaScript) +.TP +\fB\-T\fR, \fB\-\-trigraphs\fR +understand ANSI C trigraphs for input +(deprecated; only languages C, C++, ObjectiveC) +.TP +\fB\-\-its\fR=\fI\,FILE\/\fR +apply ITS rules from FILE +(only XML based languages) +.TP +\fB\-\-qt\fR +recognize Qt format strings +(only language C++) +.TP +\fB\-\-kde\fR +recognize KDE 4 format strings +(only language C++) +.TP +\fB\-\-boost\fR +recognize Boost format strings +(only language C++) +.TP +\fB\-\-debug\fR +more detailed formatstring recognition result +.SS "Output details:" +.TP +\fB\-\-color\fR +use colors and other text attributes always +.TP +\fB\-\-color\fR=\fI\,WHEN\/\fR +use colors and other text attributes if WHEN. +WHEN may be 'always', 'never', 'auto', or 'html'. +.TP +\fB\-\-style\fR=\fI\,STYLEFILE\/\fR +specify CSS style rule file for \fB\-\-color\fR +.TP +\fB\-e\fR, \fB\-\-no\-escape\fR +do not use C escapes in output (default) +.TP +\fB\-E\fR, \fB\-\-escape\fR +use C escapes in output, no extended chars +.TP +\fB\-\-force\-po\fR +write PO file even if empty +.TP +\fB\-i\fR, \fB\-\-indent\fR +write the .po file using indented style +.TP +\fB\-\-no\-location\fR +do not write '#: filename:line' lines +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +generate '#: filename:line' lines (default) +.TP +\fB\-\-strict\fR +write out strict Uniforum conforming .po file +.TP +\fB\-\-properties\-output\fR +write out a Java .properties file +.TP +\fB\-\-stringtable\-output\fR +write out a NeXTstep/GNUstep .strings file +.TP +\fB\-\-itstool\fR +write out itstool comments +.TP +\fB\-w\fR, \fB\-\-width\fR=\fI\,NUMBER\/\fR +set output page width +.TP +\fB\-\-no\-wrap\fR +do not break long message lines, longer than +the output page width, into several lines +.TP +\fB\-s\fR, \fB\-\-sort\-output\fR +generate sorted output (deprecated) +.TP +\fB\-F\fR, \fB\-\-sort\-by\-file\fR +sort output by file location +.TP +\fB\-\-omit\-header\fR +don't write header with 'msgid ""' entry +.TP +\fB\-\-no\-git\fR +don't use the git program to produce a +reproducible 'POT\-Creation\-Date' field in the +output. +.TP +\fB\-\-copyright\-holder\fR=\fI\,STRING\/\fR +set copyright holder in output +.TP +\fB\-\-foreign\-user\fR +omit FSF copyright in output for foreign user +.TP +\fB\-\-package\-name\fR=\fI\,PACKAGE\/\fR +set package name in output +.TP +\fB\-\-package\-version\fR=\fI\,VERSION\/\fR +set package version in output +.TP +\fB\-\-msgid\-bugs\-address\fR=\fI\,EMAIL\/\fR@ADDRESS +set report address for msgid bugs +.TP +\fB\-\-generated\fR=\fI\,FILE\/\fR +Declares that the given FILE is generated and +therefore should not have an influence on the +\&'POT\-Creation\-Date' field in the output. +.TP +\fB\-\-reference\fR=\fI\,FILE\/\fR +Declares that the output depends on the contents +of the given FILE. This has an influence on the +\&'POT\-Creation\-Date' field in the output. +.TP +\fB\-m[STRING]\fR, \fB\-\-msgstr\-prefix\fR[=\fI\,STRING\/\fR] +use STRING or "" as prefix for msgstr +values +.TP +\fB\-M[STRING]\fR, \fB\-\-msgstr\-suffix\fR[=\fI\,STRING\/\fR] +use STRING or "" as suffix for msgstr +values +.SS "Informative output:" +.TP +\fB\-h\fR, \fB\-\-help\fR +display this help and exit +.TP +\fB\-V\fR, \fB\-\-version\fR +output version information and exit +.TP +\fB\-v\fR, \fB\-\-verbose\fR +increase verbosity level +.SH AUTHOR +Written by Ulrich Drepper. +.SH "REPORTING BUGS" +Report bugs in the bug tracker at +or by email to . +.SH COPYRIGHT +Copyright \(co 1995\-2025 Free Software Foundation, Inc. +License GPLv3+: GNU GPL version 3 or later +.br +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. +.SH "SEE ALSO" +The full documentation for +.B xgettext +is maintained as a Texinfo manual. If the +.B info +and +.B xgettext +programs are properly installed at your site, the command +.IP +.B info xgettext +.PP +should give you access to the complete manual. diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bind_textdomain_codeset.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bind_textdomain_codeset.3 new file mode 100644 index 0000000000000000000000000000000000000000..d3a66c8b5c7e2b8cfb9661c76de7a27486545953 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bind_textdomain_codeset.3 @@ -0,0 +1,72 @@ +.\" Copyright (c) Bruno Haible +.\" +.\" This is free documentation; you can redistribute it and/or +.\" modify it under the terms of the GNU General Public License as +.\" published by the Free Software Foundation; either version 2 of +.\" the License, or (at your option) any later version. +.\" +.\" References consulted: +.\" GNU glibc-2 source code and manual +.\" GNU gettext source code and manual +.\" LI18NUX 2000 Globalization Specification +.\" +.TH BIND_TEXTDOMAIN_CODESET 3 "November 2024" "GNU gettext 0.25.1" +.SH NAME +bind_textdomain_codeset \- set encoding of message translations +.SH SYNOPSIS +.nf +.B #include +.sp +.BI "char * bind_textdomain_codeset (const char * " domainname , +.BI " const char * " codeset ); +.fi +.SH DESCRIPTION +The \fBbind_textdomain_codeset\fP function sets the output codeset for message +catalogs for domain \fIdomainname\fP. +.PP +A message domain is a set of translatable \fImsgid\fP messages. Usually, +every software package has its own message domain. +.PP +By default, the \fBgettext\fP family of functions returns translated messages +in the locale's character encoding, which can be retrieved as +\fBnl_langinfo (CODESET)\fP. The need for calling \fBbind_textdomain_codeset\fP +arises for programs which store strings in a locale independent way (e.g.\& +UTF-8) and want to avoid an extra character set conversion on the returned +translated messages. +.PP +\fIdomainname\fP must be a non-empty string. +.PP +If \fIcodeset\fP is not NULL, it must be a valid encoding name which can be +used for the \fBiconv_open\fP function. The \fBbind_textdomain_codeset\fP +function sets the output codeset for message catalogs belonging to domain +\fIdomainname\fP to \fIcodeset\fP. The function makes copies of the argument +strings as needed. +.PP +If \fIcodeset\fP is NULL, the function returns the previously set codeset for +domain \fIdomainname\fP. The default is NULL, denoting the locale's character +encoding. +.SH "RETURN VALUE" +If successful, the \fBbind_textdomain_codeset\fP function returns the current +codeset for domain \fIdomainname\fP, after possibly changing it. The resulting +string is valid until the next \fBbind_textdomain_codeset\fP call for the same +\fIdomainname\fP and must not be modified or freed. If a memory allocation +failure occurs, it sets \fBerrno\fP to \fBENOMEM\fP and returns NULL. If no +codeset has been set for domain \fIdomainname\fP, it returns NULL. +.SH ERRORS +The following error can occur, among others: +.TP +.B ENOMEM +Not enough memory available. +.SH BUGS +The return type ought to be \fBconst char *\fP, but is \fBchar *\fP to avoid +warnings in C code predating ANSI C. +.SH "SEE ALSO" +.BR gettext (3), +.BR dgettext (3), +.BR dcgettext (3), +.BR ngettext (3), +.BR dngettext (3), +.BR dcngettext (3), +.BR textdomain (3), +.BR nl_langinfo (3), +.BR iconv_open (3) diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bindtextdomain.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bindtextdomain.3 new file mode 100644 index 0000000000000000000000000000000000000000..4ee7a30d728396ebc6ee4e64ca14d9863370f2bf --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/bindtextdomain.3 @@ -0,0 +1,69 @@ +.\" Copyright (c) Bruno Haible +.\" +.\" This is free documentation; you can redistribute it and/or +.\" modify it under the terms of the GNU General Public License as +.\" published by the Free Software Foundation; either version 2 of +.\" the License, or (at your option) any later version. +.\" +.\" References consulted: +.\" GNU glibc-2 source code and manual +.\" GNU gettext source code and manual +.\" LI18NUX 2000 Globalization Specification +.\" +.TH BINDTEXTDOMAIN 3 "May 2001" "GNU gettext 0.25.1" +.SH NAME +bindtextdomain \- set directory containing message catalogs +.SH SYNOPSIS +.nf +.B #include +.sp +.BI "char * bindtextdomain (const char * " domainname ", const char * " dirname ); +.fi +.SH DESCRIPTION +The \fBbindtextdomain\fP function sets the base directory of the hierarchy +containing message catalogs for a given message domain. +.PP +A message domain is a set of translatable \fImsgid\fP messages. Usually, +every software package has its own message domain. The need for calling +\fBbindtextdomain\fP arises because packages are not always installed with +the same prefix as the header and the libc/libintl libraries. +.PP +Message catalogs will be expected at the pathnames +\fIdirname\fP/\fIlocale\fP/\fIcategory\fP/\fIdomainname\fP.mo, +where \fIlocale\fP is a locale name and \fIcategory\fP is a locale facet such +as \fBLC_MESSAGES\fP. +.PP +\fIdomainname\fP must be a non-empty string. +.PP +If \fIdirname\fP is not NULL, the base directory for message catalogs belonging +to domain \fIdomainname\fP is set to \fIdirname\fP. The function makes copies +of the argument strings as needed. If the program wishes to call the +\fBchdir\fP function, it is important that \fIdirname\fP be an absolute +pathname; otherwise it cannot be guaranteed that the message catalogs will +be found. +.PP +If \fIdirname\fP is NULL, the function returns the previously set base +directory for domain \fIdomainname\fP. +.SH "RETURN VALUE" +If successful, the \fBbindtextdomain\fP function returns the current base +directory for domain \fIdomainname\fP, after possibly changing it. The +resulting string is valid until the next \fBbindtextdomain\fP call for the +same \fIdomainname\fP and must not be modified or freed. If a memory allocation +failure occurs, it sets \fBerrno\fP to \fBENOMEM\fP and returns NULL. +.SH ERRORS +The following error can occur, among others: +.TP +.B ENOMEM +Not enough memory available. +.SH BUGS +The return type ought to be \fBconst char *\fP, but is \fBchar *\fP to avoid +warnings in C code predating ANSI C. +.SH "SEE ALSO" +.BR gettext (3), +.BR dgettext (3), +.BR dcgettext (3), +.BR ngettext (3), +.BR dngettext (3), +.BR dcngettext (3), +.BR textdomain (3), +.BR realpath (3) diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcgettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcgettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..9082c86be87d8177066087cdd5d3ed3d97edbd6e --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcgettext.3 @@ -0,0 +1 @@ +.so man3/gettext.3 diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcngettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcngettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..5fcf629c8168b6a7203567083dd1b920ce8ca003 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dcngettext.3 @@ -0,0 +1 @@ +.so man3/ngettext.3 diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dgettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dgettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..9082c86be87d8177066087cdd5d3ed3d97edbd6e --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dgettext.3 @@ -0,0 +1 @@ +.so man3/gettext.3 diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dngettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dngettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..5fcf629c8168b6a7203567083dd1b920ce8ca003 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/dngettext.3 @@ -0,0 +1 @@ +.so man3/ngettext.3 diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/gettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/gettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..8a6e4ce0cb4eb120cb7d5ae6e7892840d32b0df3 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/gettext.3 @@ -0,0 +1,99 @@ +.\" Copyright (c) Bruno Haible +.\" +.\" This is free documentation; you can redistribute it and/or +.\" modify it under the terms of the GNU General Public License as +.\" published by the Free Software Foundation; either version 2 of +.\" the License, or (at your option) any later version. +.\" +.\" References consulted: +.\" GNU glibc-2 source code and manual +.\" GNU gettext source code and manual +.\" LI18NUX 2000 Globalization Specification +.\" +.TH GETTEXT 3 "November 2024" "GNU gettext 0.25.1" +.SH NAME +gettext, dgettext, dcgettext \- translate message +.SH SYNOPSIS +.nf +.B #include +.sp +.BI "char * gettext (const char * " msgid ); +.BI "char * dgettext (const char * " domainname ", const char * " msgid ); +.BI "char * dcgettext (const char * " domainname ", const char * " msgid , +.BI " int " category ); +.fi +.SH DESCRIPTION +The \fBgettext\fP, \fBdgettext\fP and \fBdcgettext\fP functions attempt to +translate a text string into the user's native language, by looking up the +translation in a message catalog. +.PP +The \fImsgid\fP argument identifies the message to be translated. By +convention, it is the English version of the message, with non-ASCII +characters replaced by ASCII approximations. This choice allows the +translators to work with message catalogs, called PO files, that contain +both the English and the translated versions of each message, and can be +installed using the \fBmsgfmt\fP utility. +.PP +A message domain is a set of translatable \fImsgid\fP messages. Usually, +every software package has its own message domain. The domain name is used +to determine the message catalog where the translation is looked up; it must +be a non-empty string. For the \fBgettext\fP function, it is specified through +a preceding \fBtextdomain\fP call. For the \fBdgettext\fP and \fBdcgettext\fP +functions, it is passed as the \fIdomainname\fP argument; if this argument is +NULL, the domain name specified through a preceding \fBtextdomain\fP call is +used instead. +.PP +Translation lookup operates in the context of the current locale. For the +\fBgettext\fP and \fBdgettext\fP functions, the \fBLC_MESSAGES\fP locale +facet is used. It is determined by a preceding call to the \fBsetlocale\fP +function. \fBsetlocale (LC_ALL, "")\fP initializes the \fBLC_MESSAGES\fP locale +based on the first nonempty value of the three environment variables +\fBLC_ALL\fP, \fBLC_MESSAGES\fP, \fBLANG\fP; see \fBsetlocale\fP(3). For the +\fBdcgettext\fP function, the locale facet is determined by the \fIcategory\fP +argument, which should be one of the \fBLC_xxx\fP constants defined in the + header, excluding \fBLC_ALL\fP. In both cases, the functions also +use the \fBLC_CTYPE\fP locale facet in order to convert the translated message +from the translator's codeset to the current locale's codeset, unless +overridden by a prior call to the \fBbind_textdomain_codeset\fP function. +.PP +The message catalog used by the functions is at the pathname +\fIdirname\fP/\fIlocale\fP/\fIcategory\fP/\fIdomainname\fP.mo. Here +\fIdirname\fP is the directory specified through \fBbindtextdomain\fP. Its +default is system and configuration dependent; typically it is +\fIprefix\fP/share/locale, where \fIprefix\fP is the installation prefix of the +package. \fIlocale\fP is the name of the current locale facet; the GNU +implementation also tries generalizations, such as the language name without +the territory name. \fIcategory\fP is \fBLC_MESSAGES\fP for the \fBgettext\fP +and \fBdgettext\fP functions, or the argument passed to the \fBdcgettext\fP +function. +.PP +If the \fBLANGUAGE\fP environment variable is set to a nonempty value, and the +locale is not the "C" locale, the value of \fBLANGUAGE\fP is assumed to contain +a colon separated list of locale names. The functions will attempt to look up +a translation of \fImsgid\fP in each of the locales in turn. This is a GNU +extension. +.PP +In the "C" locale, or if none of the used catalogs contain a translation for +\fImsgid\fP, the \fBgettext\fP, \fBdgettext\fP and \fBdcgettext\fP functions +return \fImsgid\fP. +.SH "RETURN VALUE" +If a translation was found in one of the specified catalogs, it is converted +to the locale's codeset and returned. The resulting string is statically +allocated and must not be modified or freed. Otherwise \fImsgid\fP is returned. +.SH ERRORS +\fBerrno\fP is not modified. +.SH BUGS +The return type ought to be \fBconst char *\fP, but is \fBchar *\fP to avoid +warnings in C code predating ANSI C. +.PP +When an empty string is used for \fImsgid\fP, the functions may return a +nonempty string. +.SH "SEE ALSO" +.BR ngettext (3), +.BR dngettext (3), +.BR dcngettext (3), +.BR setlocale (3), +.BR textdomain (3), +.BR bindtextdomain (3), +.BR bind_textdomain_codeset (3), +.BR msgfmt (1) diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/ngettext.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/ngettext.3 new file mode 100644 index 0000000000000000000000000000000000000000..93c5149fa750e4b8c418c4314c2aac971f785694 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/ngettext.3 @@ -0,0 +1,60 @@ +.\" Copyright (c) Bruno Haible +.\" +.\" This is free documentation; you can redistribute it and/or +.\" modify it under the terms of the GNU General Public License as +.\" published by the Free Software Foundation; either version 2 of +.\" the License, or (at your option) any later version. +.\" +.\" References consulted: +.\" GNU glibc-2 source code and manual +.\" GNU gettext source code and manual +.\" LI18NUX 2000 Globalization Specification +.\" +.TH NGETTEXT 3 "May 2001" "GNU gettext 0.25.1" +.SH NAME +ngettext, dngettext, dcngettext \- translate message and choose plural form +.SH SYNOPSIS +.nf +.B #include +.sp +.BI "char * ngettext (const char * " msgid ", const char * " msgid_plural , +.BI " unsigned long int " n ); +.BI "char * dngettext (const char * " domainname , +.BI " const char * " msgid ", const char * " msgid_plural , +.BI " unsigned long int " n ); +.BI "char * dcngettext (const char * " domainname , +.BI " const char * " msgid ", const char * " msgid_plural , +.BI " unsigned long int " n ", int " category ); +.fi +.SH DESCRIPTION +The \fBngettext\fP, \fBdngettext\fP and \fBdcngettext\fP functions attempt to +translate a text string into the user's native language, by looking up the +appropriate plural form of the translation in a message catalog. +.PP +Plural forms are grammatical variants depending on the a number. Some languages +have two forms, called singular and plural. Other languages have three forms, +called singular, dual and plural. There are also languages with four forms. +.PP +The \fBngettext\fP, \fBdngettext\fP and \fBdcngettext\fP functions work like +the \fBgettext\fP, \fBdgettext\fP and \fBdcgettext\fP functions, respectively. +Additionally, they choose the appropriate plural form, which depends on the +number \fIn\fP and the language of the message catalog where the translation +was found. +.PP +In the "C" locale, or if none of the used catalogs contain a translation for +\fImsgid\fP, the \fBngettext\fP, \fBdngettext\fP and \fBdcngettext\fP functions +return \fImsgid\fP if \fIn\fP == 1, or \fImsgid_plural\fP if \fIn\fP != 1. +.SH "RETURN VALUE" +If a translation was found in one of the specified catalogs, the appropriate +plural form is converted to the locale's codeset and returned. The resulting +string is statically allocated and must not be modified or freed. Otherwise +\fImsgid\fP or \fImsgid_plural\fP is returned, as described above. +.SH ERRORS +\fBerrno\fP is not modified. +.SH BUGS +The return type ought to be \fBconst char *\fP, but is \fBchar *\fP to avoid +warnings in C code predating ANSI C. +.SH "SEE ALSO" +.BR gettext (3), +.BR dgettext (3), +.BR dcgettext (3) diff --git a/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/textdomain.3 b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/textdomain.3 new file mode 100644 index 0000000000000000000000000000000000000000..54913874ef0a5988cfbe36704a3012925a91d9e7 --- /dev/null +++ b/miniconda3/pkgs/gettext-tools-0.25.1-h6a67909_0/share/man/man3/textdomain.3 @@ -0,0 +1,57 @@ +.\" Copyright (c) Bruno Haible +.\" +.\" This is free documentation; you can redistribute it and/or +.\" modify it under the terms of the GNU General Public License as +.\" published by the Free Software Foundation; either version 2 of +.\" the License, or (at your option) any later version. +.\" +.\" References consulted: +.\" GNU glibc-2 source code and manual +.\" GNU gettext source code and manual +.\" LI18NUX 2000 Globalization Specification +.\" +.TH TEXTDOMAIN 3 "May 2001" "GNU gettext 0.25.1" +.SH NAME +textdomain \- set domain for future gettext() calls +.SH SYNOPSIS +.nf +.B #include +.sp +.BI "char * textdomain (const char * " domainname ); +.fi +.SH DESCRIPTION +The \fBtextdomain\fP function sets or retrieves the current message domain. +.PP +A message domain is a set of translatable \fImsgid\fP messages. Usually, +every software package has its own message domain. The domain name is used +to determine the message catalog where a translation is looked up; it must +be a non-empty string. +.PP +The current message domain is used by the \fBgettext\fP, \fBngettext\fP +functions, and by the \fBdgettext\fP, \fBdcgettext\fP, \fBdngettext\fP and +\fBdcngettext\fP functions when called with a NULL domainname argument. +.PP +If \fIdomainname\fP is not NULL, the current message domain is set to +\fIdomainname\fP. The string the function stores internally is a copy of the +\fIdomainname\fP argument. +.PP +If \fIdomainname\fP is NULL, the function returns the current message domain. +.SH "RETURN VALUE" +If successful, the \fBtextdomain\fP function returns the current message +domain, after possibly changing it. The resulting string is valid until the +next \fBtextdomain\fP call and must not be modified or freed. If a memory +allocation failure occurs, it sets \fBerrno\fP to \fBENOMEM\fP and returns +NULL. +.SH ERRORS +The following error can occur, among others: +.TP +.B ENOMEM +Not enough memory available. +.SH BUGS +The return type ought to be \fBconst char *\fP, but is \fBchar *\fP to avoid +warnings in C code predating ANSI C. +.SH "SEE ALSO" +.BR gettext (3), +.BR ngettext (3), +.BR bindtextdomain (3), +.BR bind_textdomain_codeset (3) diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/about.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/about.json new file mode 100644 index 0000000000000000000000000000000000000000..b833428193cc0f58896295fb3429fec67bfb3204 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/about.json @@ -0,0 +1,160 @@ +{ + "channels": [ + "https://repo.anaconda.com/pkgs/main", + "https://repo.anaconda.com/pkgs/r", + "https://repo.anaconda.com/pkgs/r" + ], + "conda_build_version": "25.1.2", + "conda_version": "25.1.1", + "description": "h11 is an HTTP/1.1 protocol library written in Python, heavily inspired by\n[hyper-h2](https://hyper-h2.readthedocs.io/en/stable/).\n", + "dev_url": "https://github.com/python-hyper/h11", + "doc_url": "https://h11.readthedocs.io/", + "env_vars": { + "CIO_TEST": "" + }, + "extra": { + "copy_test_source_files": true, + "final": true, + "recipe-maintainers": [ + "carlodri" + ] + }, + "home": "https://github.com/python-hyper/h11", + "identifiers": [], + "keywords": [], + "license": "MIT", + "license_family": "MIT", + "license_file": "LICENSE.txt", + "root_pkgs": [ + "_libgcc_mutex 0.1 main", + "ca-certificates 2025.9.9 h06a4308_0", + "ld_impl_linux-64 2.40 h12ee557_0", + "libstdcxx-ng 11.2.0 h1234567_1", + "nlohmann_json 3.11.2 h6a678d5_0", + "pybind11-abi 5 hd3eb1b0_0", + "tzdata 2025a h04d1e81_0", + "libgomp 11.2.0 h1234567_1", + "_openmp_mutex 5.1 1_gnu", + "libgcc-ng 11.2.0 h1234567_1", + "bzip2 1.0.8 h5eee18b_6", + "c-ares 1.19.1 h5eee18b_0", + "cpp-expected 1.1.0 hdb19cb5_0", + "expat 2.6.4 h6a678d5_0", + "fmt 9.1.0 hdb19cb5_1", + "icu 73.1 h6a678d5_0", + "libev 4.33 h7f8727e_1", + "libffi 3.4.4 h6a678d5_1", + "libuuid 1.41.5 h5eee18b_0", + "lz4-c 1.9.4 h6a678d5_1", + "ncurses 6.4 h6a678d5_0", + "liblief 0.12.3 h6a678d5_0", + "reproc 14.2.4 h6a678d5_2", + "simdjson 3.10.1 hdb19cb5_0", + "xz 5.4.6 h5eee18b_1", + "yaml-cpp 0.8.0 h6a678d5_1", + "zlib 1.2.13 h5eee18b_1", + "libedit 3.1.20230828 h5eee18b_0", + "libnghttp2 1.57.0 h2d74bed_0", + "libssh2 1.11.1 h251f7ec_0", + "libxml2 2.13.5 hfdd30dd_0", + "pcre2 10.42 hebb0a14_1", + "readline 8.2 h5eee18b_0", + "reproc-cpp 14.2.4 h6a678d5_2", + "spdlog 1.11.0 hdb19cb5_0", + "tk 8.6.14 h39e8969_0", + "zstd 1.5.6 hc292b87_0", + "krb5 1.20.1 h143b758_1", + "libarchive 3.7.7 hfab0078_0", + "libsolv 0.7.30 he621ea3_1", + "sqlite 3.45.3 h5eee18b_0", + "libcurl 8.11.1 hc9e6f67_0", + "python 3.12.9 h5148396_0", + "libmamba 2.0.5 haf1ee3a_1", + "menuinst 2.2.0 py312h06a4308_1", + "anaconda-anon-usage 0.5.0 py312hfc0e8ea_100", + "annotated-types 0.6.0 py312h06a4308_0", + "archspec 0.2.3 pyhd3eb1b0_0", + "boltons 24.1.0 py312h06a4308_0", + "brotli-python 1.0.9 py312h6a678d5_9", + "charset-normalizer 3.3.2 pyhd3eb1b0_0", + "distro 1.9.0 py312h06a4308_0", + "frozendict 2.4.2 py312h06a4308_0", + "idna 3.7 py312h06a4308_0", + "jsonpointer 2.1 pyhd3eb1b0_0", + "libmambapy 2.0.5 py312hdb19cb5_1", + "mdurl 0.1.0 py312h06a4308_0", + "packaging 24.2 py312h06a4308_0", + "platformdirs 3.10.0 py312h06a4308_0", + "pluggy 1.5.0 py312h06a4308_0", + "pycosat 0.6.6 py312h5eee18b_2", + "pycparser 2.21 pyhd3eb1b0_0", + "pygments 2.15.1 py312h06a4308_1", + "pysocks 1.7.1 py312h06a4308_0", + "ruamel.yaml.clib 0.2.8 py312h5eee18b_0", + "setuptools 75.8.0 py312h06a4308_0", + "tqdm 4.67.1 py312he106c6f_0", + "truststore 0.10.0 py312h06a4308_0", + "typing_extensions 4.12.2 py312h06a4308_0", + "wheel 0.45.1 py312h06a4308_0", + "cffi 1.17.1 py312h1fdaa30_1", + "jsonpatch 1.33 py312h06a4308_1", + "markdown-it-py 2.2.0 py312h06a4308_1", + "pip 25.0 py312h06a4308_0", + "ruamel.yaml 0.18.6 py312h5eee18b_0", + "typing-extensions 4.12.2 py312h06a4308_0", + "urllib3 2.3.0 py312h06a4308_0", + "cryptography 43.0.3 py312h7825ff9_1", + "pydantic-core 2.27.1 py312h4aa5aa6_0", + "requests 2.32.3 py312h06a4308_1", + "rich 13.9.4 py312h06a4308_0", + "zstandard 0.23.0 py312h2c38b39_1", + "conda-content-trust 0.2.0 py312h06a4308_1", + "conda-package-streaming 0.11.0 py312h06a4308_0", + "pydantic 2.10.3 py312h06a4308_0", + "conda-package-handling 2.4.0 py312h06a4308_0", + "conda 25.1.1 py312h06a4308_0", + "conda-anaconda-tos 0.1.2 py312h06a4308_0", + "conda-libmamba-solver 25.1.1 pyhd3eb1b0_0", + "libsodium 1.0.20 heac8642_0", + "openssl 3.0.18 hd6dcaed_0", + "patch 2.8 hb25bd0a_0", + "patchelf 0.17.2 h6a678d5_0", + "yaml 0.2.5 h7b6447c_0", + "argcomplete 3.6.2 py312h06a4308_0", + "attrs 24.3.0 py312h06a4308_0", + "certifi 2025.8.3 py312h06a4308_0", + "chardet 5.2.0 py312h06a4308_0", + "click 8.2.1 py312h06a4308_0", + "filelock 3.17.0 py312h06a4308_0", + "jmespath 1.0.1 py312h06a4308_0", + "markupsafe 3.0.2 py312h5eee18b_0", + "more-itertools 10.3.0 py312h06a4308_0", + "pkginfo 1.12.0 py312h06a4308_0", + "psutil 7.0.0 py312hee96239_0", + "py-lief 0.12.3 py312h6a678d5_0", + "python-libarchive-c 5.1 pyhd3eb1b0_0", + "pytz 2025.2 py312h06a4308_0", + "pyyaml 6.0.2 py312h5eee18b_0", + "rpds-py 0.22.3 py312h4aa5aa6_0", + "six 1.17.0 py312h06a4308_0", + "soupsieve 2.5 py312h06a4308_0", + "tomlkit 0.13.2 py312h06a4308_0", + "xmltodict 0.14.2 py312h06a4308_0", + "jinja2 3.1.6 py312h06a4308_0", + "python-dateutil 2.9.0post0 py312h06a4308_2", + "referencing 0.30.2 py312h06a4308_0", + "yq 3.4.3 py312h06a4308_0", + "beautifulsoup4 4.13.5 py312h06a4308_0", + "botocore 1.37.10 py312h06a4308_0", + "jsonschema-specifications 2023.7.1 py312h06a4308_0", + "pynacl 1.5.0 py312h2630517_2", + "jsonschema 4.25.0 py312h06a4308_0", + "s3transfer 0.11.2 py312h06a4308_0", + "boto3 1.37.10 py312h06a4308_0", + "conda-anaconda-telemetry 0.3.0 pyhd3eb1b0_1", + "conda-index 0.5.0 py312h06a4308_0", + "conda-build 25.1.2 py312h06a4308_0" + ], + "summary": "A pure-Python HTTP/1.1 protocol library.", + "tags": [] +} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/files b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/files new file mode 100644 index 0000000000000000000000000000000000000000..bd0736d190f0056d1568e83a1b760e42d0fcc4d0 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/files @@ -0,0 +1,31 @@ +lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER +lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA +lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD +lib/python3.13/site-packages/h11-0.16.0.dist-info/REQUESTED +lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL +lib/python3.13/site-packages/h11-0.16.0.dist-info/direct_url.json +lib/python3.13/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt +lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt +lib/python3.13/site-packages/h11/__init__.py +lib/python3.13/site-packages/h11/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_abnf.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_connection.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_events.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_headers.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_readers.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_receivebuffer.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_state.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_util.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_version.cpython-313.pyc +lib/python3.13/site-packages/h11/__pycache__/_writers.cpython-313.pyc +lib/python3.13/site-packages/h11/_abnf.py +lib/python3.13/site-packages/h11/_connection.py +lib/python3.13/site-packages/h11/_events.py +lib/python3.13/site-packages/h11/_headers.py +lib/python3.13/site-packages/h11/_readers.py +lib/python3.13/site-packages/h11/_receivebuffer.py +lib/python3.13/site-packages/h11/_state.py +lib/python3.13/site-packages/h11/_util.py +lib/python3.13/site-packages/h11/_version.py +lib/python3.13/site-packages/h11/_writers.py +lib/python3.13/site-packages/h11/py.typed diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/git b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/git new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/hash_input.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/hash_input.json new file mode 100644 index 0000000000000000000000000000000000000000..54f8fb2da41bdb4962a008606b017773d2fef48e --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/hash_input.json @@ -0,0 +1,4 @@ +{ + "target_platform": "linux-64", + "channel_targets": "defaults" +} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/index.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/index.json new file mode 100644 index 0000000000000000000000000000000000000000..aa412311e376d91c49646696f405350f0be44d6a --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/index.json @@ -0,0 +1,16 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_1", + "build_number": 1, + "depends": [ + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "license": "MIT", + "license_family": "MIT", + "name": "h11", + "platform": "linux", + "subdir": "linux-64", + "timestamp": 1761931277052, + "version": "0.16.0" +} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/licenses/LICENSE.txt b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/licenses/LICENSE.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/paths.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/paths.json new file mode 100644 index 0000000000000000000000000000000000000000..40317b7e9ef60026166627746581175e8b944d72 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/paths.json @@ -0,0 +1,191 @@ +{ + "paths": [ + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER", + "path_type": "hardlink", + "sha256": "d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8", + "size_in_bytes": 5 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA", + "path_type": "hardlink", + "sha256": "28f326098ac09fcba79b8f180f96087c841fe2456215cb7b872a9c7d5cd19d64", + "size_in_bytes": 8348 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD", + "path_type": "hardlink", + "sha256": "01580ff527e9ec3d24bc0d0da050786060e64b7f7d37e0677fdefcfaeb0ed6e9", + "size_in_bytes": 2007 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/REQUESTED", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL", + "path_type": "hardlink", + "sha256": "ff309ddcdd65ebd02bc724dbf2bcc4a0ff53a5b61792a44548d383e4ebb19d3b", + "size_in_bytes": 91 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/direct_url.json", + "path_type": "hardlink", + "sha256": "49aa90e152aea0beab993875e6770e82721ba5c2c2807afcf2135abe57f37e61", + "size_in_bytes": 93 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt", + "path_type": "hardlink", + "sha256": "37db5bb85926db28a427a25867f10b1232003aea1be69ccb851138adb8e6f361", + "size_in_bytes": 1124 + }, + { + "_path": "lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt", + "path_type": "hardlink", + "sha256": "17b742e23977cde87c4c61c43da589acc6deba859b4b7efd1b0762f98bdd722b", + "size_in_bytes": 4 + }, + { + "_path": "lib/python3.13/site-packages/h11/__init__.py", + "path_type": "hardlink", + "sha256": "88ed4ace448ee36c99e9f7e0f953206f1fd9553586518d349d16045a7facde46", + "size_in_bytes": 1507 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "1cf022f2a2b63c592ff8c1d4c5532b75c80a5566911b3541c8ff0ec2370a0e23", + "size_in_bytes": 1032 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_abnf.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "9bc6ce8ffcec7b032b12bda2074a7c0c5816dd53f56e153ef3b45d65e41dafe4", + "size_in_bytes": 1724 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_connection.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "dcf87226c6a4b98ede64e1562dbc9d6cca2292f2642fa42092643767a10eb3e3", + "size_in_bytes": 22699 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_events.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "7d09d6486ece93e6f881f4684dd51e7dafe5d35d6e110d6f61dfa1b8f63a4a0d", + "size_in_bytes": 13104 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_headers.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "4d028cfbccdc194f902c6df9cd4a61ba1ef2d972c8034070ba9d2337e6b3dea4", + "size_in_bytes": 8004 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_readers.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "da9fb3c370d6907c8e110b49e5c2b8090718e8f4bdd038679e8e134dd09c5489", + "size_in_bytes": 9830 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_receivebuffer.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "1c3f5b0ad74b2cd175c6ec196da740773366b16f1c2eeb693de4f5e4828fdeb8", + "size_in_bytes": 4739 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_state.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "011ebd563e3a6e4b2fa1911d78cfdc358e60bf105471659696f10ce5ffb2d630", + "size_in_bytes": 8739 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_util.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "b85e8e7ec86853a1ea3bf2689847f47211276ef95c2f292ec84095623075fcbb", + "size_in_bytes": 4802 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_version.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "92f99323bb4ccfe26aaf36ea31c40245acbd9dfdb040d9d1751c377d8fff47d7", + "size_in_bytes": 170 + }, + { + "_path": "lib/python3.13/site-packages/h11/__pycache__/_writers.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "d1aa7e70a96fd66cb1d5e2a1353acab84a3eed83485fa88ebbb2ea17b56d554e", + "size_in_bytes": 6430 + }, + { + "_path": "lib/python3.13/site-packages/h11/_abnf.py", + "path_type": "hardlink", + "sha256": "c9b8b1af4c6cba99e403a18503232e6ee5c5e9373595bfe117cf743600ac7cd7", + "size_in_bytes": 4815 + }, + { + "_path": "lib/python3.13/site-packages/h11/_connection.py", + "path_type": "hardlink", + "sha256": "93d61155fea4a19a9bb6d056dfac5259a26959d6706bec50554f401c4a3d0ee2", + "size_in_bytes": 26863 + }, + { + "_path": "lib/python3.13/site-packages/h11/_events.py", + "path_type": "hardlink", + "sha256": "23deda5e86a5d56bbb7642f9e3c04034150290e21b7bec790a2a1803d201635e", + "size_in_bytes": 11792 + }, + { + "_path": "lib/python3.13/site-packages/h11/_headers.py", + "path_type": "hardlink", + "sha256": "3fb0fe9413711f074b64f2e29a6630acf1bef59923125bef25925d6408123fee", + "size_in_bytes": 10412 + }, + { + "_path": "lib/python3.13/site-packages/h11/_readers.py", + "path_type": "hardlink", + "sha256": "6b8472a4e454082dddd2afe4c4fb8120cee34c3f222ede57f754c7d05b1db8de", + "size_in_bytes": 8590 + }, + { + "_path": "lib/python3.13/site-packages/h11/_receivebuffer.py", + "path_type": "hardlink", + "sha256": "c6bb29b1db0d81617145f41c4d7c51f11add8d15d74cad08a39710616a49d56b", + "size_in_bytes": 5252 + }, + { + "_path": "lib/python3.13/site-packages/h11/_state.py", + "path_type": "hardlink", + "sha256": "ff92c6fc1191f0509c1507813c7f93307826ffe07e1147160a74287fff578c51", + "size_in_bytes": 13231 + }, + { + "_path": "lib/python3.13/site-packages/h11/_util.py", + "path_type": "hardlink", + "sha256": "2d69248d7c89685940cba2eddfdc3bdd44ad925153e68bdcbe8d13918ed162e9", + "size_in_bytes": 4888 + }, + { + "_path": "lib/python3.13/site-packages/h11/_version.py", + "path_type": "hardlink", + "sha256": "1954ac6cf48f0dc3ae17aa6d7c88979d52686849b7ca05db327aa5aff1a26a1c", + "size_in_bytes": 686 + }, + { + "_path": "lib/python3.13/site-packages/h11/_writers.py", + "path_type": "hardlink", + "sha256": "a052a6e8fb637877db8f844b5fb541eca0dcd60218e778171b7fc747d96d9930", + "size_in_bytes": 5081 + }, + { + "_path": "lib/python3.13/site-packages/h11/py.typed", + "path_type": "hardlink", + "sha256": "b28c3db284f03fd4ff80401049587b19bf3ce79874e0dc2686cd967be2518193", + "size_in_bytes": 7 + } + ], + "paths_version": 1 +} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/conda_build_config.yaml b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/conda_build_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f94879c7d8de974fd78154a92057c306826d4e8 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/conda_build_config.yaml @@ -0,0 +1,28 @@ +c_compiler: gcc +channel_targets: defaults +cpu_optimization_target: nocona +cran_mirror: https://cran.r-project.org +cxx_compiler: gxx +extend_keys: +- pin_run_as_build +- ignore_version +- ignore_build_only_deps +- extend_keys +fortran_compiler: gfortran +ignore_build_only_deps: +- python +- numpy +lua: '5' +numpy: '1.26' +perl: 5.26.2 +pin_run_as_build: + python: + max_pin: x.x + min_pin: x.x + r-base: + max_pin: x.x + min_pin: x.x +platform: linux-64 +python: '3.13' +r_base: '3.5' +target_platform: linux-64 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e8811de01b28ecbbb5a35c48e5d17964fa3be24b --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml @@ -0,0 +1,79 @@ +# This file created by conda-build 25.1.2 +# meta.yaml template originally from: +# /home/task_176193111687894/h11-feedstock/recipe, last modified Fri Oct 31 17:20:49 2025 +# ------------------------------------------------ + +package: + name: h11 + version: 0.16.0 +source: + sha256: 4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 + url: https://pypi.org/packages/source/h/h11/h11-0.16.0.tar.gz +build: + number: '1' + script: /home/task_176193111687894/conda-bld/h11_1761931259172/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pla/bin/python + -m pip install . -vv --no-deps --no-build-isolation + string: py313h06a4308_1 +requirements: + host: + - _libgcc_mutex 0.1 main + - _openmp_mutex 5.1 1_gnu + - bzip2 1.0.8 h5eee18b_6 + - ca-certificates 2025.9.9 h06a4308_0 + - expat 2.7.1 h6a678d5_0 + - ld_impl_linux-64 2.44 h153f514_2 + - libffi 3.4.4 h6a678d5_1 + - libgcc-ng 11.2.0 h1234567_1 + - libgomp 11.2.0 h1234567_1 + - libmpdec 4.0.0 h5eee18b_0 + - libstdcxx-ng 11.2.0 h1234567_1 + - libuuid 1.41.5 h5eee18b_0 + - libxcb 1.17.0 h9b100fa_0 + - libzlib 1.3.1 hb25bd0a_0 + - ncurses 6.5 h7934f7d_0 + - openssl 3.0.18 hd6dcaed_0 + - pip 25.2 pyhc872135_1 + - pthread-stubs 0.3 h0ce48e5_1 + - python 3.13.9 h7e8bc2b_100_cp313 + - python_abi 3.13 1_cp313 + - readline 8.3 hc2a1206_0 + - setuptools 80.9.0 py313h06a4308_0 + - sqlite 3.50.2 hb25bd0a_1 + - tk 8.6.15 h54e0aa7_0 + - tzdata 2025b h04d1e81_0 + - wheel 0.45.1 py313h06a4308_0 + - xorg-libx11 1.8.12 h9b100fa_1 + - xorg-libxau 1.0.12 h9b100fa_0 + - xorg-libxdmcp 1.1.5 h9b100fa_0 + - xorg-xorgproto 2024.1 h5eee18b_1 + - xz 5.6.4 h5eee18b_1 + - zlib 1.3.1 hb25bd0a_0 + run: + - python >=3.13,<3.14.0a0 + - python_abi 3.13.* *_cp313 +test: + commands: + - pip check + imports: + - h11 + requires: + - pip +about: + description: 'h11 is an HTTP/1.1 protocol library written in Python, heavily inspired + by + + [hyper-h2](https://hyper-h2.readthedocs.io/en/stable/). + + ' + dev_url: https://github.com/python-hyper/h11 + doc_url: https://h11.readthedocs.io/ + home: https://github.com/python-hyper/h11 + license: MIT + license_family: MIT + license_file: LICENSE.txt + summary: A pure-Python HTTP/1.1 protocol library. +extra: + copy_test_source_files: true + final: true + recipe-maintainers: + - carlodri diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml.template b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml.template new file mode 100644 index 0000000000000000000000000000000000000000..2f8d2073adc2d48ea3f59ace8a3b54c9022aad76 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/recipe/meta.yaml.template @@ -0,0 +1,48 @@ +{% set name = "h11" %} +{% set version = "0.16.0" %} + +package: + name: {{ name|lower }} + version: {{ version }} + +source: + url: https://pypi.org/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz + sha256: 4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 + +build: + skip: true # [py<38] + number: 1 + script: {{ PYTHON }} -m pip install . -vv --no-deps --no-build-isolation + +requirements: + host: + - python + - pip + - setuptools + run: + - python + - typing_extensions # [py<38] + +test: + imports: + - h11 + requires: + - pip + commands: + - pip check + +about: + home: https://github.com/python-hyper/h11 + license: MIT + license_family: MIT + license_file: LICENSE.txt + summary: A pure-Python HTTP/1.1 protocol library. + description: | + h11 is an HTTP/1.1 protocol library written in Python, heavily inspired by + [hyper-h2](https://hyper-h2.readthedocs.io/en/stable/). + doc_url: https://h11.readthedocs.io/ + dev_url: https://github.com/python-hyper/h11 + +extra: + recipe-maintainers: + - carlodri \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/repodata_record.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/repodata_record.json new file mode 100644 index 0000000000000000000000000000000000000000..a486c00aadd5593dc5ad58db083e400c67b40bc0 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/repodata_record.json @@ -0,0 +1,23 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_1", + "build_number": 1, + "channel": "https://repo.anaconda.com/pkgs/main/linux-64/", + "constrains": [], + "depends": [ + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "fn": "h11-0.16.0-py313h06a4308_1.conda", + "license": "MIT", + "license_family": "MIT", + "md5": "64c98017f4f5b701ed2b2f20d5e9ea4c", + "name": "h11", + "platform": "linux", + "sha256": "96dcaec2513ff1034fc52b8b13e5500d41b05671d85f8bff24895bf807129812", + "size": 64750, + "subdir": "linux-64", + "timestamp": 1761931277000, + "url": "https://repo.anaconda.com/pkgs/main/linux-64/h11-0.16.0-py313h06a4308_1.conda", + "version": "0.16.0" +} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.py new file mode 100644 index 0000000000000000000000000000000000000000..03bf5ef439501afc5fea1f8ff8cff4416959ca97 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.py @@ -0,0 +1,3 @@ +print("import: 'h11'") +import h11 + diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.sh b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1afc6b862fab8658b14cb4cc0345a4ee1f02ad0e --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/run_test.sh @@ -0,0 +1,8 @@ + + +set -ex + + + +pip check +exit 0 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/test_time_dependencies.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/test_time_dependencies.json new file mode 100644 index 0000000000000000000000000000000000000000..215362c1832b66eb448cdeeadbb1db3470d5adb4 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/info/test/test_time_dependencies.json @@ -0,0 +1 @@ +["pip"] \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8a2f639061cc4a203f7109d8335d28076442c61d --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/METADATA @@ -0,0 +1,202 @@ +Metadata-Version: 2.4 +Name: h11 +Version: 0.16.0 +Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1 +Home-page: https://github.com/python-hyper/h11 +Author: Nathaniel J. Smith +Author-email: njs@pobox.com +License: MIT +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: System :: Networking +Requires-Python: >=3.8 +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +h11 +=== + +.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master + :target: https://travis-ci.org/python-hyper/h11 + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-hyper/h11 + :alt: Test coverage + +.. image:: https://readthedocs.org/projects/h11/badge/?version=latest + :target: http://h11.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +This is a little HTTP/1.1 library written from scratch in Python, +heavily inspired by `hyper-h2 `_. + +It's a "bring-your-own-I/O" library; h11 contains no IO code +whatsoever. This means you can hook h11 up to your favorite network +API, and that could be anything you want: synchronous, threaded, +asynchronous, or your own implementation of `RFC 6214 +`_ -- h11 won't judge you. +(Compare this to the current state of the art, where every time a `new +network API `_ comes along then someone +gets to start over reimplementing the entire HTTP protocol from +scratch.) Cory Benfield made an `excellent blog post describing the +benefits of this approach +`_, or if you like video +then here's his `PyCon 2016 talk on the same theme +`_. + +This also means that h11 is not immediately useful out of the box: +it's a toolkit for building programs that speak HTTP, not something +that could directly replace ``requests`` or ``twisted.web`` or +whatever. But h11 makes it much easier to implement something like +``requests`` or ``twisted.web``. + +At a high level, working with h11 goes like this: + +1) First, create an ``h11.Connection`` object to track the state of a + single HTTP/1.1 connection. + +2) When you read data off the network, pass it to + ``conn.receive_data(...)``; you'll get back a list of objects + representing high-level HTTP "events". + +3) When you want to send a high-level HTTP event, create the + corresponding "event" object and pass it to ``conn.send(...)``; + this will give you back some bytes that you can then push out + through the network. + +For example, a client might instantiate and then send a +``h11.Request`` object, then zero or more ``h11.Data`` objects for the +request body (e.g., if this is a POST), and then a +``h11.EndOfMessage`` to indicate the end of the message. Then the +server would then send back a ``h11.Response``, some ``h11.Data``, and +its own ``h11.EndOfMessage``. If either side violates the protocol, +you'll get a ``h11.ProtocolError`` exception. + +h11 is suitable for implementing both servers and clients, and has a +pleasantly symmetric API: the events you send as a client are exactly +the ones that you receive as a server and vice-versa. + +`Here's an example of a tiny HTTP client +`_ + +It also has `a fine manual `_. + +FAQ +--- + +*Whyyyyy?* + +I wanted to play with HTTP in `Curio +`__ and `Trio +`__, which at the time didn't have any +HTTP libraries. So I thought, no big deal, Python has, like, a dozen +different implementations of HTTP, surely I can find one that's +reusable. I didn't find one, but I did find Cory's call-to-arms +blog-post. So I figured, well, fine, if I have to implement HTTP from +scratch, at least I can make sure no-one *else* has to ever again. + +*Should I use it?* + +Maybe. You should be aware that it's a very young project. But, it's +feature complete and has an exhaustive test-suite and complete docs, +so the next step is for people to try using it and see how it goes +:-). If you do then please let us know -- if nothing else we'll want +to talk to you before making any incompatible changes! + +*What are the features/limitations?* + +Roughly speaking, it's trying to be a robust, complete, and non-hacky +implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230: +HTTP/1.1 Message Syntax and Routing +`_. That is, it mostly focuses on +implementing HTTP at the level of taking bytes on and off the wire, +and the headers related to that, and tries to be anal about spec +conformance. It doesn't know about higher-level concerns like URL +routing, conditional GETs, cross-origin cookie policies, or content +negotiation. But it does know how to take care of framing, +cross-version differences in keep-alive handling, and the "obsolete +line folding" rule, so you can focus your energies on the hard / +interesting parts for your application, and it tries to support the +full specification in the sense that any useful HTTP/1.1 conformant +application should be able to use h11. + +It's pure Python, and has no dependencies outside of the standard +library. + +It has a test suite with 100.0% coverage for both statements and +branches. + +Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3. +The last Python 2-compatible version was h11 0.11.x. +(Originally it had a Cython wrapper for `http-parser +`_ and a beautiful nested state +machine implemented with ``yield from`` to postprocess the output. But +I had to take these out -- the new *parser* needs fewer lines-of-code +than the old *parser wrapper*, is written in pure Python, uses no +exotic language syntax, and has more features. It's sad, really; that +old state machine was really slick. I just need a few sentences here +to mourn that.) + +I don't know how fast it is. I haven't benchmarked or profiled it yet, +so it's probably got a few pointless hot spots, and I've been trying +to err on the side of simplicity and robustness instead of +micro-optimization. But at the architectural level I tried hard to +avoid fundamentally bad decisions, e.g., I believe that all the +parsing algorithms remain linear-time even in the face of pathological +input like slowloris, and there are no byte-by-byte loops. (I also +believe that it maintains bounded memory usage in the face of +arbitrary/pathological input.) + +The whole library is ~800 lines-of-code. You can read and understand +the whole thing in less than an hour. Most of the energy invested in +this so far has been spent on trying to keep things simple by +minimizing special-cases and ad hoc state manipulation; even though it +is now quite small and simple, I'm still annoyed that I haven't +figured out how to make it even smaller and simpler. (Unfortunately, +HTTP does not lend itself to simplicity.) + +The API is ~feature complete and I don't expect the general outlines +to change much, but you can't judge an API's ergonomics until you +actually document and use it, so I'd expect some changes in the +details. + +*How do I try it?* + +.. code-block:: sh + + $ pip install h11 + $ git clone git@github.com:python-hyper/h11 + $ cd h11/examples + $ python basic-client.py + +and go from there. + +*License?* + +MIT + +*Code of conduct?* + +Contributors are requested to follow our `code of conduct +`_ in +all project spaces. diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d0d15813664707907e70e1875b4daa68651b58c5 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/RECORD @@ -0,0 +1,31 @@ +h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348 +h11-0.16.0.dist-info/RECORD,, +h11-0.16.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +h11-0.16.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +h11-0.16.0.dist-info/direct_url.json,sha256=SaqQ4VKuoL6rmTh15ncOgnIbpcLCgHr88hNavlfzfmE,93 +h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124 +h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4 +h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507 +h11/__pycache__/__init__.cpython-313.pyc,, +h11/__pycache__/_abnf.cpython-313.pyc,, +h11/__pycache__/_connection.cpython-313.pyc,, +h11/__pycache__/_events.cpython-313.pyc,, +h11/__pycache__/_headers.cpython-313.pyc,, +h11/__pycache__/_readers.cpython-313.pyc,, +h11/__pycache__/_receivebuffer.cpython-313.pyc,, +h11/__pycache__/_state.cpython-313.pyc,, +h11/__pycache__/_util.cpython-313.pyc,, +h11/__pycache__/_version.cpython-313.pyc,, +h11/__pycache__/_writers.cpython-313.pyc,, +h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815 +h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863 +h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792 +h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412 +h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590 +h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252 +h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231 +h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888 +h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686 +h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081 +h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/REQUESTED b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/direct_url.json b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8a29e9cc165619ab5e23aa7da5c0f8dd3d2b5a --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176193111687894/conda-bld/h11_1761931259172/work"} \ No newline at end of file diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d24def711344ec6f4da2108f7d5c9261eb35f8b --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11-0.16.0.dist-info/top_level.txt @@ -0,0 +1 @@ +h11 diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/__init__.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..989e92c3458681a6f0be72ae4105ea742750d328 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/__init__.py @@ -0,0 +1,62 @@ +# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230), +# containing no networking code at all, loosely modelled on hyper-h2's generic +# implementation of HTTP/2 (and in particular the h2.connection.H2Connection +# class). There's still a bunch of subtle details you need to get right if you +# want to make this actually useful, because it doesn't implement all the +# semantics to check that what you're asking to write to the wire is sensible, +# but at least it gets you out of dealing with the wire itself. + +from h11._connection import Connection, NEED_DATA, PAUSED +from h11._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from h11._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError +from h11._version import __version__ + +PRODUCT_ID = "python-h11/" + __version__ + + +__all__ = ( + "Connection", + "NEED_DATA", + "PAUSED", + "ConnectionClosed", + "Data", + "EndOfMessage", + "Event", + "InformationalResponse", + "Request", + "Response", + "CLIENT", + "CLOSED", + "DONE", + "ERROR", + "IDLE", + "MUST_CLOSE", + "SEND_BODY", + "SEND_RESPONSE", + "SERVER", + "SWITCHED_PROTOCOL", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", +) diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_abnf.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_abnf.py new file mode 100644 index 0000000000000000000000000000000000000000..933587fba22290d7eb7df4c88e12f1e61702b8ce --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_abnf.py @@ -0,0 +1,132 @@ +# We use native strings for all the re patterns, to take advantage of string +# formatting, and then convert to bytestrings when compiling the final re +# objects. + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace +# OWS = *( SP / HTAB ) +# ; optional whitespace +OWS = r"[ \t]*" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators +# token = 1*tchar +# +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" +# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" +# / DIGIT / ALPHA +# ; any VCHAR, except delimiters +token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields +# field-name = token +field_name = token + +# The standard says: +# +# field-value = *( field-content / obs-fold ) +# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] +# field-vchar = VCHAR / obs-text +# obs-fold = CRLF 1*( SP / HTAB ) +# ; obsolete line folding +# ; see Section 3.2.4 +# +# https://tools.ietf.org/html/rfc5234#appendix-B.1 +# +# VCHAR = %x21-7E +# ; visible (printing) characters +# +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string +# obs-text = %x80-FF +# +# However, the standard definition of field-content is WRONG! It disallows +# fields containing a single visible character surrounded by whitespace, +# e.g. "foo a bar". +# +# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 +# +# So our definition of field_content attempts to fix it up... +# +# Also, we allow lots of control characters, because apparently people assume +# that they're legal in practice (e.g., google analytics makes cookies with +# \x01 in them!): +# https://github.com/python-hyper/h11/issues/57 +# We still don't allow NUL or whitespace, because those are often treated as +# meta-characters and letting them through can lead to nasty issues like SSRF. +vchar = r"[\x21-\x7e]" +vchar_or_obs_text = r"[^\x00\s]" +field_vchar = vchar_or_obs_text +field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals()) + +# We handle obs-fold at a different level, and our fixed-up field_content +# already grows to swallow the whole value, so ? instead of * +field_value = r"({field_content})?".format(**globals()) + +# header-field = field-name ":" OWS field-value OWS +header_field = ( + r"(?P{field_name})" + r":" + r"{OWS}" + r"(?P{field_value})" + r"{OWS}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line +# +# request-line = method SP request-target SP HTTP-version CRLF +# method = token +# HTTP-version = HTTP-name "/" DIGIT "." DIGIT +# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive +# +# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full +# URL, host+port (for connect), or even "*", but in any case we are guaranteed +# that it contists of the visible printing characters. +method = token +request_target = r"{vchar}+".format(**globals()) +http_version = r"HTTP/(?P[0-9]\.[0-9])" +request_line = ( + r"(?P{method})" + r" " + r"(?P{request_target})" + r" " + r"{http_version}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line +# +# status-line = HTTP-version SP status-code SP reason-phrase CRLF +# status-code = 3DIGIT +# reason-phrase = *( HTAB / SP / VCHAR / obs-text ) +status_code = r"[0-9]{3}" +reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals()) +status_line = ( + r"{http_version}" + r" " + r"(?P{status_code})" + # However, there are apparently a few too many servers out there that just + # leave out the reason phrase: + # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 + # https://github.com/seanmonstar/httparse/issues/29 + # so make it optional. ?: is a non-capturing group. + r"(?: (?P{reason_phrase}))?".format(**globals()) +) + +HEXDIG = r"[0-9A-Fa-f]" +# Actually +# +# chunk-size = 1*HEXDIG +# +# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20 +chunk_size = r"({HEXDIG}){{1,20}}".format(**globals()) +# Actually +# +# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) +# +# but we aren't parsing the things so we don't really care. +chunk_ext = r";.*" +chunk_header = ( + r"(?P{chunk_size})" + r"(?P{chunk_ext})?" + r"{OWS}\r\n".format( + **globals() + ) # Even though the specification does not allow for extra whitespaces, + # we are lenient with trailing whitespaces because some servers on the wild use it. +) diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_connection.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..e37d82a82a882c072cb938a90eb4486b51cdad99 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_connection.py @@ -0,0 +1,659 @@ +# This contains the main Connection class. Everything in h11 revolves around +# this. +from typing import ( + Any, + Callable, + cast, + Dict, + List, + Optional, + overload, + Tuple, + Type, + Union, +) + +from ._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from ._headers import get_comma_header, has_expect_100_continue, set_comma_header +from ._readers import READERS, ReadersType +from ._receivebuffer import ReceiveBuffer +from ._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + ConnectionState, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + SEND_BODY, + SERVER, + SWITCHED_PROTOCOL, +) +from ._util import ( # Import the internal things we need + LocalProtocolError, + RemoteProtocolError, + Sentinel, +) +from ._writers import WRITERS, WritersType + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = ["Connection", "NEED_DATA", "PAUSED"] + + +class NEED_DATA(Sentinel, metaclass=Sentinel): + pass + + +class PAUSED(Sentinel, metaclass=Sentinel): + pass + + +# If we ever have this much buffered without it making a complete parseable +# event, we error out. The only time we really buffer is when reading the +# request/response line + headers together, so this is effectively the limit on +# the size of that. +# +# Some precedents for defaults: +# - node.js: 80 * 1024 +# - tomcat: 8 * 1024 +# - IIS: 16 * 1024 +# - Apache: <8 KiB per line> +DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024 + + +# RFC 7230's rules for connection lifecycles: +# - If either side says they want to close the connection, then the connection +# must close. +# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close +# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive +# (and even this is a mess -- e.g. if you're implementing a proxy then +# sending Connection: keep-alive is forbidden). +# +# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So +# our rule is: +# - If someone says Connection: close, we will close +# - If someone uses HTTP/1.0, we will close. +def _keep_alive(event: Union[Request, Response]) -> bool: + connection = get_comma_header(event.headers, b"connection") + if b"close" in connection: + return False + if getattr(event, "http_version", b"1.1") < b"1.1": + return False + return True + + +def _body_framing( + request_method: bytes, event: Union[Request, Response] +) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: + # Called when we enter SEND_BODY to figure out framing information for + # this body. + # + # These are the only two events that can trigger a SEND_BODY state: + assert type(event) in (Request, Response) + # Returns one of: + # + # ("content-length", count) + # ("chunked", ()) + # ("http/1.0", ()) + # + # which are (lookup key, *args) for constructing body reader/writer + # objects. + # + # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 + # + # Step 1: some responses always have an empty body, regardless of what the + # headers say. + if type(event) is Response: + if ( + event.status_code in (204, 304) + or request_method == b"HEAD" + or (request_method == b"CONNECT" and 200 <= event.status_code < 300) + ): + return ("content-length", (0,)) + # Section 3.3.3 also lists another case -- responses with status_code + # < 200. For us these are InformationalResponses, not Responses, so + # they can't get into this function in the first place. + assert event.status_code >= 200 + + # Step 2: check for Transfer-Encoding (T-E beats C-L): + transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") + if transfer_encodings: + assert transfer_encodings == [b"chunked"] + return ("chunked", ()) + + # Step 3: check for Content-Length + content_lengths = get_comma_header(event.headers, b"content-length") + if content_lengths: + return ("content-length", (int(content_lengths[0]),)) + + # Step 4: no applicable headers; fallback/default depends on type + if type(event) is Request: + return ("content-length", (0,)) + else: + return ("http/1.0", ()) + + +################################################################ +# +# The main Connection class +# +################################################################ + + +class Connection: + """An object encapsulating the state of an HTTP connection. + + Args: + our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If + you're implementing a server, pass :data:`h11.SERVER`. + + max_incomplete_event_size (int): + The maximum number of bytes we're willing to buffer of an + incomplete event. In practice this mostly sets a limit on the + maximum size of the request/response line + headers. If this is + exceeded, then :meth:`next_event` will raise + :exc:`RemoteProtocolError`. + + """ + + def __init__( + self, + our_role: Type[Sentinel], + max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, + ) -> None: + self._max_incomplete_event_size = max_incomplete_event_size + # State and role tracking + if our_role not in (CLIENT, SERVER): + raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") + self.our_role = our_role + self.their_role: Type[Sentinel] + if our_role is CLIENT: + self.their_role = SERVER + else: + self.their_role = CLIENT + self._cstate = ConnectionState() + + # Callables for converting data->events or vice-versa given the + # current state + self._writer = self._get_io_object(self.our_role, None, WRITERS) + self._reader = self._get_io_object(self.their_role, None, READERS) + + # Holds any unprocessed received data + self._receive_buffer = ReceiveBuffer() + # If this is true, then it indicates that the incoming connection was + # closed *after* the end of whatever's in self._receive_buffer: + self._receive_buffer_closed = False + + # Extra bits of state that don't fit into the state machine. + # + # These two are only used to interpret framing headers for figuring + # out how to read/write response bodies. their_http_version is also + # made available as a convenient public API. + self.their_http_version: Optional[bytes] = None + self._request_method: Optional[bytes] = None + # This is pure flow-control and doesn't at all affect the set of legal + # transitions, so no need to bother ConnectionState with it: + self.client_is_waiting_for_100_continue = False + + @property + def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: + """A dictionary like:: + + {CLIENT: , SERVER: } + + See :ref:`state-machine` for details. + + """ + return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: + """The current state of whichever role we are NOT playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.their_role] + + @property + def they_are_waiting_for_100_continue(self) -> bool: + return self.their_role is CLIENT and self.client_is_waiting_for_100_continue + + def start_next_cycle(self) -> None: + """Attempt to reset our connection state for a new request/response + cycle. + + If both client and server are in :data:`DONE` state, then resets them + both to :data:`IDLE` state in preparation for a new request/response + cycle on this same connection. Otherwise, raises a + :exc:`LocalProtocolError`. + + See :ref:`keepalive-and-pipelining`. + + """ + old_states = dict(self._cstate.states) + self._cstate.start_next_cycle() + self._request_method = None + # self.their_http_version gets left alone, since it presumably lasts + # beyond a single request/response cycle + assert not self.client_is_waiting_for_100_continue + self._respond_to_state_changes(old_states) + + def _process_error(self, role: Type[Sentinel]) -> None: + old_states = dict(self._cstate.states) + self._cstate.process_error(role) + self._respond_to_state_changes(old_states) + + def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: + if type(event) is InformationalResponse and event.status_code == 101: + return _SWITCH_UPGRADE + if type(event) is Response: + if ( + _SWITCH_CONNECT in self._cstate.pending_switch_proposals + and 200 <= event.status_code < 300 + ): + return _SWITCH_CONNECT + return None + + # All events go through here + def _process_event(self, role: Type[Sentinel], event: Event) -> None: + # First, pass the event through the state machine to make sure it + # succeeds. + old_states = dict(self._cstate.states) + if role is CLIENT and type(event) is Request: + if event.method == b"CONNECT": + self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) + if get_comma_header(event.headers, b"upgrade"): + self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) + server_switch_event = None + if role is SERVER: + server_switch_event = self._server_switch_event(event) + self._cstate.process_event(role, type(event), server_switch_event) + + # Then perform the updates triggered by it. + + if type(event) is Request: + self._request_method = event.method + + if role is self.their_role and type(event) in ( + Request, + Response, + InformationalResponse, + ): + event = cast(Union[Request, Response, InformationalResponse], event) + self.their_http_version = event.http_version + + # Keep alive handling + # + # RFC 7230 doesn't really say what one should do if Connection: close + # shows up on a 1xx InformationalResponse. I think the idea is that + # this is not supposed to happen. In any case, if it does happen, we + # ignore it. + if type(event) in (Request, Response) and not _keep_alive( + cast(Union[Request, Response], event) + ): + self._cstate.process_keep_alive_disabled() + + # 100-continue + if type(event) is Request and has_expect_100_continue(event): + self.client_is_waiting_for_100_continue = True + if type(event) in (InformationalResponse, Response): + self.client_is_waiting_for_100_continue = False + if role is CLIENT and type(event) in (Data, EndOfMessage): + self.client_is_waiting_for_100_continue = False + + self._respond_to_state_changes(old_states, event) + + def _get_io_object( + self, + role: Type[Sentinel], + event: Optional[Event], + io_dict: Union[ReadersType, WritersType], + ) -> Optional[Callable[..., Any]]: + # event may be None; it's only used when entering SEND_BODY + state = self._cstate.states[role] + if state is SEND_BODY: + # Special case: the io_dict has a dict of reader/writer factories + # that depend on the request/response framing. + framing_type, args = _body_framing( + cast(bytes, self._request_method), cast(Union[Request, Response], event) + ) + return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] + else: + # General case: the io_dict just has the appropriate reader/writer + # for this state + return io_dict.get((role, state)) # type: ignore[return-value] + + # This must be called after any action that might have caused + # self._cstate.states to change. + def _respond_to_state_changes( + self, + old_states: Dict[Type[Sentinel], Type[Sentinel]], + event: Optional[Event] = None, + ) -> None: + # Update reader/writer + if self.our_state != old_states[self.our_role]: + self._writer = self._get_io_object(self.our_role, event, WRITERS) + if self.their_state != old_states[self.their_role]: + self._reader = self._get_io_object(self.their_role, event, READERS) + + @property + def trailing_data(self) -> Tuple[bytes, bool]: + """Data that has been received, but not yet processed, represented as + a tuple with two elements, where the first is a byte-string containing + the unprocessed data itself, and the second is a bool that is True if + the receive connection was closed. + + See :ref:`switching-protocols` for discussion of why you'd want this. + """ + return (bytes(self._receive_buffer), self._receive_buffer_closed) + + def receive_data(self, data: bytes) -> None: + """Add data to our internal receive buffer. + + This does not actually do any processing on the data, just stores + it. To trigger processing, you have to call :meth:`next_event`. + + Args: + data (:term:`bytes-like object`): + The new data that was just received. + + Special case: If *data* is an empty byte-string like ``b""``, + then this indicates that the remote side has closed the + connection (end of file). Normally this is convenient, because + standard Python APIs like :meth:`file.read` or + :meth:`socket.recv` use ``b""`` to indicate end-of-file, while + other failures to read are indicated using other mechanisms + like raising :exc:`TimeoutError`. When using such an API you + can just blindly pass through whatever you get from ``read`` + to :meth:`receive_data`, and everything will work. + + But, if you have an API where reading an empty string is a + valid non-EOF condition, then you need to be aware of this and + make sure to check for such strings and avoid passing them to + :meth:`receive_data`. + + Returns: + Nothing, but after calling this you should call :meth:`next_event` + to parse the newly received data. + + Raises: + RuntimeError: + Raised if you pass an empty *data*, indicating EOF, and then + pass a non-empty *data*, indicating more data that somehow + arrived after the EOF. + + (Calling ``receive_data(b"")`` multiple times is fine, + and equivalent to calling it once.) + + """ + if data: + if self._receive_buffer_closed: + raise RuntimeError("received close, then received more data?") + self._receive_buffer += data + else: + self._receive_buffer_closed = True + + def _extract_next_receive_event( + self, + ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + state = self.their_state + # We don't pause immediately when they enter DONE, because even in + # DONE state we can still process a ConnectionClosed() event. But + # if we have data in our buffer, then we definitely aren't getting + # a ConnectionClosed() immediately and we need to pause. + if state is DONE and self._receive_buffer: + return PAUSED + if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: + return PAUSED + assert self._reader is not None + event = self._reader(self._receive_buffer) + if event is None: + if not self._receive_buffer and self._receive_buffer_closed: + # In some unusual cases (basically just HTTP/1.0 bodies), EOF + # triggers an actual protocol event; in that case, we want to + # return that event, and then the state will change and we'll + # get called again to generate the actual ConnectionClosed(). + if hasattr(self._reader, "read_eof"): + event = self._reader.read_eof() + else: + event = ConnectionClosed() + if event is None: + event = NEED_DATA + return event # type: ignore[no-any-return] + + def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + """Parse the next event out of our receive buffer, update our internal + state, and return it. + + This is a mutating operation -- think of it like calling :func:`next` + on an iterator. + + Returns: + : One of three things: + + 1) An event object -- see :ref:`events`. + + 2) The special constant :data:`NEED_DATA`, which indicates that + you need to read more data from your socket and pass it to + :meth:`receive_data` before this method will be able to return + any more events. + + 3) The special constant :data:`PAUSED`, which indicates that we + are not in a state where we can process incoming data (usually + because the peer has finished their part of the current + request/response cycle, and you have not yet called + :meth:`start_next_cycle`). See :ref:`flow-control` for details. + + Raises: + RemoteProtocolError: + The peer has misbehaved. You should close the connection + (possibly after sending some kind of 4xx response). + + Once this method returns :class:`ConnectionClosed` once, then all + subsequent calls will also return :class:`ConnectionClosed`. + + If this method raises any exception besides :exc:`RemoteProtocolError` + then that's a bug -- if it happens please file a bug report! + + If this method raises any exception then it also sets + :attr:`Connection.their_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + + if self.their_state is ERROR: + raise RemoteProtocolError("Can't receive data when peer state is ERROR") + try: + event = self._extract_next_receive_event() + if event not in [NEED_DATA, PAUSED]: + self._process_event(self.their_role, cast(Event, event)) + if event is NEED_DATA: + if len(self._receive_buffer) > self._max_incomplete_event_size: + # 431 is "Request header fields too large" which is pretty + # much the only situation where we can get here + raise RemoteProtocolError( + "Receive buffer too long", error_status_hint=431 + ) + if self._receive_buffer_closed: + # We're still trying to complete some event, but that's + # never going to happen because no more data is coming + raise RemoteProtocolError("peer unexpectedly closed connection") + return event + except BaseException as exc: + self._process_error(self.their_role) + if isinstance(exc, LocalProtocolError): + exc._reraise_as_remote_protocol_error() + else: + raise + + @overload + def send(self, event: ConnectionClosed) -> None: + ... + + @overload + def send( + self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] + ) -> bytes: + ... + + @overload + def send(self, event: Event) -> Optional[bytes]: + ... + + def send(self, event: Event) -> Optional[bytes]: + """Convert a high-level event into bytes that can be sent to the peer, + while updating our internal state machine. + + Args: + event: The :ref:`event ` to send. + + Returns: + If ``type(event) is ConnectionClosed``, then returns + ``None``. Otherwise, returns a :term:`bytes-like object`. + + Raises: + LocalProtocolError: + Sending this event at this time would violate our + understanding of the HTTP/1.1 protocol. + + If this method raises any exception then it also sets + :attr:`Connection.our_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + data_list = self.send_with_data_passthrough(event) + if data_list is None: + return None + else: + return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where + :meth:`send` returns a single :term:`bytes-like object`, this instead + returns a list of them -- and when sending a :class:`Data` event, this + list is guaranteed to contain the exact object you passed in as + :attr:`Data.data`. See :ref:`sendfile` for discussion. + + """ + if self.our_state is ERROR: + raise LocalProtocolError("Can't send data when our state is ERROR") + try: + if type(event) is Response: + event = self._clean_up_response_headers_for_sending(event) + # We want to call _process_event before calling the writer, + # because if someone tries to do something invalid then this will + # give a sensible error message, while our writers all just assume + # they will only receive valid events. But, _process_event might + # change self._writer. So we have to do a little dance: + writer = self._writer + self._process_event(self.our_role, event) + if type(event) is ConnectionClosed: + return None + else: + # In any situation where writer is None, process_event should + # have raised ProtocolError + assert writer is not None + data_list: List[bytes] = [] + writer(event, data_list.append) + return data_list + except: + self._process_error(self.our_role) + raise + + def send_failed(self) -> None: + """Notify the state machine that we failed to send the data it gave + us. + + This causes :attr:`Connection.our_state` to immediately become + :data:`ERROR` -- see :ref:`error-handling` for discussion. + + """ + self._process_error(self.our_role) + + # When sending a Response, we take responsibility for a few things: + # + # - Sometimes you MUST set Connection: close. We take care of those + # times. (You can also set it yourself if you want, and if you do then + # we'll respect that and close the connection at the right time. But you + # don't have to worry about that unless you want to.) + # + # - The user has to set Content-Length if they want it. Otherwise, for + # responses that have bodies (e.g. not HEAD), then we will automatically + # select the right mechanism for streaming a body of unknown length, + # which depends on depending on the peer's HTTP version. + # + # This function's *only* responsibility is making sure headers are set up + # right -- everything downstream just looks at the headers. There are no + # side channels. + def _clean_up_response_headers_for_sending(self, response: Response) -> Response: + assert type(response) is Response + + headers = response.headers + need_close = False + + # HEAD requests need some special handling: they always act like they + # have Content-Length: 0, and that's how _body_framing treats + # them. But their headers are supposed to match what we would send if + # the request was a GET. (Technically there is one deviation allowed: + # we're allowed to leave out the framing headers -- see + # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as + # easy to get them right.) + method_for_choosing_headers = cast(bytes, self._request_method) + if method_for_choosing_headers == b"HEAD": + method_for_choosing_headers = b"GET" + framing_type, _ = _body_framing(method_for_choosing_headers, response) + if framing_type in ("chunked", "http/1.0"): + # This response has a body of unknown length. + # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked + # If our peer is HTTP/1.0, we use no framing headers, and close the + # connection afterwards. + # + # Make sure to clear Content-Length (in principle user could have + # set both and then we ignored Content-Length b/c + # Transfer-Encoding overwrote it -- this would be naughty of them, + # but the HTTP spec says that if our peer does this then we have + # to fix it instead of erroring out, so we'll accord the user the + # same respect). + headers = set_comma_header(headers, b"content-length", []) + if self.their_http_version is None or self.their_http_version < b"1.1": + # Either we never got a valid request and are sending back an + # error (their_http_version is None), so we assume the worst; + # or else we did get a valid HTTP/1.0 request, so we know that + # they don't understand chunked encoding. + headers = set_comma_header(headers, b"transfer-encoding", []) + # This is actually redundant ATM, since currently we + # unconditionally disable keep-alive when talking to HTTP/1.0 + # peers. But let's be defensive just in case we add + # Connection: keep-alive support later: + if self._request_method != b"HEAD": + need_close = True + else: + headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"]) + + if not self._cstate.keep_alive or need_close: + # Make sure Connection: close is set + connection = set(get_comma_header(headers, b"connection")) + connection.discard(b"keep-alive") + connection.add(b"close") + headers = set_comma_header(headers, b"connection", sorted(connection)) + + return Response( + headers=headers, + status_code=response.status_code, + http_version=response.http_version, + reason=response.reason, + ) diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_events.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_events.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1c3adbde2c4e7710482a18e3471f91f1da610e --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_events.py @@ -0,0 +1,369 @@ +# High level events that make up HTTP/1.1 conversations. Loosely inspired by +# the corresponding events in hyper-h2: +# +# http://python-hyper.org/h2/en/stable/api.html#events +# +# Don't subclass these. Stuff will break. + +import re +from abc import ABC +from dataclasses import dataclass +from typing import List, Tuple, Union + +from ._abnf import method, request_target +from ._headers import Headers, normalize_and_validate +from ._util import bytesify, LocalProtocolError, validate + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "Event", + "Request", + "InformationalResponse", + "Response", + "Data", + "EndOfMessage", + "ConnectionClosed", +] + +method_re = re.compile(method.encode("ascii")) +request_target_re = re.compile(request_target.encode("ascii")) + + +class Event(ABC): + """ + Base class for h11 events. + """ + + __slots__ = () + + +@dataclass(init=False, frozen=True) +class Request(Event): + """The beginning of an HTTP request. + + Fields: + + .. attribute:: method + + An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: target + + The target of an HTTP request, e.g. ``b"/index.html"``, or one of the + more exotic formats described in `RFC 7320, section 5.3 + `_. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + """ + + __slots__ = ("method", "headers", "target", "http_version") + + method: bytes + headers: Headers + target: bytes + http_version: bytes + + def __init__( + self, + *, + method: Union[bytes, str], + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + target: Union[bytes, str], + http_version: Union[bytes, str] = b"1.1", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "method", bytesify(method)) + object.__setattr__(self, "target", bytesify(target)) + object.__setattr__(self, "http_version", bytesify(http_version)) + else: + object.__setattr__(self, "method", method) + object.__setattr__(self, "target", target) + object.__setattr__(self, "http_version", http_version) + + # "A server MUST respond with a 400 (Bad Request) status code to any + # HTTP/1.1 request message that lacks a Host header field and to any + # request message that contains more than one Host header field or a + # Host header field with an invalid field-value." + # -- https://tools.ietf.org/html/rfc7230#section-5.4 + host_count = 0 + for name, value in self.headers: + if name == b"host": + host_count += 1 + if self.http_version == b"1.1" and host_count == 0: + raise LocalProtocolError("Missing mandatory Host: header") + if host_count > 1: + raise LocalProtocolError("Found multiple Host: headers") + + validate(method_re, self.method, "Illegal method characters") + validate(request_target_re, self.target, "Illegal target characters") + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class _ResponseBase(Event): + __slots__ = ("headers", "http_version", "reason", "status_code") + + headers: Headers + http_version: bytes + reason: bytes + status_code: int + + def __init__( + self, + *, + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + status_code: int, + http_version: Union[bytes, str] = b"1.1", + reason: Union[bytes, str] = b"", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "reason", bytesify(reason)) + object.__setattr__(self, "http_version", bytesify(http_version)) + if not isinstance(status_code, int): + raise LocalProtocolError("status code must be integer") + # Because IntEnum objects are instances of int, but aren't + # duck-compatible (sigh), see gh-72. + object.__setattr__(self, "status_code", int(status_code)) + else: + object.__setattr__(self, "reason", reason) + object.__setattr__(self, "http_version", http_version) + object.__setattr__(self, "status_code", status_code) + + self.__post_init__() + + def __post_init__(self) -> None: + pass + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class InformationalResponse(_ResponseBase): + """An HTTP informational response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`InformationalResponse`, this is always in the range [100, + 200). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for + details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Response(_ResponseBase): + """The beginning of an HTTP response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`Response`, this is always in the range [200, + 1000). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (200 <= self.status_code < 1000): + raise LocalProtocolError( + "Response status_code should be in range [200, 1000), not {}".format( + self.status_code + ) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Data(Event): + """Part of an HTTP message body. + + Fields: + + .. attribute:: data + + A :term:`bytes-like object` containing part of a message body. Or, if + using the ``combine=False`` argument to :meth:`Connection.send`, then + any object that your socket writing code knows what to do with, and for + which calling :func:`len` returns the number of bytes that will be + written -- see :ref:`sendfile` for details. + + .. attribute:: chunk_start + + A marker that indicates whether this data object is from the start of a + chunked transfer encoding chunk. This field is ignored when when a Data + event is provided to :meth:`Connection.send`: it is only valid on + events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + .. attribute:: chunk_end + + A marker that indicates whether this data object is the last for a + given chunked transfer encoding chunk. This field is ignored when when + a Data event is provided to :meth:`Connection.send`: it is only valid + on events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + """ + + __slots__ = ("data", "chunk_start", "chunk_end") + + data: bytes + chunk_start: bool + chunk_end: bool + + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: + object.__setattr__(self, "data", data) + object.__setattr__(self, "chunk_start", chunk_start) + object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that +# are forbidden to be sent in a trailer, since processing them as if they were +# present in the header section might bypass external security filters." +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part +# Unfortunately, the list of forbidden fields is long and vague :-/ +@dataclass(init=False, frozen=True) +class EndOfMessage(Event): + """The end of an HTTP message. + + Fields: + + .. attribute:: headers + + Default value: ``[]`` + + Any trailing headers attached to this message, represented as a list of + (name, value) pairs. See :ref:`the header normalization rules + ` for details. + + Must be empty unless ``Transfer-Encoding: chunked`` is in use. + + """ + + __slots__ = ("headers",) + + headers: Headers + + def __init__( + self, + *, + headers: Union[ + Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None + ] = None, + _parsed: bool = False, + ) -> None: + super().__init__() + if headers is None: + headers = Headers([]) + elif not isinstance(headers, Headers): + headers = normalize_and_validate(headers, _parsed=_parsed) + + object.__setattr__(self, "headers", headers) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(frozen=True) +class ConnectionClosed(Event): + """This event indicates that the sender has closed their outgoing + connection. + + Note that this does not necessarily mean that they can't *receive* further + data, because TCP connections are composed to two one-way channels which + can be closed independently. See :ref:`closing` for details. + + No fields. + """ + + pass diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_headers.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..31da3e2b23b55a624b36f105e62a6902e63286aa --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_headers.py @@ -0,0 +1,282 @@ +import re +from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union + +from ._abnf import field_name, field_value +from ._util import bytesify, LocalProtocolError, validate + +if TYPE_CHECKING: + from ._events import Request + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1 + + +# Facts +# ----- +# +# Headers are: +# keys: case-insensitive ascii +# values: mixture of ascii and raw bytes +# +# "Historically, HTTP has allowed field content with text in the ISO-8859-1 +# charset [ISO-8859-1], supporting other charsets only through use of +# [RFC2047] encoding. In practice, most HTTP header field values use only a +# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD +# limit their field values to US-ASCII octets. A recipient SHOULD treat other +# octets in field content (obs-text) as opaque data." +# And it deprecates all non-ascii values +# +# Leading/trailing whitespace in header names is forbidden +# +# Values get leading/trailing whitespace stripped +# +# Content-Disposition actually needs to contain unicode semantically; to +# accomplish this it has a terrifically weird way of encoding the filename +# itself as ascii (and even this still has lots of cross-browser +# incompatibilities) +# +# Order is important: +# "a proxy MUST NOT change the order of these field values when forwarding a +# message" +# (and there are several headers where the order indicates a preference) +# +# Multiple occurences of the same header: +# "A sender MUST NOT generate multiple header fields with the same field name +# in a message unless either the entire field value for that header field is +# defined as a comma-separated list [or the header is Set-Cookie which gets a +# special exception]" - RFC 7230. (cookies are in RFC 6265) +# +# So every header aside from Set-Cookie can be merged by b", ".join if it +# occurs repeatedly. But, of course, they can't necessarily be split by +# .split(b","), because quoting. +# +# Given all this mess (case insensitive, duplicates allowed, order is +# important, ...), there doesn't appear to be any standard way to handle +# headers in Python -- they're almost like dicts, but... actually just +# aren't. For now we punt and just use a super simple representation: headers +# are a list of pairs +# +# [(name1, value1), (name2, value2), ...] +# +# where all entries are bytestrings, names are lowercase and have no +# leading/trailing whitespace, and values are bytestrings with no +# leading/trailing whitespace. Searching and updating are done via naive O(n) +# methods. +# +# Maybe a dict-of-lists would be better? + +_content_length_re = re.compile(rb"[0-9]+") +_field_name_re = re.compile(field_name.encode("ascii")) +_field_value_re = re.compile(field_value.encode("ascii")) + + +class Headers(Sequence[Tuple[bytes, bytes]]): + """ + A list-like interface that allows iterating over headers as byte-pairs + of (lowercased-name, value). + + Internally we actually store the representation as three-tuples, + including both the raw original casing, in order to preserve casing + over-the-wire, and the lowercased name, for case-insensitive comparisions. + + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert r.headers == [ + (b"host", b"example.org"), + (b"connection", b"keep-alive") + ] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive") + ] + """ + + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: + self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) + + def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] + _, name, value = self._full_items[idx] + return (name, value) + + def raw_items(self) -> List[Tuple[bytes, bytes]]: + return [(raw_name, value) for raw_name, _, value in self._full_items] + + +HeaderTypes = Union[ + List[Tuple[bytes, bytes]], + List[Tuple[bytes, str]], + List[Tuple[str, bytes]], + List[Tuple[str, str]], +] + + +@overload +def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: + ... + + +@overload +def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: + ... + + +@overload +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + ... + + +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + new_headers = [] + seen_content_length = None + saw_transfer_encoding = False + for name, value in headers: + # For headers coming out of the parser, we can safely skip some steps, + # because it always returns bytes and has already run these regexes + # over the data: + if not _parsed: + name = bytesify(name) + value = bytesify(value) + validate(_field_name_re, name, "Illegal header name {!r}", name) + validate(_field_value_re, value, "Illegal header value {!r}", value) + assert isinstance(name, bytes) + assert isinstance(value, bytes) + + raw_name = name + name = name.lower() + if name == b"content-length": + lengths = {length.strip() for length in value.split(b",")} + if len(lengths) != 1: + raise LocalProtocolError("conflicting Content-Length headers") + value = lengths.pop() + validate(_content_length_re, value, "bad Content-Length") + if len(value) > CONTENT_LENGTH_MAX_DIGITS: + raise LocalProtocolError("bad Content-Length") + if seen_content_length is None: + seen_content_length = value + new_headers.append((raw_name, name, value)) + elif seen_content_length != value: + raise LocalProtocolError("conflicting Content-Length headers") + elif name == b"transfer-encoding": + # "A server that receives a request message with a transfer coding + # it does not understand SHOULD respond with 501 (Not + # Implemented)." + # https://tools.ietf.org/html/rfc7230#section-3.3.1 + if saw_transfer_encoding: + raise LocalProtocolError( + "multiple Transfer-Encoding headers", error_status_hint=501 + ) + # "All transfer-coding names are case-insensitive" + # -- https://tools.ietf.org/html/rfc7230#section-4 + value = value.lower() + if value != b"chunked": + raise LocalProtocolError( + "Only Transfer-Encoding: chunked is supported", + error_status_hint=501, + ) + saw_transfer_encoding = True + new_headers.append((raw_name, name, value)) + else: + new_headers.append((raw_name, name, value)) + return Headers(new_headers) + + +def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: + # Should only be used for headers whose value is a list of + # comma-separated, case-insensitive values. + # + # The header name `name` is expected to be lower-case bytes. + # + # Connection: meets these criteria (including cast insensitivity). + # + # Content-Length: technically is just a single value (1*DIGIT), but the + # standard makes reference to implementations that do multiple values, and + # using this doesn't hurt. Ditto, case insensitivity doesn't things either + # way. + # + # Transfer-Encoding: is more complex (allows for quoted strings), so + # splitting on , is actually wrong. For example, this is legal: + # + # Transfer-Encoding: foo; options="1,2", chunked + # + # and should be parsed as + # + # foo; options="1,2" + # chunked + # + # but this naive function will parse it as + # + # foo; options="1 + # 2" + # chunked + # + # However, this is okay because the only thing we are going to do with + # any Transfer-Encoding is reject ones that aren't just "chunked", so + # both of these will be treated the same anyway. + # + # Expect: the only legal value is the literal string + # "100-continue". Splitting on commas is harmless. Case insensitive. + # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: + if found_name == name: + found_raw_value = found_raw_value.lower() + for found_split_value in found_raw_value.split(b","): + found_split_value = found_split_value.strip() + if found_split_value: + out.append(found_split_value) + return out + + +def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: + # The header name `name` is expected to be lower-case bytes. + # + # Note that when we store the header we use title casing for the header + # names, in order to match the conventional HTTP header style. + # + # Simply calling `.title()` is a blunt approach, but it's correct + # here given the cases where we're using `set_comma_header`... + # + # Connection, Content-Length, Transfer-Encoding. + new_headers: List[Tuple[bytes, bytes]] = [] + for found_raw_name, found_name, found_raw_value in headers._full_items: + if found_name != name: + new_headers.append((found_raw_name, found_raw_value)) + for new_value in new_values: + new_headers.append((name.title(), new_value)) + return normalize_and_validate(new_headers) + + +def has_expect_100_continue(request: "Request") -> bool: + # https://tools.ietf.org/html/rfc7231#section-5.1.1 + # "A server that receives a 100-continue expectation in an HTTP/1.0 request + # MUST ignore that expectation." + if request.http_version < b"1.1": + return False + expect = get_comma_header(request.headers, b"expect") + return b"100-continue" in expect diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_readers.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..576804cc282032526e0a932c9853d586a094bad0 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_readers.py @@ -0,0 +1,250 @@ +# Code to read HTTP data +# +# Strategy: each reader is a callable which takes a ReceiveBuffer object, and +# either: +# 1) consumes some of it and returns an Event +# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate() +# and it might raise a LocalProtocolError, so simpler just to always use +# this) +# 3) returns None, meaning "I need more data" +# +# If they have a .read_eof attribute, then this will be called if an EOF is +# received -- but this is optional. Either way, the actual ConnectionClosed +# event will be generated afterwards. +# +# READERS is a dict describing how to pick a reader. It maps states to either: +# - a reader +# - or, for body readers, a dict of per-framing reader factories + +import re +from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union + +from ._abnf import chunk_header, header_field, request_line, status_line +from ._events import Data, EndOfMessage, InformationalResponse, Request, Response +from ._receivebuffer import ReceiveBuffer +from ._state import ( + CLIENT, + CLOSED, + DONE, + IDLE, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, +) +from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate + +__all__ = ["READERS"] + +header_field_re = re.compile(header_field.encode("ascii")) +obs_fold_re = re.compile(rb"[ \t]+") + + +def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]: + it = iter(lines) + last: Optional[bytes] = None + for line in it: + match = obs_fold_re.match(line) + if match: + if last is None: + raise LocalProtocolError("continuation line at start of headers") + if not isinstance(last, bytearray): + # Cast to a mutable type, avoiding copy on append to ensure O(n) time + last = bytearray(last) + last += b" " + last += line[match.end() :] + else: + if last is not None: + yield last + last = line + if last is not None: + yield last + + +def _decode_header_lines( + lines: Iterable[bytes], +) -> Iterable[Tuple[bytes, bytes]]: + for line in _obsolete_line_fold(lines): + matches = validate(header_field_re, line, "illegal header line: {!r}", line) + yield (matches["field_name"], matches["field_value"]) + + +request_line_re = re.compile(request_line.encode("ascii")) + + +def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no request line received") + matches = validate( + request_line_re, lines[0], "illegal request line: {!r}", lines[0] + ) + return Request( + headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches + ) + + +status_line_re = re.compile(status_line.encode("ascii")) + + +def maybe_read_from_SEND_RESPONSE_server( + buf: ReceiveBuffer, +) -> Union[InformationalResponse, Response, None]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no response line received") + matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0]) + http_version = ( + b"1.1" if matches["http_version"] is None else matches["http_version"] + ) + reason = b"" if matches["reason"] is None else matches["reason"] + status_code = int(matches["status_code"]) + class_: Union[Type[InformationalResponse], Type[Response]] = ( + InformationalResponse if status_code < 200 else Response + ) + return class_( + headers=list(_decode_header_lines(lines[1:])), + _parsed=True, + status_code=status_code, + reason=reason, + http_version=http_version, + ) + + +class ContentLengthReader: + def __init__(self, length: int) -> None: + self._length = length + self._remaining = length + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._remaining == 0: + return EndOfMessage() + data = buf.maybe_extract_at_most(self._remaining) + if data is None: + return None + self._remaining -= len(data) + return Data(data=data) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(received {} bytes, expected {})".format( + self._length - self._remaining, self._length + ) + ) + + +chunk_header_re = re.compile(chunk_header.encode("ascii")) + + +class ChunkedReader: + def __init__(self) -> None: + self._bytes_in_chunk = 0 + # After reading a chunk, we have to throw away the trailing \r\n. + # This tracks the bytes that we need to match and throw away. + self._bytes_to_discard = b"" + self._reading_trailer = False + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._reading_trailer: + lines = buf.maybe_extract_lines() + if lines is None: + return None + return EndOfMessage(headers=list(_decode_header_lines(lines))) + if self._bytes_to_discard: + data = buf.maybe_extract_at_most(len(self._bytes_to_discard)) + if data is None: + return None + if data != self._bytes_to_discard[: len(data)]: + raise LocalProtocolError( + f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})" + ) + self._bytes_to_discard = self._bytes_to_discard[len(data) :] + if self._bytes_to_discard: + return None + # else, fall through and read some more + assert self._bytes_to_discard == b"" + if self._bytes_in_chunk == 0: + # We need to refill our chunk count + chunk_header = buf.maybe_extract_next_line() + if chunk_header is None: + return None + matches = validate( + chunk_header_re, + chunk_header, + "illegal chunk header: {!r}", + chunk_header, + ) + # XX FIXME: we discard chunk extensions. Does anyone care? + self._bytes_in_chunk = int(matches["chunk_size"], base=16) + if self._bytes_in_chunk == 0: + self._reading_trailer = True + return self(buf) + chunk_start = True + else: + chunk_start = False + assert self._bytes_in_chunk > 0 + data = buf.maybe_extract_at_most(self._bytes_in_chunk) + if data is None: + return None + self._bytes_in_chunk -= len(data) + if self._bytes_in_chunk == 0: + self._bytes_to_discard = b"\r\n" + chunk_end = True + else: + chunk_end = False + return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(incomplete chunked read)" + ) + + +class Http10Reader: + def __call__(self, buf: ReceiveBuffer) -> Optional[Data]: + data = buf.maybe_extract_at_most(999999999) + if data is None: + return None + return Data(data=data) + + def read_eof(self) -> EndOfMessage: + return EndOfMessage() + + +def expect_nothing(buf: ReceiveBuffer) -> None: + if buf: + raise LocalProtocolError("Got data when expecting EOF") + return None + + +ReadersType = Dict[ + Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]], + Union[Callable[..., Any], Dict[str, Callable[..., Any]]], +] + +READERS: ReadersType = { + (CLIENT, IDLE): maybe_read_from_IDLE_client, + (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server, + (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server, + (CLIENT, DONE): expect_nothing, + (CLIENT, MUST_CLOSE): expect_nothing, + (CLIENT, CLOSED): expect_nothing, + (SERVER, DONE): expect_nothing, + (SERVER, MUST_CLOSE): expect_nothing, + (SERVER, CLOSED): expect_nothing, + SEND_BODY: { + "chunked": ChunkedReader, + "content-length": ContentLengthReader, + "http/1.0": Http10Reader, + }, +} diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_receivebuffer.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c4e08a56f5081e87103f38b4add6ce1b730204 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_receivebuffer.py @@ -0,0 +1,153 @@ +import re +import sys +from typing import List, Optional, Union + +__all__ = ["ReceiveBuffer"] + + +# Operations we want to support: +# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable), +# or wait until there is one +# - read at-most-N bytes +# Goals: +# - on average, do this fast +# - worst case, do this in O(n) where n is the number of bytes processed +# Plan: +# - store bytearray, offset, how far we've searched for a separator token +# - use the how-far-we've-searched data to avoid rescanning +# - while doing a stream of uninterrupted processing, advance offset instead +# of constantly copying +# WARNING: +# - I haven't benchmarked or profiled any of this yet. +# +# Note that starting in Python 3.4, deleting the initial n bytes from a +# bytearray is amortized O(n), thanks to some excellent work by Antoine +# Martin: +# +# https://bugs.python.org/issue19087 +# +# This means that if we only supported 3.4+, we could get rid of the code here +# involving self._start and self.compress, because it's doing exactly the same +# thing that bytearray now does internally. +# +# BUT unfortunately, we still support 2.7, and reading short segments out of a +# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually +# delete this code. Yet: +# +# https://pythonclock.org/ +# +# (Two things to double-check first though: make sure PyPy also has the +# optimization, and benchmark to make sure it's a win, since we do have a +# slightly clever thing where we delay calling compress() until we've +# processed a whole event, which could in theory be slightly more efficient +# than the internal bytearray support.) +blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE) + + +class ReceiveBuffer: + def __init__(self) -> None: + self._data = bytearray() + self._next_line_search = 0 + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": + self._data += byteslike + return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: + return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: + return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it + out = self._data[:count] + del self._data[:count] + + self._next_line_search = 0 + self._multiple_lines_search = 0 + + return out + + def maybe_extract_at_most(self, count: int) -> Optional[bytearray]: + """ + Extract a fixed number of bytes from the buffer. + """ + out = self._data[:count] + if not out: + return None + + return self._extract(count) + + def maybe_extract_next_line(self) -> Optional[bytearray]: + """ + Extract the first line, if it is completed in the buffer. + """ + # Only search in buffer space that we've not already looked at. + search_start_index = max(0, self._next_line_search - 1) + partial_idx = self._data.find(b"\r\n", search_start_index) + + if partial_idx == -1: + self._next_line_search = len(self._data) + return None + + # + 2 is to compensate len(b"\r\n") + idx = partial_idx + 2 + + return self._extract(idx) + + def maybe_extract_lines(self) -> Optional[List[bytearray]]: + """ + Extract everything up to the first blank line, and return a list of lines. + """ + # Handle the case where we have an immediate empty line. + if self._data[:1] == b"\n": + self._extract(1) + return [] + + if self._data[:2] == b"\r\n": + self._extract(2) + return [] + + # Only search in buffer space that we've not already looked at. + match = blank_line_regex.search(self._data, self._multiple_lines_search) + if match is None: + self._multiple_lines_search = max(0, len(self._data) - 2) + return None + + # Truncate the buffer and return it. + idx = match.span(0)[-1] + out = self._extract(idx) + lines = out.split(b"\n") + + for line in lines: + if line.endswith(b"\r"): + del line[-1] + + assert lines[-2] == lines[-1] == b"" + + del lines[-2:] + + return lines + + # In theory we should wait until `\r\n` before starting to validate + # incoming data. However it's interesting to detect (very) invalid data + # early given they might not even contain `\r\n` at all (hence only + # timeout will get rid of them). + # This is not a 100% effective detection but more of a cheap sanity check + # allowing for early abort in some useful cases. + # This is especially interesting when peer is messing up with HTTPS and + # sent us a TLS stream where we were expecting plain HTTP given all + # versions of TLS so far start handshake with a 0x16 message type code. + def is_next_line_obviously_invalid_request_line(self) -> bool: + try: + # HTTP header line must not contain non-printable characters + # and should not start with a space + return self._data[0] < 0x21 + except IndexError: + return False diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_state.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_state.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_state.py @@ -0,0 +1,365 @@ +################################################################ +# The core state machine +################################################################ +# +# Rule 1: everything that affects the state machine and state transitions must +# live here in this file. As much as possible goes into the table-based +# representation, but for the bits that don't quite fit, the actual code and +# state must nonetheless live here. +# +# Rule 2: this file does not know about what role we're playing; it only knows +# about HTTP request/response cycles in the abstract. This ensures that we +# don't cheat and apply different rules to local and remote parties. +# +# +# Theory of operation +# =================== +# +# Possibly the simplest way to think about this is that we actually have 5 +# different state machines here. Yes, 5. These are: +# +# 1) The client state, with its complicated automaton (see the docs) +# 2) The server state, with its complicated automaton (see the docs) +# 3) The keep-alive state, with possible states {True, False} +# 4) The SWITCH_CONNECT state, with possible states {False, True} +# 5) The SWITCH_UPGRADE state, with possible states {False, True} +# +# For (3)-(5), the first state listed is the initial state. +# +# (1)-(3) are stored explicitly in member variables. The last +# two are stored implicitly in the pending_switch_proposals set as: +# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals) +# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals) +# +# And each of these machines has two different kinds of transitions: +# +# a) Event-triggered +# b) State-triggered +# +# Event triggered is the obvious thing that you'd think it is: some event +# happens, and if it's the right event at the right time then a transition +# happens. But there are somewhat complicated rules for which machines can +# "see" which events. (As a rule of thumb, if a machine "sees" an event, this +# means two things: the event can affect the machine, and if the machine is +# not in a state where it expects that event then it's an error.) These rules +# are: +# +# 1) The client machine sees all h11.events objects emitted by the client. +# +# 2) The server machine sees all h11.events objects emitted by the server. +# +# It also sees the client's Request event. +# +# And sometimes, server events are annotated with a _SWITCH_* event. For +# example, we can have a (Response, _SWITCH_CONNECT) event, which is +# different from a regular Response event. +# +# 3) The keep-alive machine sees the process_keep_alive_disabled() event +# (which is derived from Request/Response events), and this event +# transitions it from True -> False, or from False -> False. There's no way +# to transition back. +# +# 4&5) The _SWITCH_* machines transition from False->True when we get a +# Request that proposes the relevant type of switch (via +# process_client_switch_proposals), and they go from True->False when we +# get a Response that has no _SWITCH_* annotation. +# +# So that's event-triggered transitions. +# +# State-triggered transitions are less standard. What they do here is couple +# the machines together. The way this works is, when certain *joint* +# configurations of states are achieved, then we automatically transition to a +# new *joint* state. So, for example, if we're ever in a joint state with +# +# client: DONE +# keep-alive: False +# +# then the client state immediately transitions to: +# +# client: MUST_CLOSE +# +# This is fundamentally different from an event-based transition, because it +# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state +# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive +# transitioned True -> False. Either way, once this precondition is satisfied, +# this transition is immediately triggered. +# +# What if two conflicting state-based transitions get enabled at the same +# time? In practice there's only one case where this arises (client DONE -> +# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by +# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition. +# +# Implementation +# -------------- +# +# The event-triggered transitions for the server and client machines are all +# stored explicitly in a table. Ditto for the state-triggered transitions that +# involve just the server and client state. +# +# The transitions for the other machines, and the state-triggered transitions +# that involve the other machines, are written out as explicit Python code. +# +# It'd be nice if there were some cleaner way to do all this. This isn't +# *too* terrible, but I feel like it could probably be better. +# +# WARNING +# ------- +# +# The script that generates the state machine diagrams for the docs knows how +# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS +# tables. But it can't automatically read the transitions that are written +# directly in Python code. So if you touch those, you need to also update the +# script to keep it in sync! +from typing import cast, Dict, Optional, Set, Tuple, Type, Union + +from ._events import * +from ._util import LocalProtocolError, Sentinel + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "CLIENT", + "SERVER", + "IDLE", + "SEND_RESPONSE", + "SEND_BODY", + "DONE", + "MUST_CLOSE", + "CLOSED", + "MIGHT_SWITCH_PROTOCOL", + "SWITCHED_PROTOCOL", + "ERROR", +] + + +class CLIENT(Sentinel, metaclass=Sentinel): + pass + + +class SERVER(Sentinel, metaclass=Sentinel): + pass + + +# States +class IDLE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_RESPONSE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_BODY(Sentinel, metaclass=Sentinel): + pass + + +class DONE(Sentinel, metaclass=Sentinel): + pass + + +class MUST_CLOSE(Sentinel, metaclass=Sentinel): + pass + + +class CLOSED(Sentinel, metaclass=Sentinel): + pass + + +class ERROR(Sentinel, metaclass=Sentinel): + pass + + +# Switch types +class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): + pass + + +EventTransitionType = Dict[ + Type[Sentinel], + Dict[ + Type[Sentinel], + Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], + ], +] + +EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { + CLIENT: { + IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + MIGHT_SWITCH_PROTOCOL: {}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, + SERVER: { + IDLE: { + ConnectionClosed: CLOSED, + Response: SEND_BODY, + # Special case: server sees client Request events, in this form + (Request, CLIENT): SEND_RESPONSE, + }, + SEND_RESPONSE: { + InformationalResponse: SEND_RESPONSE, + Response: SEND_BODY, + (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, + (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, + }, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, +} + +StateTransitionType = Dict[ + Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]] +] + +# NB: there are also some special-case state-triggered transitions hard-coded +# into _fire_state_triggered_transitions below. +STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { + # (Client state, Server state) -> new states + # Protocol negotiation + (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, + # Socket shutdown + (CLOSED, DONE): {SERVER: MUST_CLOSE}, + (CLOSED, IDLE): {SERVER: MUST_CLOSE}, + (ERROR, DONE): {SERVER: MUST_CLOSE}, + (DONE, CLOSED): {CLIENT: MUST_CLOSE}, + (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, + (DONE, ERROR): {CLIENT: MUST_CLOSE}, +} + + +class ConnectionState: + def __init__(self) -> None: + # Extra bits of state that don't quite fit into the state model. + + # If this is False then it enables the automatic DONE -> MUST_CLOSE + # transition. Don't set this directly; call .keep_alive_disabled() + self.keep_alive = True + + # This is a subset of {UPGRADE, CONNECT}, containing the proposals + # made by the client for switching protocols. + self.pending_switch_proposals: Set[Type[Sentinel]] = set() + + self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE} + + def process_error(self, role: Type[Sentinel]) -> None: + self.states[role] = ERROR + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: + self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: + self.pending_switch_proposals.add(switch_event) + self._fire_state_triggered_transitions() + + def process_event( + self, + role: Type[Sentinel], + event_type: Type[Event], + server_switch_event: Optional[Type[Sentinel]] = None, + ) -> None: + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER + if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( + "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) + if server_switch_event is None and _event_type is Response: + self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) + # Special case: the server state does get to see Request + # events. + if _event_type is Request: + assert role is CLIENT + self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( + self, + role: Type[Sentinel], + event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], + ) -> None: + state = self.states[role] + try: + new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] + except KeyError: + event_type = cast(Type[Event], event_type) + raise LocalProtocolError( + "can't handle event type {} when role={} and state={}".format( + event_type.__name__, role, self.states[role] + ) + ) from None + self.states[role] = new_state + + def _fire_state_triggered_transitions(self) -> None: + # We apply these rules repeatedly until converging on a fixed point + while True: + start_states = dict(self.states) + + # It could happen that both these special-case transitions are + # enabled at the same time: + # + # DONE -> MIGHT_SWITCH_PROTOCOL + # DONE -> MUST_CLOSE + # + # For example, this will always be true of a HTTP/1.0 client + # requesting CONNECT. If this happens, the protocol switch takes + # priority. From there the client will either go to + # SWITCHED_PROTOCOL, in which case it's none of our business when + # they close the connection, or else the server will deny the + # request, in which case the client will go back to DONE and then + # from there to MUST_CLOSE. + if self.pending_switch_proposals: + if self.states[CLIENT] is DONE: + self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL + + if not self.pending_switch_proposals: + if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: + self.states[CLIENT] = DONE + + if not self.keep_alive: + for role in (CLIENT, SERVER): + if self.states[role] is DONE: + self.states[role] = MUST_CLOSE + + # Tabular state-triggered transitions + joint_state = (self.states[CLIENT], self.states[SERVER]) + changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) + self.states.update(changes) + + if self.states == start_states: + # Fixed point reached + return + + def start_next_cycle(self) -> None: + if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) + # Can't reach DONE/DONE with any of these active, but still, let's be + # sure. + assert self.keep_alive + assert not self.pending_switch_proposals + self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_util.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6718445290770e028ea2f1f662026c9a0b0991db --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_util.py @@ -0,0 +1,135 @@ +from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union + +__all__ = [ + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "validate", + "bytesify", +] + + +class ProtocolError(Exception): + """Exception indicating a violation of the HTTP/1.1 protocol. + + This as an abstract base class, with two concrete base classes: + :exc:`LocalProtocolError`, which indicates that you tried to do something + that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which + indicates that the remote peer tried to do something that HTTP/1.1 says is + illegal. See :ref:`error-handling` for details. + + In addition to the normal :exc:`Exception` features, it has one attribute: + + .. attribute:: error_status_hint + + This gives a suggestion as to what status code a server might use if + this error occurred as part of a request. + + For a :exc:`RemoteProtocolError`, this is useful as a suggestion for + how you might want to respond to a misbehaving peer, if you're + implementing a server. + + For a :exc:`LocalProtocolError`, this can be taken as a suggestion for + how your peer might have responded to *you* if h11 had allowed you to + continue. + + The default is 400 Bad Request, a generic catch-all for protocol + violations. + + """ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: + raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) + self.error_status_hint = error_status_hint + + +# Strategy: there are a number of public APIs where a LocalProtocolError can +# be raised (send(), all the different event constructors, ...), and only one +# public API where RemoteProtocolError can be raised +# (receive_data()). Therefore we always raise LocalProtocolError internally, +# and then receive_data will translate this into a RemoteProtocolError. +# +# Internally: +# LocalProtocolError is the generic "ProtocolError". +# Externally: +# LocalProtocolError is for local errors and RemoteProtocolError is for +# remote errors. +class LocalProtocolError(ProtocolError): + def _reraise_as_remote_protocol_error(self) -> NoReturn: + # After catching a LocalProtocolError, use this method to re-raise it + # as a RemoteProtocolError. This method must be called from inside an + # except: block. + # + # An easy way to get an equivalent RemoteProtocolError is just to + # modify 'self' in place. + self.__class__ = RemoteProtocolError # type: ignore + # But the re-raising is somewhat non-trivial -- you might think that + # now that we've modified the in-flight exception object, that just + # doing 'raise' to re-raise it would be enough. But it turns out that + # this doesn't work, because Python tracks the exception type + # (exc_info[0]) separately from the exception object (exc_info[1]), + # and we only modified the latter. So we really do need to re-raise + # the new type explicitly. + # On py3, the traceback is part of the exception object, so our + # in-place modification preserved it and we can just re-raise: + raise self + + +class RemoteProtocolError(ProtocolError): + pass + + +def validate( + regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any +) -> Dict[str, bytes]: + match = regex.fullmatch(data) + if not match: + if format_args: + msg = msg.format(*format_args) + raise LocalProtocolError(msg) + return match.groupdict() + + +# Sentinel values +# +# - Inherit identity-based comparison and hashing from object +# - Have a nice repr +# - Have a *bonus property*: type(sentinel) is sentinel +# +# The bonus property is useful if you want to take the return value from +# next_event() and do some sort of dispatch based on type(event). + +_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel") + + +class Sentinel(type): + def __new__( + cls: Type[_T_Sentinel], + name: str, + bases: Tuple[type, ...], + namespace: Dict[str, Any], + **kwds: Any + ) -> _T_Sentinel: + assert bases == (Sentinel,) + v = super().__new__(cls, name, bases, namespace, **kwds) + v.__class__ = v # type: ignore + return v + + def __repr__(self) -> str: + return self.__name__ + + +# Used for methods, request targets, HTTP versions, header names, and header +# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always +# returns bytes. +def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes: + # Fast-path: + if type(s) is bytes: + return s + if isinstance(s, str): + s = s.encode("ascii") + if isinstance(s, int): + raise TypeError("expected bytes-like object, not int") + return bytes(s) diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_version.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..76e7327b8617c9d12236f511414d5eb58e98a44b --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_version.py @@ -0,0 +1,16 @@ +# This file must be kept very simple, because it is consumed from several +# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc. + +# We use a simple scheme: +# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev +# where the +dev versions are never released into the wild, they're just what +# we stick into the VCS in between releases. +# +# This is compatible with PEP 440: +# http://legacy.python.org/dev/peps/pep-0440/ +# via the use of the "local suffix" "+dev", which is disallowed on index +# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we +# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before* +# 1.0.0.) + +__version__ = "0.16.0" diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_writers.py b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_writers.py new file mode 100644 index 0000000000000000000000000000000000000000..939cdb912a9debaea07fbf3a9ac04549c44d077c --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/_writers.py @@ -0,0 +1,145 @@ +# Code to read HTTP data +# +# Strategy: each writer takes an event + a write-some-bytes function, which is +# calls. +# +# WRITERS is a dict describing how to pick a reader. It maps states to either: +# - a writer +# - or, for body writers, a dict of framin-dependent writer factories + +from typing import Any, Callable, Dict, List, Tuple, Type, Union + +from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response +from ._headers import Headers +from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER +from ._util import LocalProtocolError, Sentinel + +__all__ = ["WRITERS"] + +Writer = Callable[[bytes], Any] + + +def write_headers(headers: Headers, write: Writer) -> None: + # "Since the Host field-value is critical information for handling a + # request, a user agent SHOULD generate Host as the first header field + # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: + if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: + if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + + +def write_request(request: Request, write: Writer) -> None: + if request.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target)) + write_headers(request.headers, write) + + +# Shared between InformationalResponse and Response +def write_any_response( + response: Union[InformationalResponse, Response], write: Writer +) -> None: + if response.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + status_bytes = str(response.status_code).encode("ascii") + # We don't bother sending ascii status messages like "OK"; they're + # optional and ignored by the protocol. (But the space after the numeric + # status code is mandatory.) + # + # XX FIXME: could at least make an effort to pull out the status message + # from stdlib's http.HTTPStatus table. Or maybe just steal their enums + # (either by import or copy/paste). We already accept them as status codes + # since they're of type IntEnum < int. + write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason)) + write_headers(response.headers, write) + + +class BodyWriter: + def __call__(self, event: Event, write: Writer) -> None: + if type(event) is Data: + self.send_data(event.data, write) + elif type(event) is EndOfMessage: + self.send_eom(event.headers, write) + else: # pragma: no cover + assert False + + def send_data(self, data: bytes, write: Writer) -> None: + pass + + def send_eom(self, headers: Headers, write: Writer) -> None: + pass + + +# +# These are all careful not to do anything to 'data' except call len(data) and +# write(data). This allows us to transparently pass-through funny objects, +# like placeholder objects referring to files on disk that will be sent via +# sendfile(2). +# +class ContentLengthWriter(BodyWriter): + def __init__(self, length: int) -> None: + self._length = length + + def send_data(self, data: bytes, write: Writer) -> None: + self._length -= len(data) + if self._length < 0: + raise LocalProtocolError("Too much data for declared Content-Length") + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") + if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +class ChunkedWriter(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + # if we encoded 0-length data in the naive way, it would look like an + # end-of-message. + if not data: + return + write(b"%x\r\n" % len(data)) + write(data) + write(b"\r\n") + + def send_eom(self, headers: Headers, write: Writer) -> None: + write(b"0\r\n") + write_headers(headers, write) + + +class Http10Writer(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if headers: + raise LocalProtocolError("can't send trailers to HTTP/1.0 client") + # no need to close the socket ourselves, that will be taken care of by + # Connection: close machinery + + +WritersType = Dict[ + Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]], + Union[ + Dict[str, Type[BodyWriter]], + Callable[[Union[InformationalResponse, Response], Writer], None], + Callable[[Request, Writer], None], + ], +] + +WRITERS: WritersType = { + (CLIENT, IDLE): write_request, + (SERVER, IDLE): write_any_response, + (SERVER, SEND_RESPONSE): write_any_response, + SEND_BODY: { + "chunked": ChunkedWriter, + "content-length": ContentLengthWriter, + "http/1.0": Http10Writer, + }, +} diff --git a/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/py.typed b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..f5642f79f21d872f010979dcf6f0c4a415acc19d --- /dev/null +++ b/miniconda3/pkgs/h11-0.16.0-py313h06a4308_1/lib/python3.13/site-packages/h11/py.typed @@ -0,0 +1 @@ +Marker diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/about.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/about.json new file mode 100644 index 0000000000000000000000000000000000000000..ced52a8ad74f3df40bba94915f5c89020afe964f --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/about.json @@ -0,0 +1,132 @@ +{ + "channels": [ + "https://repo.anaconda.com/pkgs/main" + ], + "conda_build_version": "24.1.2", + "conda_version": "24.1.2", + "description": "The HTTP Core package provides a minimal low-level HTTP client, which does one thing only. Sending HTTP requests.", + "dev_url": "https://github.com/encode/httpcore", + "doc_url": "https://www.encode.io/httpcore/", + "env_vars": { + "CIO_TEST": "" + }, + "extra": { + "copy_test_source_files": true, + "final": true, + "flow_run_id": "86f5e8db-440e-4094-93b2-b06eda562860", + "recipe-maintainers": [ + "nicoddemus", + "synapticarbors" + ], + "remote_url": "git@github.com:AnacondaRecipes/httpcore-feedstock.git", + "sha": "bf922a7a787fe76f6d2a10110d0d35537d06e5ca" + }, + "home": "https://github.com/encode/httpcore", + "identifiers": [], + "keywords": [], + "license": "BSD-3-Clause", + "license_family": "BSD", + "license_file": "LICENSE.md", + "root_pkgs": [ + "_libgcc_mutex 0.1 main", + "_openmp_mutex 5.1 1_gnu", + "archspec 0.2.1 pyhd3eb1b0_0", + "boltons 23.0.0 py39h06a4308_0", + "brotli-python 1.0.9 py39h6a678d5_7", + "bzip2 1.0.8 h7b6447c_0", + "c-ares 1.19.1 h5eee18b_0", + "charset-normalizer 2.0.4 pyhd3eb1b0_0", + "conda-content-trust 0.2.0 py39h06a4308_0", + "conda-package-handling 2.2.0 py39h06a4308_0", + "conda-package-streaming 0.9.0 py39h06a4308_0", + "fmt 9.1.0 hdb19cb5_0", + "icu 73.1 h6a678d5_0", + "idna 3.4 py39h06a4308_0", + "jsonpatch 1.32 pyhd3eb1b0_0", + "jsonpointer 2.1 pyhd3eb1b0_0", + "krb5 1.20.1 h143b758_1", + "ld_impl_linux-64 2.38 h1181459_1", + "libarchive 3.6.2 h6ac8c49_2", + "libev 4.33 h7f8727e_1", + "libffi 3.4.4 h6a678d5_0", + "libgcc-ng 11.2.0 h1234567_1", + "libgomp 11.2.0 h1234567_1", + "libnghttp2 1.57.0 h2d74bed_0", + "libsolv 0.7.24 he621ea3_0", + "libssh2 1.10.0 hdbd6064_2", + "libstdcxx-ng 11.2.0 h1234567_1", + "libxml2 2.10.4 hf1b16e4_1", + "lz4-c 1.9.4 h6a678d5_0", + "ncurses 6.4 h6a678d5_0", + "packaging 23.1 py39h06a4308_0", + "pcre2 10.42 hebb0a14_0", + "pluggy 1.0.0 py39h06a4308_1", + "pybind11-abi 4 hd3eb1b0_1", + "pycosat 0.6.6 py39h5eee18b_0", + "pycparser 2.21 pyhd3eb1b0_0", + "pysocks 1.7.1 py39h06a4308_0", + "python 3.9.18 h955ad1f_0", + "readline 8.2 h5eee18b_0", + "reproc 14.2.4 h295c915_1", + "reproc-cpp 14.2.4 h295c915_1", + "ruamel.yaml 0.17.21 py39h5eee18b_0", + "ruamel.yaml.clib 0.2.6 py39h5eee18b_1", + "sqlite 3.41.2 h5eee18b_0", + "tk 8.6.12 h1ccaba5_0", + "tqdm 4.65.0 py39hb070fc8_0", + "wheel 0.41.2 py39h06a4308_0", + "yaml-cpp 0.8.0 h6a678d5_0", + "zlib 1.2.13 h5eee18b_0", + "zstandard 0.19.0 py39h5eee18b_0", + "zstd 1.5.5 hc292b87_0", + "attrs 23.1.0 py39h06a4308_0", + "beautifulsoup4 4.12.2 py39h06a4308_0", + "ca-certificates 2023.12.12 h06a4308_0", + "certifi 2024.2.2 py39h06a4308_0", + "cffi 1.16.0 py39h5eee18b_0", + "chardet 4.0.0 py39h06a4308_1003", + "click 8.1.7 py39h06a4308_0", + "conda 24.1.2 py39h06a4308_0", + "conda-build 24.1.2 py39h06a4308_0", + "conda-index 0.4.0 pyhd3eb1b0_0", + "conda-libmamba-solver 24.1.0 pyhd3eb1b0_0", + "cryptography 42.0.2 py39hdda0065_0", + "distro 1.8.0 py39h06a4308_0", + "filelock 3.13.1 py39h06a4308_0", + "jinja2 3.1.3 py39h06a4308_0", + "jsonschema 4.19.2 py39h06a4308_0", + "jsonschema-specifications 2023.7.1 py39h06a4308_0", + "libcurl 8.5.0 h251f7ec_0", + "libedit 3.1.20230828 h5eee18b_0", + "liblief 0.12.3 h6a678d5_0", + "libmamba 1.5.6 haf1ee3a_0", + "libmambapy 1.5.6 py39h2dafd23_0", + "markupsafe 2.1.3 py39h5eee18b_0", + "menuinst 2.0.2 py39h06a4308_0", + "more-itertools 10.1.0 py39h06a4308_0", + "openssl 3.0.13 h7f8727e_0", + "patch 2.7.6 h7b6447c_1001", + "patchelf 0.17.2 h6a678d5_0", + "pip 23.3.1 py39h06a4308_0", + "pkginfo 1.9.6 py39h06a4308_0", + "platformdirs 3.10.0 py39h06a4308_0", + "psutil 5.9.0 py39h5eee18b_0", + "py-lief 0.12.3 py39h6a678d5_0", + "pyopenssl 24.0.0 py39h06a4308_0", + "python-libarchive-c 2.9 pyhd3eb1b0_1", + "pytz 2023.3.post1 py39h06a4308_0", + "pyyaml 6.0.1 py39h5eee18b_0", + "referencing 0.30.2 py39h06a4308_0", + "requests 2.31.0 py39h06a4308_1", + "rpds-py 0.10.6 py39hb02cf49_0", + "setuptools 68.2.2 py39h06a4308_0", + "soupsieve 2.5 py39h06a4308_0", + "tomli 2.0.1 py39h06a4308_0", + "tzdata 2023d h04d1e81_0", + "urllib3 2.1.0 py39h06a4308_1", + "xz 5.4.5 h5eee18b_0", + "yaml 0.2.5 h7b6447c_0" + ], + "summary": "The next generation HTTP client.", + "tags": [] +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/files b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/files new file mode 100644 index 0000000000000000000000000000000000000000..f0f79404c87f401ea01af0dde3383a1ae09aef14 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/files @@ -0,0 +1,70 @@ +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/REQUESTED +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/direct_url.json +lib/python3.13/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md +lib/python3.13/site-packages/httpcore/__init__.py +lib/python3.13/site-packages/httpcore/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_api.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_exceptions.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_models.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_ssl.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_synchronization.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_trace.cpython-313.pyc +lib/python3.13/site-packages/httpcore/__pycache__/_utils.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_api.py +lib/python3.13/site-packages/httpcore/_async/__init__.py +lib/python3.13/site-packages/httpcore/_async/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/connection.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/http11.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/http2.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/interfaces.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_async/connection.py +lib/python3.13/site-packages/httpcore/_async/connection_pool.py +lib/python3.13/site-packages/httpcore/_async/http11.py +lib/python3.13/site-packages/httpcore/_async/http2.py +lib/python3.13/site-packages/httpcore/_async/http_proxy.py +lib/python3.13/site-packages/httpcore/_async/interfaces.py +lib/python3.13/site-packages/httpcore/_async/socks_proxy.py +lib/python3.13/site-packages/httpcore/_backends/__init__.py +lib/python3.13/site-packages/httpcore/_backends/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/anyio.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/auto.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/base.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/mock.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/sync.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/__pycache__/trio.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_backends/anyio.py +lib/python3.13/site-packages/httpcore/_backends/auto.py +lib/python3.13/site-packages/httpcore/_backends/base.py +lib/python3.13/site-packages/httpcore/_backends/mock.py +lib/python3.13/site-packages/httpcore/_backends/sync.py +lib/python3.13/site-packages/httpcore/_backends/trio.py +lib/python3.13/site-packages/httpcore/_exceptions.py +lib/python3.13/site-packages/httpcore/_models.py +lib/python3.13/site-packages/httpcore/_ssl.py +lib/python3.13/site-packages/httpcore/_sync/__init__.py +lib/python3.13/site-packages/httpcore/_sync/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/connection.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/http11.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/http2.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-313.pyc +lib/python3.13/site-packages/httpcore/_sync/connection.py +lib/python3.13/site-packages/httpcore/_sync/connection_pool.py +lib/python3.13/site-packages/httpcore/_sync/http11.py +lib/python3.13/site-packages/httpcore/_sync/http2.py +lib/python3.13/site-packages/httpcore/_sync/http_proxy.py +lib/python3.13/site-packages/httpcore/_sync/interfaces.py +lib/python3.13/site-packages/httpcore/_sync/socks_proxy.py +lib/python3.13/site-packages/httpcore/_synchronization.py +lib/python3.13/site-packages/httpcore/_trace.py +lib/python3.13/site-packages/httpcore/_utils.py +lib/python3.13/site-packages/httpcore/py.typed diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/git b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/git new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/hash_input.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/hash_input.json new file mode 100644 index 0000000000000000000000000000000000000000..e1489271625fa4f5548417553f3725447d4df321 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/hash_input.json @@ -0,0 +1,4 @@ +{ + "channel_targets": "defaults", + "target_platform": "linux-64" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/index.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/index.json new file mode 100644 index 0000000000000000000000000000000000000000..a8326ba2b8953dbd50d15cf846f003ebde753aa4 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/index.json @@ -0,0 +1,18 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_0", + "build_number": 0, + "depends": [ + "certifi", + "h11 >=0.16", + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "license": "BSD-3-Clause", + "license_family": "BSD", + "name": "httpcore", + "platform": "linux", + "subdir": "linux-64", + "timestamp": 1748526107673, + "version": "1.0.9" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/licenses/LICENSE.md b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..311b2b56c53f678ab95fc0def708c675d521a807 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/paths.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/paths.json new file mode 100644 index 0000000000000000000000000000000000000000..fae9300799e516b20df5bf567700a44542a525f5 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/paths.json @@ -0,0 +1,425 @@ +{ + "paths": [ + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER", + "path_type": "hardlink", + "sha256": "d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8", + "size_in_bytes": 5 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA", + "path_type": "hardlink", + "sha256": "fe2d4fda6199128978779e0cf27f3c045c531863fcdd987eacc74f3a18d41c21", + "size_in_bytes": 21529 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD", + "path_type": "hardlink", + "sha256": "9caf35e2a9ecdef02668e05fc9a112135adb640936cd6205b195ae7d690e70c9", + "size_in_bytes": 4947 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/REQUESTED", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL", + "path_type": "hardlink", + "sha256": "aad0b0a12256807936d52d4a6f88a1773236ae527564a688bab4e3fe780e8724", + "size_in_bytes": 87 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/direct_url.json", + "path_type": "hardlink", + "sha256": "4b152fb8564e4b5efc093ab4475a6d3cb968638c3e8a280d4c4492e1d07dc353", + "size_in_bytes": 68 + }, + { + "_path": "lib/python3.13/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md", + "path_type": "hardlink", + "sha256": "fdcb59154c74cbaba16a11242f7740bea9f23d6feb5547917d8c5f94a80392a5", + "size_in_bytes": 1518 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__init__.py", + "path_type": "hardlink", + "sha256": "f644ff92a0a10822544c7c30db866647f7b371d6e94585a4b03fa060dce464ff", + "size_in_bytes": 3445 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "d8e820d865a5314662d2dea3985e5f945f72067bb1b879aa69bfacaa9b9d9210", + "size_in_bytes": 3222 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_api.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "42f324c3342da955b8e4ccddc3768790b87c74255661be65197788861b169e04", + "size_in_bytes": 3575 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_exceptions.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "67323dc26657fb796f7648a3bcd5f14d1706e7310d03ff7821c670368f029bb9", + "size_in_bytes": 3464 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_models.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "559a2bc38e6b1674190f806e0e98ed558f900224452f34c01f91a3415f61b5d3", + "size_in_bytes": 23249 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_ssl.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "4964681268dc234f57d28768662135f080920282559845eb336803c160d69c74", + "size_in_bytes": 573 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_synchronization.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "cbbf195d4722a715b740024c69b8349145f3ce6452b1e8c1f7b90b1ff95c761e", + "size_in_bytes": 14612 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_trace.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "fe965c53c57e811899dcf60728083434fe081ec11370d1be2825c096e4e41320", + "size_in_bytes": 5832 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/__pycache__/_utils.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "2e1917ac410b6db1f2f4871f7aa9d9ec93d592cc67e30813ae6d0aa0926e478d", + "size_in_bytes": 1247 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_api.py", + "path_type": "hardlink", + "sha256": "ba7666783b1c8415821823c2c244b75a8b7d7ae2ba6e0fe42b12ed193c70db5e", + "size_in_bytes": 3146 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__init__.py", + "path_type": "hardlink", + "sha256": "116765dafe2d867007cc9a6a8d4e21d9af03522180bcd896ae48a2f697e14dfd", + "size_in_bytes": 1221 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "48842d71f781752f7d2d765990d46919ee65d8c0ac6466bc68c41ddd9c1d295f", + "size_in_bytes": 1664 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/connection.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "0e9a405ea1dd18e997e41f0d1f716450f988ea3bafdd1bdce5caf7e01023d098", + "size_in_bytes": 11948 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "1ca65ee6814d3a2d01f601d6d6d29f795f5706f9ec9d6e7cf724da665c87f84b", + "size_in_bytes": 19637 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/http11.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "6bd0ff290e4e27f78ae7464f3d677b25ab48702b56c47d21dc64de6d5eb2cf55", + "size_in_bytes": 20468 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/http2.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "ba4c9f05f5a581dd76c6ddec4782a3809e70f061fc5efec4910730444aa3dbfa", + "size_in_bytes": 31605 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "ff216212753bf5e04353c2a30ce9f72f46bf300ddd7b27698b70b3864caeee53", + "size_in_bytes": 17842 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/interfaces.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "f92bc18830e4e0fc272eefac2029f95935fda6e903a400651a7d3b74dd16f918", + "size_in_bytes": 5579 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "e0229f3f3f0c098cb27f7b923e7f3b1833c7bbda3d50f0c07dfe9de619877f15", + "size_in_bytes": 16866 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/connection.py", + "path_type": "hardlink", + "sha256": "e8e70f5ea3047dcd01537f3ffa21d4343775bca4937365154f4f57a8d6ff04e9", + "size_in_bytes": 8449 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/connection_pool.py", + "path_type": "hardlink", + "sha256": "0ce210dacd9909ff6a7f0c61ccca6b4cf2ea08bf0ec465e2285eaa447c6f5726", + "size_in_bytes": 17307 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/http11.py", + "path_type": "hardlink", + "sha256": "faa33d6d5ecf8d2405e6fc6cdfbf9e5173881706c88cf7196cd962b97f53b41c", + "size_in_bytes": 13880 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/http2.py", + "path_type": "hardlink", + "sha256": "6b35f57dc9ad5da2308e9bad165678bddf7627cc708c639af5ac7d408bf8dfde", + "size_in_bytes": 23936 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/http_proxy.py", + "path_type": "hardlink", + "sha256": "db3564ae5bfe0ecfab5866aa69796b84426201014fa36dc14f71aafec5a80575", + "size_in_bytes": 14701 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/interfaces.py", + "path_type": "hardlink", + "sha256": "8d389a58bf37a60a460bdce2bfdd197f068a34c987c2639a97368a8ae4f1013a", + "size_in_bytes": 4455 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_async/socks_proxy.py", + "path_type": "hardlink", + "sha256": "94b2a02e58203df84596a8b438378190e5afb7d0a0841054caab27b14d6dc7a4", + "size_in_bytes": 13841 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__init__.py", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "8f8601a729e0665c018274f44563ea1c050bc7b8d17b073666ffc2045552a869", + "size_in_bytes": 156 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/anyio.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "fe42d8cb3f6d52e2c18ed60cd5ff844100cb8a2cb89a4637544eb92b6d616efa", + "size_in_bytes": 8571 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/auto.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "99485e5e5e518a5d5c508bccc5380c58a1725a916ddd75ded8d2db0d480c46f8", + "size_in_bytes": 2709 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/base.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "514c498817b7a4175d750f7f070354f120d94b8f11c2f75fba46c36e70728ec8", + "size_in_bytes": 5033 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/mock.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "edd6ecb036567a1aa716b87106359671d908d416485126d63e528f0b4211da79", + "size_in_bytes": 7346 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/sync.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "fe3380aa6f0b59a00b5bf0fc21d434c724079c64f6d6d7f62dbebdebf3897b89", + "size_in_bytes": 11573 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/__pycache__/trio.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "b81a4d02f991a44b3b49bbcff35ef67c08b93e67ce25f7ab0cbb411841d3b075", + "size_in_bytes": 9082 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/anyio.py", + "path_type": "hardlink", + "sha256": "c7c3e01215d10bc6d5aac77393f609c7c63a77d4ee6f4e82b944b09db9adaa86", + "size_in_bytes": 5252 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/auto.py", + "path_type": "hardlink", + "sha256": "cced77e8f2999ac6930caf87464f38780f8c520f3fdb025fe0dbe62b8df6022a", + "size_in_bytes": 1662 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/base.py", + "path_type": "hardlink", + "sha256": "69286045d6673264611561deb63ba694cef77fc2b3d58380c8250fff8907b250", + "size_in_bytes": 3042 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/mock.py", + "path_type": "hardlink", + "sha256": "7abf53e37eae49eecd2eb7e22dae31e8dbaa8398af43af770b1598096b206c7e", + "size_in_bytes": 4077 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/sync.py", + "path_type": "hardlink", + "sha256": "6e113877d88af549b176c76c826d847ca9d76819acd9682019853eee3994ba35", + "size_in_bytes": 7977 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_backends/trio.py", + "path_type": "hardlink", + "sha256": "2c7bb8fccaf932cc109a64f7c84e282e07fd6ff2497de552e018c3c5e25ced1a", + "size_in_bytes": 5996 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_exceptions.py", + "path_type": "hardlink", + "sha256": "968a022a06b7fd8558bb7b3e7772fd44c3d127286c63b7e2bae1b1be4383d1cd", + "size_in_bytes": 1184 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_models.py", + "path_type": "hardlink", + "sha256": "20ed8271771da68bd170b4dd185181e91c8165d126da1fd33a6a02738ac42a1a", + "size_in_bytes": 17623 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_ssl.py", + "path_type": "hardlink", + "sha256": "b2baa648d53888e52f585f92ac9bdbf06fd811b1c510b39740ec1d0c80534bd7", + "size_in_bytes": 187 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__init__.py", + "path_type": "hardlink", + "sha256": "2410c8817b7995ad4b089d6c2d078a863285a4b9e936bf12beceb3da78b77e08", + "size_in_bytes": 1141 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "a333591d9a8d8bf87ffd70f078d82fd8f1f03038934b683bca62c0da9f059f6e", + "size_in_bytes": 1618 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/connection.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "639c2461545bfa2fa48e901d573f8fd76cabe04ebcf4fafe20035dd38d85d5d6", + "size_in_bytes": 10615 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/connection_pool.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "5b17f0089384b246761c69c2e273a13ca6b888db5dac254c61f7638fe96464d1", + "size_in_bytes": 18729 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/http11.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "3f30f01921e498510733c16e56b7d8b357007e900e83be33d4e08ab103bb5a3f", + "size_in_bytes": 18090 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/http2.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "6414233412ccd83649a484d658d8e1585d129751a660e4b1ecaabbf34389cfcf", + "size_in_bytes": 27791 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/http_proxy.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "d1bfed055eaed3e8907d4c065714ede761966775a0631c48d2dfb7b9265e5b1e", + "size_in_bytes": 17051 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/interfaces.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "6d228dccf2e985f5478c4f278654633c352a3ad573701ada7756369c2ba8215b", + "size_in_bytes": 5131 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/__pycache__/socks_proxy.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "a7a79e067a77244dbbd4cd604aafb09e54b41e9eb5629ba817cd877f8c2d87e8", + "size_in_bytes": 15663 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/connection.py", + "path_type": "hardlink", + "sha256": "f5ec4639bdcf07e329d93d7eb1c91278bdadfad27ff7e357a2657c8a19960a05", + "size_in_bytes": 8238 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/connection_pool.py", + "path_type": "hardlink", + "sha256": "6be4fc2d3b14c5ceebd16c356ad7c7483a163e34347c0f1497b4b7f85d0c8fbd", + "size_in_bytes": 16955 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/http11.py", + "path_type": "hardlink", + "sha256": "205a1b0f531de491652462969e1d7f4377a98a452bc88f2aa34f6ff0c8892040", + "size_in_bytes": 13476 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/http2.py", + "path_type": "hardlink", + "sha256": "031538ca172aebc067e6fa9d258b625ca6148fb9ef8586f1cf7bf8ad3e319ef0", + "size_in_bytes": 23400 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/http_proxy.py", + "path_type": "hardlink", + "sha256": "fda97fe9cacab8466edb0cafbb8f7745922625d0499e3e6818a3632ce24bd99a", + "size_in_bytes": 14463 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/interfaces.py", + "path_type": "hardlink", + "sha256": "b275ce378daf5031cee49049be8f03e155a4d966ade38cf63975c70eb8db97de", + "size_in_bytes": 4344 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_sync/socks_proxy.py", + "path_type": "hardlink", + "sha256": "cde8195bd4a7aa3dbff7dd831496bcfc2a6939506454be0083076e4644ad6a44", + "size_in_bytes": 13614 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_synchronization.py", + "path_type": "hardlink", + "sha256": "cd28b5de6002a250679278d90649d40ba84a343413e02ea28e77b367eaf44f6b", + "size_in_bytes": 9434 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_trace.py", + "path_type": "hardlink", + "sha256": "724e99a08cd84e474d0087eae4c19e2aa0570edaa3397faa7d8c266456eb19ca", + "size_in_bytes": 3952 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/_utils.py", + "path_type": "hardlink", + "sha256": "fd12e05d8380602df9d229002d5e7d199ebc209adda1c459c4fb3d3e39b37456", + "size_in_bytes": 1537 + }, + { + "_path": "lib/python3.13/site-packages/httpcore/py.typed", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + } + ], + "paths_version": 1 +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/conda_build_config.yaml b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/conda_build_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76282aad1e0a266c1b15fbbbf27f960e1bc217ac --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/conda_build_config.yaml @@ -0,0 +1,375 @@ +VERBOSE_AT: V=1 +VERBOSE_CM: VERBOSE=1 +alsa_lib: '1.2' +ampl_mp: '3.1' +aom: '3.6' +armadillo: '12' +arpack: '3.9' +arrow_cpp: 19.0.0 +assimp: 5.4.3 +at_spi2_core: '2.36' +aws_c_auth: 0.8.5 +aws_c_cal: 0.8.5 +aws_c_common: 0.11.1 +aws_c_compression: 0.3.1 +aws_c_event_stream: 0.5.4 +aws_c_http: 0.9.3 +aws_c_io: 0.17.0 +aws_c_mqtt: 0.12.2 +aws_c_s3: 0.7.11 +aws_c_sdkutils: 0.2.3 +aws_checksums: 0.2.3 +aws_crt_cpp: 0.31.0 +aws_sdk_cpp: 1.11.528 +azure_core_cpp: 1.14.1 +azure_identity_cpp: 1.10.1 +azure_storage_blobs_cpp: 12.13.0 +azure_storage_common_cpp: 12.10.0 +backtrace: '20241216' +blas_impl: openblas +blosc: '1' +boost: '1.82' +boost_cpp: '1.82' +brunsli: '0' +bzip2: '1' +c_ares: '1' +c_blosc2: '2' +c_compiler: gcc +c_compiler_version: 11.2.0 +cairo: '1' +capnproto: 1.1.0 +ceres_solver: '2.2' +cfitsio: '3.470' +cgo_compiler: go-cgo +cgo_compiler_version: '1.21' +channel_targets: defaults +charls: '2.2' +clang_variant: clang +coin_or_cbc: '2.10' +coin_or_cgl: '0.60' +coin_or_clp: '1.17' +coin_or_osi: '0.108' +coin_or_utils: '2.11' +cpu_optimization_target: nocona +cran_mirror: https://cran.r-project.org +cuda_compiler: cuda-nvcc +cuda_compiler_version: '12.4' +cudnn: '9' +cutensor: '2' +cxx_compiler: gxx +cxx_compiler_version: 11.2.0 +cyrus_sasl: 2.1.28 +dav1d: 1.2.1 +dbus: '1' +eigen: 3.3.7 +epoxy: '1.5' +expat: '2' +extend_keys: +- ignore_build_only_deps +- extend_keys +- pin_run_as_build +- ignore_version +ffmpeg: '6' +fftw: '3.3' +flatbuffers: 24.3.25 +fmt: '9' +fontconfig: '2' +fortran_compiler: gfortran +fortran_compiler_version: 11.2.0 +freeglut: '3' +freetds: '1' +freetype: '2' +freexl: '2' +fribidi: '1' +g2clib: '1.6' +gcab: '1' +gdbm: '1.18' +gdk_pixbuf: '2' +geos: 3.10.6 +geotiff: '1.7' +gettext: '0' +gflags: '2.2' +giflib: '5.2' +gl2ps: 1.4.2 +glew: '2.2' +glib: '2' +glog: '0.5' +glpk: '4.65' +glslang: '15' +gmp: '6' +gnupg: '2.4' +gnutls: '3.8' +go_compiler: go-nocgo +go_compiler_version: '1.21' +graphite2: '1' +gsl: '2.7' +gst_plugins_base: '1.24' +gst_plugins_good: '1.24' +gstreamer: '1.24' +gstreamer_orc: '0.4' +gtest: 1.14.0 +gtk3: '3' +gts: '0.7' +harfbuzz: '10' +hdf4: 4.2.13 +hdf5: 1.14.5 +hdfeos2: '2.20' +hdfeos5: '5.1' +icu: '73' +ignore_build_only_deps: +- numpy +- python +igraph: '0.10' +isl: '0.22' +jansson: '2' +jasper: '4' +jemalloc: '5' +jpeg: 9e +json_c: '0.16' +jsoncpp: 1.9.4 +jxrlib: '1.1' +kealib: '1.5' +krb5: '1.21' +lame: '3.100' +lcms2: '2' +leptonica: '1.82' +lerc: '4' +leveldb: '1.23' +libabseil: '20250127.0' +libaec: '1' +libaio: '0.3' +libapr: '1' +libapriconv: '1' +libaprutil: '1' +libarchive: '3.7' +libassuan: '3' +libavif: '1' +libbrotlicommon: '1.0' +libbrotlidec: '1.0' +libbrotlienc: '1.0' +libclang13: '14.0' +libclang_cpp14: '14.0' +libcrc32c: '1.1' +libcryptominisat: '5.6' +libcurl: '8' +libdap4: '3.19' +libdb: '6.2' +libde265: 1.0.15 +libdeflate: '1.22' +libdrm: '2.4' +libebm: 0.4.4 +libedit: '3.1' +libegl: '1' +libevent: 2.1.12 +libfaiss: 1.0.0 +libffi: '3.4' +libflac: '1.4' +libgcrypt: '1' +libgd: '2.3' +libgdal: '3.6' +libgit2: '1.6' +libgl: '1' +libgles: '1' +libglib: '2' +libglvnd: '1' +libglx: '1' +libgpg_error: '1' +libgrpc: '1.71' +libgsasl: '1' +libgsf: '1.14' +libheif: '1.19' +libiconv: '1' +libidn2: '2' +libjpeg_turbo: '3' +libkml: '1.3' +libksba: '1.6' +liblief: '0.16' +libllvm19: '19.1' +libmamba: '2.0' +libmambapy: '2.0' +libmicrohttpd: '0.9' +libmlir19: '19.1' +libnetcdf: '4' +libnghttp2: '1' +libnsl: '2.0' +libntlm: '1' +libogg: '1.3' +libopengl: '1' +libopus: '1' +libortools: '9.9' +libosqp: 0.6.3 +libpcap: '1.10' +libpciaccess: '0.18' +libpng: '1.6' +libpq: '17' +libprotobuf: 5.29.3 +libqdldl: 0.1.7 +librdkafka: '2.2' +libre2_11: '2024' +librsvg: '2' +libsentencepiece: 0.2.0 +libsndfile: '1.2' +libsodium: 1.0.18 +libspatialindex: 1.9.3 +libspatialite: '5.1' +libssh2: '1' +libtasn1: '4' +libtensorflow: 2.18.1 +libtensorflow_cc: 2.18.1 +libtheora: '1' +libthrift: '0.15' +libtiff: '4' +libtorch: '2.5' +libunistring: '0' +libunwind: '1' +libutf8proc: '2' +libuuid: '1' +libuv: '1' +libvorbis: '1' +libvpx: '1.13' +libwebp: 1.3.2 +libwebp_base: '1' +libxcb: '1' +libxkbcommon: '1' +libxml2: '2.13' +libxmlsec1: '1.3' +libxslt: '1' +libzopfli: '1.0' +lmdb: '0' +lua: '5' +lz4_c: '1.9' +lzo: '2' +mbedtls: '3.5' +metis: '5.1' +minizip: '4' +mkl: '2023' +mkl_service: '2' +mpc: '1' +mpfr: '4' +mpich: '4' +nanobind_abi: '15' +nccl: '2' +ncurses: '6' +nettle: '3.7' +nlopt: '2.7' +npth: '1' +nspr: '4' +nss: '3' +ntbtls: '0' +numpy: '2.1' +ocl_icd: '2' +oniguruma: '6.9' +openblas: '0' +openblas_devel: '0' +openh264: '2.6' +openjpeg: '2' +openldap: '2.6' +openmpi: '4.1' +openssl: '3' +orc: 2.1.1 +pango: '1' +pcre: '8' +pcre2: '10.42' +pdal: '2.5' +perl: '5.38' +pin_run_as_build: + python: + max_pin: x.x + min_pin: x.x + r-base: + max_pin: x.x + min_pin: x.x + libboost: + max_pin: x.x.x +pixman: '0' +popt: '1' +proj: 9.3.1 +ptscotch: 6.0.9 +pugixml: '1.11' +py_lief: '0.16' +pybind11_abi: '5' +pyqt: '6.7' +pyqtwebengine: '6.7' +python: '3.13' +python_igraph: '0.10' +python_impl: cpython +python_implementation: cpython +pytorch: '2.5' +qhull: '2020.2' +qpdf: '11' +qt: '6.7' +quantlib: '1' +r_base: 4.3.1 +r_implementation: r-base +r_version: 4.3.1 +rdkit: 2023.03.3 +re2: '2024' +readline: '8' +reproc: '14.2' +reproc_cpp: '14.2' +rhash: '1' +ruby: '3.2' +rust_compiler: rust +rust_compiler_version: 1.82.0 +s2n: 1.5.14 +scotch: 6.0.9 +serf: '1.3' +simdjson: '3.10' +sip: '6.10' +sleef: '3' +snappy: '1' +spdlog: '1' +spdlog_fmt_embed: '1' +spirv_tools: '2025' +sqlite: '3' +suitesparse: '7' +target_platform: linux-64 +tesseract: 5.2.0 +tiledb: '2.26' +tk: '8.6' +unixodbc: '2.3' +vc: '14' +vtk_base: 9.4.1 +vtk_io_ffmpeg: 9.4.1 +x264: 1!152.20180806 +xcb_util: '0.4' +xcb_util_cursor: '0.1' +xcb_util_image: '0.4' +xcb_util_keysyms: '0.4' +xcb_util_renderutil: '0.3' +xcb_util_wm: '0.4' +xerces_c: '3.2' +xorg_libice: '1' +xorg_libsm: '1' +xorg_libx11: '1' +xorg_libxau: '1' +xorg_libxcomposite: '0' +xorg_libxcursor: '1' +xorg_libxdamage: '1' +xorg_libxdmcp: '1' +xorg_libxext: '1' +xorg_libxfixes: '6' +xorg_libxft: '2' +xorg_libxi: '1' +xorg_libxinerama: '1.1' +xorg_libxmu: '1' +xorg_libxrandr: '1' +xorg_libxrender: '0.9' +xorg_libxscrnsaver: '1' +xorg_libxshmfence: '1' +xorg_libxt: '1' +xorg_libxtst: '1' +xorg_libxxf86vm: '1' +xorg_xextproto: '7' +xorg_xorgproto: '2024' +xxhash: 0.8.0 +xz: '5' +yaml: '0.2' +yaml_cpp: '0.8' +zfp: '1' +zip_keys: +- - python + - numpy +zlib: '1.2' +zlib_ng: '2.0' +zstd: '1.5' diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..631039c0ad6110aeade5ab7ed5662a56decf7ebb --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml @@ -0,0 +1,80 @@ +# This file created by conda-build 24.1.2 +# meta.yaml template originally from: +# /feedstock/recipe, last modified Thu May 29 13:40:42 2025 +# ------------------------------------------------ + +package: + name: httpcore + version: 1.0.9 +source: + sha256: 6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + url: https://pypi.io/packages/source/h/httpcore/httpcore-1.0.9.tar.gz +build: + number: '0' + script: /croot/httpcore_1748526048470/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehol/bin/python + -m pip install . -vv --no-deps --no-build-isolation + string: py313h06a4308_0 +requirements: + host: + - _libgcc_mutex 0.1 main + - _openmp_mutex 5.1 1_gnu + - bzip2 1.0.8 h5eee18b_6 + - ca-certificates 2025.2.25 h06a4308_0 + - expat 2.7.1 h6a678d5_0 + - hatch-fancy-pypi-readme 24.1.0 py313h06a4308_0 + - hatchling 1.27.0 py313h06a4308_0 + - ld_impl_linux-64 2.40 h12ee557_0 + - libffi 3.4.4 h6a678d5_1 + - libgcc-ng 11.2.0 h1234567_1 + - libgomp 11.2.0 h1234567_1 + - libmpdec 4.0.0 h5eee18b_0 + - libstdcxx-ng 11.2.0 h1234567_1 + - libuuid 1.41.5 h5eee18b_0 + - ncurses 6.4 h6a678d5_0 + - openssl 3.0.16 h5eee18b_0 + - packaging 24.2 py313h06a4308_0 + - pathspec 0.10.3 py313h06a4308_0 + - pip 25.1 pyhc872135_2 + - pluggy 1.5.0 py313h06a4308_0 + - python 3.13.2 hf623796_100_cp313 + - python_abi 3.13 0_cp313 + - readline 8.2 h5eee18b_0 + - setuptools 78.1.1 py313h06a4308_0 + - sqlite 3.45.3 h5eee18b_0 + - tk 8.6.14 h39e8969_0 + - trove-classifiers 2024.10.14 py313h06a4308_0 + - tzdata 2025b h04d1e81_0 + - wheel 0.45.1 py313h06a4308_0 + - xz 5.6.4 h5eee18b_1 + - zlib 1.2.13 h5eee18b_1 + run: + - certifi + - h11 >=0.16 + - python >=3.13,<3.14.0a0 + - python_abi 3.13.* *_cp313 +test: + commands: + - pip check + imports: + - httpcore + requires: + - pip +about: + description: The HTTP Core package provides a minimal low-level HTTP client, which + does one thing only. Sending HTTP requests. + dev_url: https://github.com/encode/httpcore + doc_url: https://www.encode.io/httpcore/ + home: https://github.com/encode/httpcore + license: BSD-3-Clause + license_family: BSD + license_file: LICENSE.md + summary: The next generation HTTP client. +extra: + copy_test_source_files: true + final: true + flow_run_id: 86f5e8db-440e-4094-93b2-b06eda562860 + recipe-maintainers: + - nicoddemus + - synapticarbors + remote_url: git@github.com:AnacondaRecipes/httpcore-feedstock.git + sha: bf922a7a787fe76f6d2a10110d0d35537d06e5ca diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml.template b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml.template new file mode 100644 index 0000000000000000000000000000000000000000..260a320312b783dbb1be9d0a07c0998de1f9588a --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/recipe/meta.yaml.template @@ -0,0 +1,49 @@ +{% set name = "httpcore" %} +{% set version = "1.0.9" %} + +package: + name: {{ name|lower }} + version: {{ version }} + +source: + url: https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz + sha256: 6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + +build: + number: 0 + script: {{ PYTHON }} -m pip install . -vv --no-deps --no-build-isolation + skip: True # [py<38] + +requirements: + host: + - pip + - python + - hatchling + - hatch-fancy-pypi-readme + run: + - python + - certifi + - h11 >=0.16 + +test: + requires: + - pip + imports: + - httpcore + commands: + - pip check + +about: + home: https://github.com/encode/httpcore + license: BSD-3-Clause + license_family: BSD + license_file: LICENSE.md + summary: The next generation HTTP client. + description: The HTTP Core package provides a minimal low-level HTTP client, which does one thing only. Sending HTTP requests. + dev_url: https://github.com/encode/httpcore + doc_url: https://www.encode.io/httpcore/ + +extra: + recipe-maintainers: + - nicoddemus + - synapticarbors diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/repodata_record.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/repodata_record.json new file mode 100644 index 0000000000000000000000000000000000000000..470e55006825a00717192bc47e14222bb159e518 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/repodata_record.json @@ -0,0 +1,25 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_0", + "build_number": 0, + "channel": "https://repo.anaconda.com/pkgs/main/linux-64/", + "constrains": [], + "depends": [ + "certifi", + "h11 >=0.16", + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "fn": "httpcore-1.0.9-py313h06a4308_0.conda", + "license": "BSD-3-Clause", + "license_family": "BSD", + "md5": "77016551f9607c23c6243632bf100507", + "name": "httpcore", + "platform": "linux", + "sha256": "43cf7bc5c9c8a5a7470c5b7c6b1ad0f67319bf4de5b958d7c1e7027e63029cc4", + "size": 127896, + "subdir": "linux-64", + "timestamp": 1748526107000, + "url": "https://repo.anaconda.com/pkgs/main/linux-64/httpcore-1.0.9-py313h06a4308_0.conda", + "version": "1.0.9" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.py new file mode 100644 index 0000000000000000000000000000000000000000..24bb6f7aad1264b275cb549c8c51ed89321ca760 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.py @@ -0,0 +1,3 @@ +print("import: 'httpcore'") +import httpcore + diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.sh b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1afc6b862fab8658b14cb4cc0345a4ee1f02ad0e --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/run_test.sh @@ -0,0 +1,8 @@ + + +set -ex + + + +pip check +exit 0 diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/test_time_dependencies.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/test_time_dependencies.json new file mode 100644 index 0000000000000000000000000000000000000000..215362c1832b66eb448cdeeadbb1db3470d5adb4 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/info/test/test_time_dependencies.json @@ -0,0 +1 @@ +["pip"] \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8056834e6714b089ef49847820064a1ae4b041fd --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA @@ -0,0 +1,625 @@ +Metadata-Version: 2.4 +Name: httpcore +Version: 1.0.9 +Summary: A minimal low-level HTTP client. +Project-URL: Documentation, https://www.encode.io/httpcore +Project-URL: Homepage, https://www.encode.io/httpcore/ +Project-URL: Source, https://github.com/encode/httpcore +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: certifi +Requires-Dist: h11>=0.16 +Provides-Extra: asyncio +Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: trio +Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio' +Description-Content-Type: text/markdown + +# HTTP Core + +[![Test Suite](https://github.com/encode/httpcore/workflows/Test%20Suite/badge.svg)](https://github.com/encode/httpcore/actions) +[![Package version](https://badge.fury.io/py/httpcore.svg)](https://pypi.org/project/httpcore/) + +> *Do one thing, and do it well.* + +The HTTP Core package provides a minimal low-level HTTP client, which does +one thing only. Sending HTTP requests. + +It does not provide any high level model abstractions over the API, +does not handle redirects, multipart uploads, building authentication headers, +transparent HTTP caching, URL parsing, session cookie handling, +content or charset decoding, handling JSON, environment based configuration +defaults, or any of that Jazz. + +Some things HTTP Core does do: + +* Sending HTTP requests. +* Thread-safe / task-safe connection pooling. +* HTTP(S) proxy & SOCKS proxy support. +* Supports HTTP/1.1 and HTTP/2. +* Provides both sync and async interfaces. +* Async backend support for `asyncio` and `trio`. + +## Requirements + +Python 3.8+ + +## Installation + +For HTTP/1.1 only support, install with: + +```shell +$ pip install httpcore +``` + +There are also a number of optional extras available... + +```shell +$ pip install httpcore['asyncio,trio,http2,socks'] +``` + +## Sending requests + +Send an HTTP request: + +```python +import httpcore + +response = httpcore.request("GET", "https://www.example.com/") + +print(response) +# +print(response.status) +# 200 +print(response.headers) +# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] +print(response.content) +# b'\n\n\nExample Domain\n\n\n ...' +``` + +The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides. + +```python +import httpcore + +http = httpcore.ConnectionPool() +response = http.request("GET", "https://www.example.com/") +``` + +Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/). + +## Motivation + +You *probably* don't want to be using HTTP Core directly. It might make sense if +you're writing something like a proxy service in Python, and you just want +something at the lowest possible level, but more typically you'll want to use +a higher level client library, such as `httpx`. + +The motivation for `httpcore` is: + +* To provide a reusable low-level client library, that other packages can then build on top of. +* To provide a *really clear interface split* between the networking code and client logic, + so that each is easier to understand and reason about in isolation. + +## Dependencies + +The `httpcore` package has the following dependencies... + +* `h11` +* `certifi` + +And the following optional extras... + +* `anyio` - Required by `pip install httpcore['asyncio']`. +* `trio` - Required by `pip install httpcore['trio']`. +* `h2` - Required by `pip install httpcore['http2']`. +* `socksio` - Required by `pip install httpcore['socks']`. + +## Versioning + +We use [SEMVER for our versioning policy](https://semver.org/). + +For changes between package versions please see our [project changelog](CHANGELOG.md). + +We recommend pinning your requirements either the most current major version, or a more specific version range: + +```python +pip install 'httpcore==1.*' +``` +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## Version 1.0.9 (April 24th, 2025) + +- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008) + +## Version 1.0.8 (April 11th, 2025) + +- Fix `AttributeError` when importing on Python 3.14. (#1005) + +## Version 1.0.7 (November 15th, 2024) + +- Support `proxy=…` configuration on `ConnectionPool()`. (#974) + +## Version 1.0.6 (October 1st, 2024) + +- Relax `trio` dependency pinning. (#956) +- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955) +- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918) + +## 1.0.5 (March 27th, 2024) + +- Handle `EndOfStream` exception for anyio backend. (#899) +- Allow trio `0.25.*` series in package dependancies. (#903) + +## 1.0.4 (February 21st, 2024) + +- Add `target` request extension. (#888) +- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882) + +## 1.0.3 (February 13th, 2024) + +- Fix support for async cancellations. (#880) +- Fix trace extension when used with socks proxy. (#849) +- Fix SSL context for connections using the "wss" scheme (#869) + +## 1.0.2 (November 10th, 2023) + +- Fix `float("inf")` timeouts in `Event.wait` function. (#846) + +## 1.0.1 (November 3rd, 2023) + +- Fix pool timeout to account for the total time spent retrying. (#823) +- Raise a neater RuntimeError when the correct async deps are not installed. (#826) +- Add support for synchronous TLS-in-TLS streams. (#840) + +## 1.0.0 (October 6th, 2023) + +From version 1.0 our async support is now optional, as the package has minimal dependencies by default. + +For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`. + +The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/. + +- Async support becomes fully optional. (#809) +- Add support for Python 3.12. (#807) + +## 0.18.0 (September 8th, 2023) + +- Add support for HTTPS proxies. (#745, #786) +- Drop Python 3.7 support. (#727) +- Handle `sni_hostname` extension with SOCKS proxy. (#774) +- Handle HTTP/1.1 half-closed connections gracefully. (#641) +- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762) + +## 0.17.3 (July 5th, 2023) + +- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726) +- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699) +- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730) +- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717) +- Drop Python 3.7 support. (#727) + +## 0.17.2 (May 23th, 2023) + +- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668) +- Improve logging with per-module logger names. (#690) +- Add `sni_hostname` request extension. (#696) +- Resolve race condition during import of `anyio` package. (#692) +- Enable TCP_NODELAY for all synchronous sockets. (#651) + +## 0.17.1 (May 17th, 2023) + +- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669) +- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678) +- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679) +- Fix edge-case exception when removing requests from the connection pool. (#680) +- Fix pool timeout edge-case. (#688) + +## 0.17.0 (March 16th, 2023) + +- Add DEBUG level logging. (#648) +- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652) +- Increase the allowable HTTP header size to 100kB. (#647) +- Add `retries` option to SOCKS proxy classes. (#643) + +## 0.16.3 (December 20th, 2022) + +- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625) +- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637) +- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631) +- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639) + +## 0.16.2 (November 25th, 2022) + +- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627) +- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619) + +## 0.16.1 (November 17th, 2022) + +- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605) + +## 0.16.0 (October 11th, 2022) + +- Support HTTP/1.1 informational responses. (#581) +- Fix async cancellation behaviour. (#580) +- Support `h11` 0.14. (#579) + +## 0.15.0 (May 17th, 2022) + +- Drop Python 3.6 support (#535) +- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506) +- Switch to explicit `typing.Optional` for type hints. (#513) +- For `trio` map OSError exceptions to `ConnectError`. (#543) + +## 0.14.7 (February 4th, 2022) + +- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502) +- Fix AttributeError that happened when Socks5Connection were terminated. (#501) + +## 0.14.6 (February 1st, 2022) + +- Fix SOCKS support for `http://` URLs. (#492) +- Resolve race condition around exceptions during streaming a response. (#491) + +## 0.14.5 (January 18th, 2022) + +- SOCKS proxy support. (#478) +- Add proxy_auth argument to HTTPProxy. (#481) +- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479) + +## 0.14.4 (January 5th, 2022) + +- Support HTTP/2 on HTTPS tunnelling proxies. (#468) +- Fix proxy headers missing on HTTP forwarding. (#456) +- Only instantiate SSL context if required. (#457) +- More robust HTTP/2 handling. (#253, #439, #440, #441) + +## 0.14.3 (November 17th, 2021) + +- Fix race condition when removing closed connections from the pool. (#437) + +## 0.14.2 (November 16th, 2021) + +- Failed connections no longer remain in the pool. (Pull #433) + +## 0.14.1 (November 12th, 2021) + +- `max_connections` becomes optional. (Pull #429) +- `certifi` is now included in the install dependancies. (Pull #428) +- `h2` is now strictly optional. (Pull #428) + +## 0.14.0 (November 11th, 2021) + +The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly. + +Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage. + +See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background. + +There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to... + +* Log the point at which the connection is established, and the IP/port on which it is made. +* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.) +* Log SSL version info / certificate info. + +Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not. + +## 0.13.7 (September 13th, 2021) + +- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403) + +## 0.13.6 (June 15th, 2021) + +### Fixed + +- Close sockets when read or write timeouts occur. (Pull #365) + +## 0.13.5 (June 14th, 2021) + +### Fixed + +- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362) + +## 0.13.4 (June 9th, 2021) + +### Added + +- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354) + +### Fixed + +- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511). + +## 0.13.3 (May 6th, 2021) + +### Added + +- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333) + +### Fixed + +- Handle cases where environment does not provide `select.poll` support. (Pull #331) + +## 0.13.2 (April 29th, 2021) + +### Added + +- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313) + +## 0.13.1 (April 28th, 2021) + +### Fixed + +- More resiliant testing for closed connections. (Pull #311) +- Don't raise exceptions on ungraceful connection closes. (Pull #310) + +## 0.13.0 (April 21st, 2021) + +The 0.13 release updates the core API in order to match the HTTPX Transport API, +introduced in HTTPX 0.18 onwards. + +An example of making requests with the new interface is: + +```python +with httpcore.SyncConnectionPool() as http: + status_code, headers, stream, extensions = http.handle_request( + method=b'GET', + url=(b'https', b'example.org', 443, b'/'), + headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] + stream=httpcore.ByteStream(b''), + extensions={} + ) + body = stream.read() + print(status_code, body) +``` + +### Changed + +- The `.request()` method is now `handle_request()`. (Pull #296) +- The `.arequest()` method is now `.handle_async_request()`. (Pull #296) +- The `headers` argument is no longer optional. (Pull #296) +- The `stream` argument is no longer optional. (Pull #296) +- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296) +- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296) +- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296) +- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296) + +### Added + +- Streams now support a `.read()` interface. (Pull #296) + +### Fixed + +- Task cancellation no longer leaks connections from the connection pool. (Pull #305) + +## 0.12.3 (December 7th, 2020) + +### Fixed + +- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167) +- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236) +- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243) +- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244) +- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249) + +## 0.12.2 (November 20th, 2020) + +### Fixed + +- Properly wrap connect errors on the asyncio backend. (Pull #235) +- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237) + +## 0.12.1 (November 7th, 2020) + +### Added + +- Add connect retries. (Pull #221) + +### Fixed + +- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185) +- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223) +- Properly wrap OS errors when using `trio`. (Pull #225) + +## 0.12.0 (October 6th, 2020) + +### Changed + +- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104) + +### Added + +- Add Python 3.9 to officially supported versions. + +### Fixed + +- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201) + +## 0.11.1 (September 28nd, 2020) + +### Fixed + +- Add await to async semaphore release() coroutine (#197) +- Drop incorrect curio classifier (#192) + +## 0.11.0 (September 22nd, 2020) + +The Transport API with 0.11.0 has a couple of significant changes. + +Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features +such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections. + +The interface changes from: + +```python +def request(method, url, headers, stream, timeout): + return (http_version, status_code, reason, headers, stream) +``` + +To instead including an optional dictionary of extensions on the request and response: + +```python +def request(method, url, headers, stream, ext): + return (status_code, headers, stream, ext) +``` + +Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes. + +In particular: + +* Trailing headers support. +* HTTP/2 Server Push +* sendfile. +* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming. +* Exposing debug information out of the API, including template name, template context. + +Currently extensions are limited to: + +* request: `timeout` - Optional. Timeout dictionary. +* response: `http_version` - Optional. Include the HTTP version used on the response. +* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*. + +See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this. + +Secondly, the async version of `request` is now namespaced as `arequest`. + +This allows concrete transports to support both sync and async implementations on the same class. + +### Added + +- Add curio support. (Pull #168) +- Add anyio support, with `backend="anyio"`. (Pull #169) + +### Changed + +- Update the Transport API to use 'ext' for optional extensions. (Pull #190) +- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189) + +## 0.10.2 (August 20th, 2020) + +### Added + +- Added Unix Domain Socket support. (Pull #139) + +### Fixed + +- Always include the port on proxy CONNECT requests. (Pull #154) +- Fix `max_keepalive_connections` configuration. (Pull #153) +- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164) + +## 0.10.1 (August 7th, 2020) + +- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes. + +## 0.10.0 (August 7th, 2020) + +The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional. + +Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support. + +### Added + +- HTTP/2 support becomes optional. (Pull #121, #130) +- Add `local_address=...` support. (Pull #100, #134) +- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133) +- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129) +- Add `UnsupportedProtocol` exception. (Pull #128) +- Add `.get_connection_info()` method. (Pull #102, #137) +- Add better TRACE logs. (Pull #101) + +### Changed + +- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140) + +### Fixed + +- Improve handling of server disconnects. (Pull #112) + +## 0.9.1 (May 27th, 2020) + +### Fixed + +- Proper host resolution for sync case, including IPv6 support. (Pull #97) +- Close outstanding connections when connection pool is closed. (Pull #98) + +## 0.9.0 (May 21th, 2020) + +### Changed + +- URL port becomes an `Optional[int]` instead of `int`. (Pull #92) + +### Fixed + +- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90) +- Remove incorrect debug log. (Pull #83) + +## 0.8.4 (May 11th, 2020) + +### Added + +- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables +and TRACE level logging. (Pull #79) + +### Fixed + +- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81) + +## 0.8.3 (May 6rd, 2020) + +### Fixed + +- Include `Host` and `Accept` headers on proxy "CONNECT" requests. +- De-duplicate any headers also contained in proxy_headers. +- HTTP/2 flag not being passed down to proxy connections. + +## 0.8.2 (May 3rd, 2020) + +### Fixed + +- Fix connections using proxy forwarding requests not being added to the +connection pool properly. (Pull #70) + +## 0.8.1 (April 30th, 2020) + +### Changed + +- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts. + +## 0.8.0 (April 30th, 2020) + +### Fixed + +- Fixed tunnel proxy support. + +### Added + +- New `TimeoutException` base class. + +## 0.7.0 (March 5th, 2020) + +- First integration with HTTPX. diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0d40708bbd839cb751e49d5043ab5036d624851e --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD @@ -0,0 +1,70 @@ +httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529 +httpcore-1.0.9.dist-info/RECORD,, +httpcore-1.0.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +httpcore-1.0.9.dist-info/direct_url.json,sha256=SxUvuFZOS178CTq0R1ptPLloY4w-iigNTESS4dB9w1M,68 +httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518 +httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445 +httpcore/__pycache__/__init__.cpython-313.pyc,, +httpcore/__pycache__/_api.cpython-313.pyc,, +httpcore/__pycache__/_exceptions.cpython-313.pyc,, +httpcore/__pycache__/_models.cpython-313.pyc,, +httpcore/__pycache__/_ssl.cpython-313.pyc,, +httpcore/__pycache__/_synchronization.cpython-313.pyc,, +httpcore/__pycache__/_trace.cpython-313.pyc,, +httpcore/__pycache__/_utils.cpython-313.pyc,, +httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146 +httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221 +httpcore/_async/__pycache__/__init__.cpython-313.pyc,, +httpcore/_async/__pycache__/connection.cpython-313.pyc,, +httpcore/_async/__pycache__/connection_pool.cpython-313.pyc,, +httpcore/_async/__pycache__/http11.cpython-313.pyc,, +httpcore/_async/__pycache__/http2.cpython-313.pyc,, +httpcore/_async/__pycache__/http_proxy.cpython-313.pyc,, +httpcore/_async/__pycache__/interfaces.cpython-313.pyc,, +httpcore/_async/__pycache__/socks_proxy.cpython-313.pyc,, +httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449 +httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307 +httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880 +httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936 +httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701 +httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455 +httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841 +httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpcore/_backends/__pycache__/__init__.cpython-313.pyc,, +httpcore/_backends/__pycache__/anyio.cpython-313.pyc,, +httpcore/_backends/__pycache__/auto.cpython-313.pyc,, +httpcore/_backends/__pycache__/base.cpython-313.pyc,, +httpcore/_backends/__pycache__/mock.cpython-313.pyc,, +httpcore/_backends/__pycache__/sync.cpython-313.pyc,, +httpcore/_backends/__pycache__/trio.cpython-313.pyc,, +httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252 +httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662 +httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042 +httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077 +httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977 +httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996 +httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184 +httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623 +httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187 +httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141 +httpcore/_sync/__pycache__/__init__.cpython-313.pyc,, +httpcore/_sync/__pycache__/connection.cpython-313.pyc,, +httpcore/_sync/__pycache__/connection_pool.cpython-313.pyc,, +httpcore/_sync/__pycache__/http11.cpython-313.pyc,, +httpcore/_sync/__pycache__/http2.cpython-313.pyc,, +httpcore/_sync/__pycache__/http_proxy.cpython-313.pyc,, +httpcore/_sync/__pycache__/interfaces.cpython-313.pyc,, +httpcore/_sync/__pycache__/socks_proxy.cpython-313.pyc,, +httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238 +httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955 +httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476 +httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400 +httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463 +httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344 +httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614 +httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434 +httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952 +httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537 +httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/REQUESTED b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/direct_url.json b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..4185bd732d4b146671259f295926082def8749a6 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/httpcore_1748526048470/work"} \ No newline at end of file diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..311b2b56c53f678ab95fc0def708c675d521a807 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/__init__.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a92dc4a440bdf6f259ec1083c89c817eb7b631b --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/__init__.py @@ -0,0 +1,141 @@ +from ._api import request, stream +from ._async import ( + AsyncConnectionInterface, + AsyncConnectionPool, + AsyncHTTP2Connection, + AsyncHTTP11Connection, + AsyncHTTPConnection, + AsyncHTTPProxy, + AsyncSOCKSProxy, +) +from ._backends.base import ( + SOCKET_OPTION, + AsyncNetworkBackend, + AsyncNetworkStream, + NetworkBackend, + NetworkStream, +) +from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream +from ._backends.sync import SyncBackend +from ._exceptions import ( + ConnectError, + ConnectionNotAvailable, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from ._models import URL, Origin, Proxy, Request, Response +from ._ssl import default_ssl_context +from ._sync import ( + ConnectionInterface, + ConnectionPool, + HTTP2Connection, + HTTP11Connection, + HTTPConnection, + HTTPProxy, + SOCKSProxy, +) + +# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed. +try: + from ._backends.anyio import AnyIOBackend +except ImportError: # pragma: nocover + + class AnyIOBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = ( + "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." + ) + raise RuntimeError(msg) + + +# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed. +try: + from ._backends.trio import TrioBackend +except ImportError: # pragma: nocover + + class TrioBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." + raise RuntimeError(msg) + + +__all__ = [ + # top-level requests + "request", + "stream", + # models + "Origin", + "URL", + "Request", + "Response", + "Proxy", + # async + "AsyncHTTPConnection", + "AsyncConnectionPool", + "AsyncHTTPProxy", + "AsyncHTTP11Connection", + "AsyncHTTP2Connection", + "AsyncConnectionInterface", + "AsyncSOCKSProxy", + # sync + "HTTPConnection", + "ConnectionPool", + "HTTPProxy", + "HTTP11Connection", + "HTTP2Connection", + "ConnectionInterface", + "SOCKSProxy", + # network backends, implementations + "SyncBackend", + "AnyIOBackend", + "TrioBackend", + # network backends, mock implementations + "AsyncMockBackend", + "AsyncMockStream", + "MockBackend", + "MockStream", + # network backends, interface + "AsyncNetworkStream", + "AsyncNetworkBackend", + "NetworkStream", + "NetworkBackend", + # util + "default_ssl_context", + "SOCKET_OPTION", + # exceptions + "ConnectionNotAvailable", + "ProxyError", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "UnsupportedProtocol", + "TimeoutException", + "PoolTimeout", + "ConnectTimeout", + "ReadTimeout", + "WriteTimeout", + "NetworkError", + "ConnectError", + "ReadError", + "WriteError", +] + +__version__ = "1.0.9" + + +__locals = locals() +for __name in __all__: + # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 + if not __name.startswith(("__", "SOCKET_OPTION")): + setattr(__locals[__name], "__module__", "httpcore") # noqa diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_api.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..38b961d10de88bebc98c758d0d1f14af1e7c0370 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_api.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import contextlib +import typing + +from ._models import URL, Extensions, HeaderTypes, Response +from ._sync.connection_pool import ConnectionPool + + +def request( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> Response: + """ + Sends an HTTP request, returning the response. + + ``` + response = httpcore.request("GET", "https://www.example.com/") + ``` + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + return pool.request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + + +@contextlib.contextmanager +def stream( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> typing.Iterator[Response]: + """ + Sends an HTTP request, returning the response within a content manager. + + ``` + with httpcore.stream("GET", "https://www.example.com/") as response: + ... + ``` + + When using the `stream()` function, the body of the response will not be + automatically read. If you want to access the response body you should + either use `content = response.read()`, or `for chunk in response.iter_content()`. + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + with pool.stream( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) as response: + yield response diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/__init__.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88dc7f01e132933728cbcf45c88ce82e85ddf65f --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/__init__.py @@ -0,0 +1,39 @@ +from .connection import AsyncHTTPConnection +from .connection_pool import AsyncConnectionPool +from .http11 import AsyncHTTP11Connection +from .http_proxy import AsyncHTTPProxy +from .interfaces import AsyncConnectionInterface + +try: + from .http2 import AsyncHTTP2Connection +except ImportError: # pragma: nocover + + class AsyncHTTP2Connection: # type: ignore + def __init__(self, *args, **kwargs) -> None: # type: ignore + raise RuntimeError( + "Attempted to use http2 support, but the `h2` package is not " + "installed. Use 'pip install httpcore[http2]'." + ) + + +try: + from .socks_proxy import AsyncSOCKSProxy +except ImportError: # pragma: nocover + + class AsyncSOCKSProxy: # type: ignore + def __init__(self, *args, **kwargs) -> None: # type: ignore + raise RuntimeError( + "Attempted to use SOCKS support, but the `socksio` package is not " + "installed. Use 'pip install httpcore[socks]'." + ) + + +__all__ = [ + "AsyncHTTPConnection", + "AsyncConnectionPool", + "AsyncHTTPProxy", + "AsyncHTTP11Connection", + "AsyncHTTP2Connection", + "AsyncConnectionInterface", + "AsyncSOCKSProxy", +] diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..b42581dff8aabf4c2ef80ffda26296e1b368d693 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import itertools +import logging +import ssl +import types +import typing + +from .._backends.auto import AutoBackend +from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream +from .._exceptions import ConnectError, ConnectTimeout +from .._models import Origin, Request, Response +from .._ssl import default_ssl_context +from .._synchronization import AsyncLock +from .._trace import Trace +from .http11 import AsyncHTTP11Connection +from .interfaces import AsyncConnectionInterface + +RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc. + + +logger = logging.getLogger("httpcore.connection") + + +def exponential_backoff(factor: float) -> typing.Iterator[float]: + """ + Generate a geometric sequence that has a ratio of 2 and starts with 0. + + For example: + - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` + - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` + """ + yield 0 + for n in itertools.count(): + yield factor * 2**n + + +class AsyncHTTPConnection(AsyncConnectionInterface): + def __init__( + self, + origin: Origin, + ssl_context: ssl.SSLContext | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: AsyncNetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + self._origin = origin + self._ssl_context = ssl_context + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._retries = retries + self._local_address = local_address + self._uds = uds + + self._network_backend: AsyncNetworkBackend = ( + AutoBackend() if network_backend is None else network_backend + ) + self._connection: AsyncConnectionInterface | None = None + self._connect_failed: bool = False + self._request_lock = AsyncLock() + self._socket_options = socket_options + + async def handle_async_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection to {self._origin}" + ) + + try: + async with self._request_lock: + if self._connection is None: + stream = await self._connect(request) + + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + if http2_negotiated or (self._http2 and not self._http1): + from .http2 import AsyncHTTP2Connection + + self._connection = AsyncHTTP2Connection( + origin=self._origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = AsyncHTTP11Connection( + origin=self._origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + except BaseException as exc: + self._connect_failed = True + raise exc + + return await self._connection.handle_async_request(request) + + async def _connect(self, request: Request) -> AsyncNetworkStream: + timeouts = request.extensions.get("timeout", {}) + sni_hostname = request.extensions.get("sni_hostname", None) + timeout = timeouts.get("connect", None) + + retries_left = self._retries + delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) + + while True: + try: + if self._uds is None: + kwargs = { + "host": self._origin.host.decode("ascii"), + "port": self._origin.port, + "local_address": self._local_address, + "timeout": timeout, + "socket_options": self._socket_options, + } + async with Trace("connect_tcp", logger, request, kwargs) as trace: + stream = await self._network_backend.connect_tcp(**kwargs) + trace.return_value = stream + else: + kwargs = { + "path": self._uds, + "timeout": timeout, + "socket_options": self._socket_options, + } + async with Trace( + "connect_unix_socket", logger, request, kwargs + ) as trace: + stream = await self._network_backend.connect_unix_socket( + **kwargs + ) + trace.return_value = stream + + if self._origin.scheme in (b"https", b"wss"): + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": sni_hostname + or self._origin.host.decode("ascii"), + "timeout": timeout, + } + async with Trace("start_tls", logger, request, kwargs) as trace: + stream = await stream.start_tls(**kwargs) + trace.return_value = stream + return stream + except (ConnectError, ConnectTimeout): + if retries_left <= 0: + raise + retries_left -= 1 + delay = next(delays) + async with Trace("retry", logger, request, kwargs) as trace: + await self._network_backend.sleep(delay) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + async def aclose(self) -> None: + if self._connection is not None: + async with Trace("close", logger, None, {}): + await self._connection.aclose() + + def is_available(self) -> bool: + if self._connection is None: + # If HTTP/2 support is enabled, and the resulting connection could + # end up as HTTP/2 then we should indicate the connection as being + # available to service multiple requests. + return ( + self._http2 + and (self._origin.scheme == b"https" or not self._http1) + and not self._connect_failed + ) + return self._connection.is_available() + + def has_expired(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.has_expired() + + def is_idle(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.is_idle() + + def is_closed(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.is_closed() + + def info(self) -> str: + if self._connection is None: + return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" + return self._connection.info() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + async def __aenter__(self) -> AsyncHTTPConnection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + await self.aclose() diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection_pool.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..96e973d0ce223f6bed9be9e6a6a2f3c01622c611 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/connection_pool.py @@ -0,0 +1,420 @@ +from __future__ import annotations + +import ssl +import sys +import types +import typing + +from .._backends.auto import AutoBackend +from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend +from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol +from .._models import Origin, Proxy, Request, Response +from .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLock +from .connection import AsyncHTTPConnection +from .interfaces import AsyncConnectionInterface, AsyncRequestInterface + + +class AsyncPoolRequest: + def __init__(self, request: Request) -> None: + self.request = request + self.connection: AsyncConnectionInterface | None = None + self._connection_acquired = AsyncEvent() + + def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None: + self.connection = connection + self._connection_acquired.set() + + def clear_connection(self) -> None: + self.connection = None + self._connection_acquired = AsyncEvent() + + async def wait_for_connection( + self, timeout: float | None = None + ) -> AsyncConnectionInterface: + if self.connection is None: + await self._connection_acquired.wait(timeout=timeout) + assert self.connection is not None + return self.connection + + def is_queued(self) -> bool: + return self.connection is None + + +class AsyncConnectionPool(AsyncRequestInterface): + """ + A connection pool for making HTTP requests. + """ + + def __init__( + self, + ssl_context: ssl.SSLContext | None = None, + proxy: Proxy | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: AsyncNetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish a + connection. + local_address: Local address to connect from. Can also be used to connect + using a particular address family. Using `local_address="0.0.0.0"` + will connect using an `AF_INET` address (IPv4), while using + `local_address="::"` will connect using an `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + socket_options: Socket options that have to be included + in the TCP socket when the connection was established. + """ + self._ssl_context = ssl_context + self._proxy = proxy + self._max_connections = ( + sys.maxsize if max_connections is None else max_connections + ) + self._max_keepalive_connections = ( + sys.maxsize + if max_keepalive_connections is None + else max_keepalive_connections + ) + self._max_keepalive_connections = min( + self._max_connections, self._max_keepalive_connections + ) + + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._retries = retries + self._local_address = local_address + self._uds = uds + + self._network_backend = ( + AutoBackend() if network_backend is None else network_backend + ) + self._socket_options = socket_options + + # The mutable state on a connection pool is the queue of incoming requests, + # and the set of connections that are servicing those requests. + self._connections: list[AsyncConnectionInterface] = [] + self._requests: list[AsyncPoolRequest] = [] + + # We only mutate the state of the connection pool within an 'optional_thread_lock' + # context. This holds a threading lock unless we're running in async mode, + # in which case it is a no-op. + self._optional_thread_lock = AsyncThreadLock() + + def create_connection(self, origin: Origin) -> AsyncConnectionInterface: + if self._proxy is not None: + if self._proxy.url.scheme in (b"socks5", b"socks5h"): + from .socks_proxy import AsyncSocks5Connection + + return AsyncSocks5Connection( + proxy_origin=self._proxy.url.origin, + proxy_auth=self._proxy.auth, + remote_origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + elif origin.scheme == b"http": + from .http_proxy import AsyncForwardHTTPConnection + + return AsyncForwardHTTPConnection( + proxy_origin=self._proxy.url.origin, + proxy_headers=self._proxy.headers, + proxy_ssl_context=self._proxy.ssl_context, + remote_origin=origin, + keepalive_expiry=self._keepalive_expiry, + network_backend=self._network_backend, + ) + from .http_proxy import AsyncTunnelHTTPConnection + + return AsyncTunnelHTTPConnection( + proxy_origin=self._proxy.url.origin, + proxy_headers=self._proxy.headers, + proxy_ssl_context=self._proxy.ssl_context, + remote_origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + return AsyncHTTPConnection( + origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + retries=self._retries, + local_address=self._local_address, + uds=self._uds, + network_backend=self._network_backend, + socket_options=self._socket_options, + ) + + @property + def connections(self) -> list[AsyncConnectionInterface]: + """ + Return a list of the connections currently in the pool. + + For example: + + ```python + >>> pool.connections + [ + , + , + , + ] + ``` + """ + return list(self._connections) + + async def handle_async_request(self, request: Request) -> Response: + """ + Send an HTTP request, and return an HTTP response. + + This is the core implementation that is called into by `.request()` or `.stream()`. + """ + scheme = request.url.scheme.decode() + if scheme == "": + raise UnsupportedProtocol( + "Request URL is missing an 'http://' or 'https://' protocol." + ) + if scheme not in ("http", "https", "ws", "wss"): + raise UnsupportedProtocol( + f"Request URL has an unsupported protocol '{scheme}://'." + ) + + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("pool", None) + + with self._optional_thread_lock: + # Add the incoming request to our request queue. + pool_request = AsyncPoolRequest(request) + self._requests.append(pool_request) + + try: + while True: + with self._optional_thread_lock: + # Assign incoming requests to available connections, + # closing or creating new connections as required. + closing = self._assign_requests_to_connections() + await self._close_connections(closing) + + # Wait until this request has an assigned connection. + connection = await pool_request.wait_for_connection(timeout=timeout) + + try: + # Send the request on the assigned connection. + response = await connection.handle_async_request( + pool_request.request + ) + except ConnectionNotAvailable: + # In some cases a connection may initially be available to + # handle a request, but then become unavailable. + # + # In this case we clear the connection and try again. + pool_request.clear_connection() + else: + break # pragma: nocover + + except BaseException as exc: + with self._optional_thread_lock: + # For any exception or cancellation we remove the request from + # the queue, and then re-assign requests to connections. + self._requests.remove(pool_request) + closing = self._assign_requests_to_connections() + + await self._close_connections(closing) + raise exc from None + + # Return the response. Note that in this case we still have to manage + # the point at which the response is closed. + assert isinstance(response.stream, typing.AsyncIterable) + return Response( + status=response.status, + headers=response.headers, + content=PoolByteStream( + stream=response.stream, pool_request=pool_request, pool=self + ), + extensions=response.extensions, + ) + + def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]: + """ + Manage the state of the connection pool, assigning incoming + requests to connections as available. + + Called whenever a new request is added or removed from the pool. + + Any closing connections are returned, allowing the I/O for closing + those connections to be handled seperately. + """ + closing_connections = [] + + # First we handle cleaning up any connections that are closed, + # have expired their keep-alive, or surplus idle connections. + for connection in list(self._connections): + if connection.is_closed(): + # log: "removing closed connection" + self._connections.remove(connection) + elif connection.has_expired(): + # log: "closing expired connection" + self._connections.remove(connection) + closing_connections.append(connection) + elif ( + connection.is_idle() + and len([connection.is_idle() for connection in self._connections]) + > self._max_keepalive_connections + ): + # log: "closing idle connection" + self._connections.remove(connection) + closing_connections.append(connection) + + # Assign queued requests to connections. + queued_requests = [request for request in self._requests if request.is_queued()] + for pool_request in queued_requests: + origin = pool_request.request.url.origin + available_connections = [ + connection + for connection in self._connections + if connection.can_handle_request(origin) and connection.is_available() + ] + idle_connections = [ + connection for connection in self._connections if connection.is_idle() + ] + + # There are three cases for how we may be able to handle the request: + # + # 1. There is an existing connection that can handle the request. + # 2. We can create a new connection to handle the request. + # 3. We can close an idle connection and then create a new connection + # to handle the request. + if available_connections: + # log: "reusing existing connection" + connection = available_connections[0] + pool_request.assign_to_connection(connection) + elif len(self._connections) < self._max_connections: + # log: "creating new connection" + connection = self.create_connection(origin) + self._connections.append(connection) + pool_request.assign_to_connection(connection) + elif idle_connections: + # log: "closing idle connection" + connection = idle_connections[0] + self._connections.remove(connection) + closing_connections.append(connection) + # log: "creating new connection" + connection = self.create_connection(origin) + self._connections.append(connection) + pool_request.assign_to_connection(connection) + + return closing_connections + + async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None: + # Close connections which have been removed from the pool. + with AsyncShieldCancellation(): + for connection in closing: + await connection.aclose() + + async def aclose(self) -> None: + # Explicitly close the connection pool. + # Clears all existing requests and connections. + with self._optional_thread_lock: + closing_connections = list(self._connections) + self._connections = [] + await self._close_connections(closing_connections) + + async def __aenter__(self) -> AsyncConnectionPool: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + await self.aclose() + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + with self._optional_thread_lock: + request_is_queued = [request.is_queued() for request in self._requests] + connection_is_idle = [ + connection.is_idle() for connection in self._connections + ] + + num_active_requests = request_is_queued.count(False) + num_queued_requests = request_is_queued.count(True) + num_active_connections = connection_is_idle.count(False) + num_idle_connections = connection_is_idle.count(True) + + requests_info = ( + f"Requests: {num_active_requests} active, {num_queued_requests} queued" + ) + connection_info = ( + f"Connections: {num_active_connections} active, {num_idle_connections} idle" + ) + + return f"<{class_name} [{requests_info} | {connection_info}]>" + + +class PoolByteStream: + def __init__( + self, + stream: typing.AsyncIterable[bytes], + pool_request: AsyncPoolRequest, + pool: AsyncConnectionPool, + ) -> None: + self._stream = stream + self._pool_request = pool_request + self._pool = pool + self._closed = False + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + try: + async for part in self._stream: + yield part + except BaseException as exc: + await self.aclose() + raise exc from None + + async def aclose(self) -> None: + if not self._closed: + self._closed = True + with AsyncShieldCancellation(): + if hasattr(self._stream, "aclose"): + await self._stream.aclose() + + with self._pool._optional_thread_lock: + self._pool._requests.remove(self._pool_request) + closing = self._pool._assign_requests_to_connections() + + await self._pool._close_connections(closing) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http11.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http11.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d6d709852b137a862cfe2b3af42dc790fa705d --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http11.py @@ -0,0 +1,379 @@ +from __future__ import annotations + +import enum +import logging +import ssl +import time +import types +import typing + +import h11 + +from .._backends.base import AsyncNetworkStream +from .._exceptions import ( + ConnectionNotAvailable, + LocalProtocolError, + RemoteProtocolError, + WriteError, + map_exceptions, +) +from .._models import Origin, Request, Response +from .._synchronization import AsyncLock, AsyncShieldCancellation +from .._trace import Trace +from .interfaces import AsyncConnectionInterface + +logger = logging.getLogger("httpcore.http11") + + +# A subset of `h11.Event` types supported by `_send_event` +H11SendEvent = typing.Union[ + h11.Request, + h11.Data, + h11.EndOfMessage, +] + + +class HTTPConnectionState(enum.IntEnum): + NEW = 0 + ACTIVE = 1 + IDLE = 2 + CLOSED = 3 + + +class AsyncHTTP11Connection(AsyncConnectionInterface): + READ_NUM_BYTES = 64 * 1024 + MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024 + + def __init__( + self, + origin: Origin, + stream: AsyncNetworkStream, + keepalive_expiry: float | None = None, + ) -> None: + self._origin = origin + self._network_stream = stream + self._keepalive_expiry: float | None = keepalive_expiry + self._expire_at: float | None = None + self._state = HTTPConnectionState.NEW + self._state_lock = AsyncLock() + self._request_count = 0 + self._h11_state = h11.Connection( + our_role=h11.CLIENT, + max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, + ) + + async def handle_async_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection " + f"to {self._origin}" + ) + + async with self._state_lock: + if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): + self._request_count += 1 + self._state = HTTPConnectionState.ACTIVE + self._expire_at = None + else: + raise ConnectionNotAvailable() + + try: + kwargs = {"request": request} + try: + async with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + await self._send_request_headers(**kwargs) + async with Trace("send_request_body", logger, request, kwargs) as trace: + await self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + + async with Trace( + "receive_response_headers", logger, request, kwargs + ) as trace: + ( + http_version, + status, + reason_phrase, + headers, + trailing_data, + ) = await self._receive_response_headers(**kwargs) + trace.return_value = ( + http_version, + status, + reason_phrase, + headers, + ) + + network_stream = self._network_stream + + # CONNECT or Upgrade request + if (status == 101) or ( + (request.method == b"CONNECT") and (200 <= status < 300) + ): + network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data) + + return Response( + status=status, + headers=headers, + content=HTTP11ConnectionByteStream(self, request), + extensions={ + "http_version": http_version, + "reason_phrase": reason_phrase, + "network_stream": network_stream, + }, + ) + except BaseException as exc: + with AsyncShieldCancellation(): + async with Trace("response_closed", logger, request) as trace: + await self._response_closed() + raise exc + + # Sending the request... + + async def _send_request_headers(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): + event = h11.Request( + method=request.method, + target=request.url.target, + headers=request.headers, + ) + await self._send_event(event, timeout=timeout) + + async def _send_request_body(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + assert isinstance(request.stream, typing.AsyncIterable) + async for chunk in request.stream: + event = h11.Data(data=chunk) + await self._send_event(event, timeout=timeout) + + await self._send_event(h11.EndOfMessage(), timeout=timeout) + + async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: + bytes_to_send = self._h11_state.send(event) + if bytes_to_send is not None: + await self._network_stream.write(bytes_to_send, timeout=timeout) + + # Receiving the response... + + async def _receive_response_headers( + self, request: Request + ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + while True: + event = await self._receive_event(timeout=timeout) + if isinstance(event, h11.Response): + break + if ( + isinstance(event, h11.InformationalResponse) + and event.status_code == 101 + ): + break + + http_version = b"HTTP/" + event.http_version + + # h11 version 0.11+ supports a `raw_items` interface to get the + # raw header casing, rather than the enforced lowercase headers. + headers = event.headers.raw_items() + + trailing_data, _ = self._h11_state.trailing_data + + return http_version, event.status_code, event.reason, headers, trailing_data + + async def _receive_response_body( + self, request: Request + ) -> typing.AsyncIterator[bytes]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + while True: + event = await self._receive_event(timeout=timeout) + if isinstance(event, h11.Data): + yield bytes(event.data) + elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): + break + + async def _receive_event( + self, timeout: float | None = None + ) -> h11.Event | type[h11.PAUSED]: + while True: + with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): + event = self._h11_state.next_event() + + if event is h11.NEED_DATA: + data = await self._network_stream.read( + self.READ_NUM_BYTES, timeout=timeout + ) + + # If we feed this case through h11 we'll raise an exception like: + # + # httpcore.RemoteProtocolError: can't handle event type + # ConnectionClosed when role=SERVER and state=SEND_RESPONSE + # + # Which is accurate, but not very informative from an end-user + # perspective. Instead we handle this case distinctly and treat + # it as a ConnectError. + if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: + msg = "Server disconnected without sending a response." + raise RemoteProtocolError(msg) + + self._h11_state.receive_data(data) + else: + # mypy fails to narrow the type in the above if statement above + return event # type: ignore[return-value] + + async def _response_closed(self) -> None: + async with self._state_lock: + if ( + self._h11_state.our_state is h11.DONE + and self._h11_state.their_state is h11.DONE + ): + self._state = HTTPConnectionState.IDLE + self._h11_state.start_next_cycle() + if self._keepalive_expiry is not None: + now = time.monotonic() + self._expire_at = now + self._keepalive_expiry + else: + await self.aclose() + + # Once the connection is no longer required... + + async def aclose(self) -> None: + # Note that this method unilaterally closes the connection, and does + # not have any kind of locking in place around it. + self._state = HTTPConnectionState.CLOSED + await self._network_stream.aclose() + + # The AsyncConnectionInterface methods provide information about the state of + # the connection, allowing for a connection pooling implementation to + # determine when to reuse and when to close the connection... + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + def is_available(self) -> bool: + # Note that HTTP/1.1 connections in the "NEW" state are not treated as + # being "available". The control flow which created the connection will + # be able to send an outgoing request, but the connection will not be + # acquired from the connection pool for any other request. + return self._state == HTTPConnectionState.IDLE + + def has_expired(self) -> bool: + now = time.monotonic() + keepalive_expired = self._expire_at is not None and now > self._expire_at + + # If the HTTP connection is idle but the socket is readable, then the + # only valid state is that the socket is about to return b"", indicating + # a server-initiated disconnect. + server_disconnected = ( + self._state == HTTPConnectionState.IDLE + and self._network_stream.get_extra_info("is_readable") + ) + + return keepalive_expired or server_disconnected + + def is_idle(self) -> bool: + return self._state == HTTPConnectionState.IDLE + + def is_closed(self) -> bool: + return self._state == HTTPConnectionState.CLOSED + + def info(self) -> str: + origin = str(self._origin) + return ( + f"{origin!r}, HTTP/1.1, {self._state.name}, " + f"Request Count: {self._request_count}" + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + origin = str(self._origin) + return ( + f"<{class_name} [{origin!r}, {self._state.name}, " + f"Request Count: {self._request_count}]>" + ) + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + async def __aenter__(self) -> AsyncHTTP11Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + await self.aclose() + + +class HTTP11ConnectionByteStream: + def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None: + self._connection = connection + self._request = request + self._closed = False + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + kwargs = {"request": self._request} + try: + async with Trace("receive_response_body", logger, self._request, kwargs): + async for chunk in self._connection._receive_response_body(**kwargs): + yield chunk + except BaseException as exc: + # If we get an exception while streaming the response, + # we want to close the response (and possibly the connection) + # before raising that exception. + with AsyncShieldCancellation(): + await self.aclose() + raise exc + + async def aclose(self) -> None: + if not self._closed: + self._closed = True + async with Trace("response_closed", logger, self._request): + await self._connection._response_closed() + + +class AsyncHTTP11UpgradeStream(AsyncNetworkStream): + def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None: + self._stream = stream + self._leading_data = leading_data + + async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + if self._leading_data: + buffer = self._leading_data[:max_bytes] + self._leading_data = self._leading_data[max_bytes:] + return buffer + else: + return await self._stream.read(max_bytes, timeout) + + async def write(self, buffer: bytes, timeout: float | None = None) -> None: + await self._stream.write(buffer, timeout) + + async def aclose(self) -> None: + await self._stream.aclose() + + async def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> AsyncNetworkStream: + return await self._stream.start_tls(ssl_context, server_hostname, timeout) + + def get_extra_info(self, info: str) -> typing.Any: + return self._stream.get_extra_info(info) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http2.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http2.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd0beeb4da32d8c0175d412fa442eae8f837723 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http2.py @@ -0,0 +1,592 @@ +from __future__ import annotations + +import enum +import logging +import time +import types +import typing + +import h2.config +import h2.connection +import h2.events +import h2.exceptions +import h2.settings + +from .._backends.base import AsyncNetworkStream +from .._exceptions import ( + ConnectionNotAvailable, + LocalProtocolError, + RemoteProtocolError, +) +from .._models import Origin, Request, Response +from .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellation +from .._trace import Trace +from .interfaces import AsyncConnectionInterface + +logger = logging.getLogger("httpcore.http2") + + +def has_body_headers(request: Request) -> bool: + return any( + k.lower() == b"content-length" or k.lower() == b"transfer-encoding" + for k, v in request.headers + ) + + +class HTTPConnectionState(enum.IntEnum): + ACTIVE = 1 + IDLE = 2 + CLOSED = 3 + + +class AsyncHTTP2Connection(AsyncConnectionInterface): + READ_NUM_BYTES = 64 * 1024 + CONFIG = h2.config.H2Configuration(validate_inbound_headers=False) + + def __init__( + self, + origin: Origin, + stream: AsyncNetworkStream, + keepalive_expiry: float | None = None, + ): + self._origin = origin + self._network_stream = stream + self._keepalive_expiry: float | None = keepalive_expiry + self._h2_state = h2.connection.H2Connection(config=self.CONFIG) + self._state = HTTPConnectionState.IDLE + self._expire_at: float | None = None + self._request_count = 0 + self._init_lock = AsyncLock() + self._state_lock = AsyncLock() + self._read_lock = AsyncLock() + self._write_lock = AsyncLock() + self._sent_connection_init = False + self._used_all_stream_ids = False + self._connection_error = False + + # Mapping from stream ID to response stream events. + self._events: dict[ + int, + list[ + h2.events.ResponseReceived + | h2.events.DataReceived + | h2.events.StreamEnded + | h2.events.StreamReset, + ], + ] = {} + + # Connection terminated events are stored as state since + # we need to handle them for all streams. + self._connection_terminated: h2.events.ConnectionTerminated | None = None + + self._read_exception: Exception | None = None + self._write_exception: Exception | None = None + + async def handle_async_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + # This cannot occur in normal operation, since the connection pool + # will only send requests on connections that handle them. + # It's in place simply for resilience as a guard against incorrect + # usage, for anyone working directly with httpcore connections. + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection " + f"to {self._origin}" + ) + + async with self._state_lock: + if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): + self._request_count += 1 + self._expire_at = None + self._state = HTTPConnectionState.ACTIVE + else: + raise ConnectionNotAvailable() + + async with self._init_lock: + if not self._sent_connection_init: + try: + sci_kwargs = {"request": request} + async with Trace( + "send_connection_init", logger, request, sci_kwargs + ): + await self._send_connection_init(**sci_kwargs) + except BaseException as exc: + with AsyncShieldCancellation(): + await self.aclose() + raise exc + + self._sent_connection_init = True + + # Initially start with just 1 until the remote server provides + # its max_concurrent_streams value + self._max_streams = 1 + + local_settings_max_streams = ( + self._h2_state.local_settings.max_concurrent_streams + ) + self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams) + + for _ in range(local_settings_max_streams - self._max_streams): + await self._max_streams_semaphore.acquire() + + await self._max_streams_semaphore.acquire() + + try: + stream_id = self._h2_state.get_next_available_stream_id() + self._events[stream_id] = [] + except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover + self._used_all_stream_ids = True + self._request_count -= 1 + raise ConnectionNotAvailable() + + try: + kwargs = {"request": request, "stream_id": stream_id} + async with Trace("send_request_headers", logger, request, kwargs): + await self._send_request_headers(request=request, stream_id=stream_id) + async with Trace("send_request_body", logger, request, kwargs): + await self._send_request_body(request=request, stream_id=stream_id) + async with Trace( + "receive_response_headers", logger, request, kwargs + ) as trace: + status, headers = await self._receive_response( + request=request, stream_id=stream_id + ) + trace.return_value = (status, headers) + + return Response( + status=status, + headers=headers, + content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), + extensions={ + "http_version": b"HTTP/2", + "network_stream": self._network_stream, + "stream_id": stream_id, + }, + ) + except BaseException as exc: # noqa: PIE786 + with AsyncShieldCancellation(): + kwargs = {"stream_id": stream_id} + async with Trace("response_closed", logger, request, kwargs): + await self._response_closed(stream_id=stream_id) + + if isinstance(exc, h2.exceptions.ProtocolError): + # One case where h2 can raise a protocol error is when a + # closed frame has been seen by the state machine. + # + # This happens when one stream is reading, and encounters + # a GOAWAY event. Other flows of control may then raise + # a protocol error at any point they interact with the 'h2_state'. + # + # In this case we'll have stored the event, and should raise + # it as a RemoteProtocolError. + if self._connection_terminated: # pragma: nocover + raise RemoteProtocolError(self._connection_terminated) + # If h2 raises a protocol error in some other state then we + # must somehow have made a protocol violation. + raise LocalProtocolError(exc) # pragma: nocover + + raise exc + + async def _send_connection_init(self, request: Request) -> None: + """ + The HTTP/2 connection requires some initial setup before we can start + using individual request/response streams on it. + """ + # Need to set these manually here instead of manipulating via + # __setitem__() otherwise the H2Connection will emit SettingsUpdate + # frames in addition to sending the undesired defaults. + self._h2_state.local_settings = h2.settings.Settings( + client=True, + initial_values={ + # Disable PUSH_PROMISE frames from the server since we don't do anything + # with them for now. Maybe when we support caching? + h2.settings.SettingCodes.ENABLE_PUSH: 0, + # These two are taken from h2 for safe defaults + h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, + h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, + }, + ) + + # Some websites (*cough* Yahoo *cough*) balk at this setting being + # present in the initial handshake since it's not defined in the original + # RFC despite the RFC mandating ignoring settings you don't know about. + del self._h2_state.local_settings[ + h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL + ] + + self._h2_state.initiate_connection() + self._h2_state.increment_flow_control_window(2**24) + await self._write_outgoing_data(request) + + # Sending the request... + + async def _send_request_headers(self, request: Request, stream_id: int) -> None: + """ + Send the request headers to a given stream ID. + """ + end_stream = not has_body_headers(request) + + # In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. + # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require + # HTTP/1.1 style headers, and map them appropriately if we end up on + # an HTTP/2 connection. + authority = [v for k, v in request.headers if k.lower() == b"host"][0] + + headers = [ + (b":method", request.method), + (b":authority", authority), + (b":scheme", request.url.scheme), + (b":path", request.url.target), + ] + [ + (k.lower(), v) + for k, v in request.headers + if k.lower() + not in ( + b"host", + b"transfer-encoding", + ) + ] + + self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) + self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) + await self._write_outgoing_data(request) + + async def _send_request_body(self, request: Request, stream_id: int) -> None: + """ + Iterate over the request body sending it to a given stream ID. + """ + if not has_body_headers(request): + return + + assert isinstance(request.stream, typing.AsyncIterable) + async for data in request.stream: + await self._send_stream_data(request, stream_id, data) + await self._send_end_stream(request, stream_id) + + async def _send_stream_data( + self, request: Request, stream_id: int, data: bytes + ) -> None: + """ + Send a single chunk of data in one or more data frames. + """ + while data: + max_flow = await self._wait_for_outgoing_flow(request, stream_id) + chunk_size = min(len(data), max_flow) + chunk, data = data[:chunk_size], data[chunk_size:] + self._h2_state.send_data(stream_id, chunk) + await self._write_outgoing_data(request) + + async def _send_end_stream(self, request: Request, stream_id: int) -> None: + """ + Send an empty data frame on on a given stream ID with the END_STREAM flag set. + """ + self._h2_state.end_stream(stream_id) + await self._write_outgoing_data(request) + + # Receiving the response... + + async def _receive_response( + self, request: Request, stream_id: int + ) -> tuple[int, list[tuple[bytes, bytes]]]: + """ + Return the response status code and headers for a given stream ID. + """ + while True: + event = await self._receive_stream_event(request, stream_id) + if isinstance(event, h2.events.ResponseReceived): + break + + status_code = 200 + headers = [] + assert event.headers is not None + for k, v in event.headers: + if k == b":status": + status_code = int(v.decode("ascii", errors="ignore")) + elif not k.startswith(b":"): + headers.append((k, v)) + + return (status_code, headers) + + async def _receive_response_body( + self, request: Request, stream_id: int + ) -> typing.AsyncIterator[bytes]: + """ + Iterator that returns the bytes of the response body for a given stream ID. + """ + while True: + event = await self._receive_stream_event(request, stream_id) + if isinstance(event, h2.events.DataReceived): + assert event.flow_controlled_length is not None + assert event.data is not None + amount = event.flow_controlled_length + self._h2_state.acknowledge_received_data(amount, stream_id) + await self._write_outgoing_data(request) + yield event.data + elif isinstance(event, h2.events.StreamEnded): + break + + async def _receive_stream_event( + self, request: Request, stream_id: int + ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: + """ + Return the next available event for a given stream ID. + + Will read more data from the network if required. + """ + while not self._events.get(stream_id): + await self._receive_events(request, stream_id) + event = self._events[stream_id].pop(0) + if isinstance(event, h2.events.StreamReset): + raise RemoteProtocolError(event) + return event + + async def _receive_events( + self, request: Request, stream_id: int | None = None + ) -> None: + """ + Read some data from the network until we see one or more events + for a given stream ID. + """ + async with self._read_lock: + if self._connection_terminated is not None: + last_stream_id = self._connection_terminated.last_stream_id + if stream_id and last_stream_id and stream_id > last_stream_id: + self._request_count -= 1 + raise ConnectionNotAvailable() + raise RemoteProtocolError(self._connection_terminated) + + # This conditional is a bit icky. We don't want to block reading if we've + # actually got an event to return for a given stream. We need to do that + # check *within* the atomic read lock. Though it also need to be optional, + # because when we call it from `_wait_for_outgoing_flow` we *do* want to + # block until we've available flow control, event when we have events + # pending for the stream ID we're attempting to send on. + if stream_id is None or not self._events.get(stream_id): + events = await self._read_incoming_data(request) + for event in events: + if isinstance(event, h2.events.RemoteSettingsChanged): + async with Trace( + "receive_remote_settings", logger, request + ) as trace: + await self._receive_remote_settings_change(event) + trace.return_value = event + + elif isinstance( + event, + ( + h2.events.ResponseReceived, + h2.events.DataReceived, + h2.events.StreamEnded, + h2.events.StreamReset, + ), + ): + if event.stream_id in self._events: + self._events[event.stream_id].append(event) + + elif isinstance(event, h2.events.ConnectionTerminated): + self._connection_terminated = event + + await self._write_outgoing_data(request) + + async def _receive_remote_settings_change( + self, event: h2.events.RemoteSettingsChanged + ) -> None: + max_concurrent_streams = event.changed_settings.get( + h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS + ) + if max_concurrent_streams: + new_max_streams = min( + max_concurrent_streams.new_value, + self._h2_state.local_settings.max_concurrent_streams, + ) + if new_max_streams and new_max_streams != self._max_streams: + while new_max_streams > self._max_streams: + await self._max_streams_semaphore.release() + self._max_streams += 1 + while new_max_streams < self._max_streams: + await self._max_streams_semaphore.acquire() + self._max_streams -= 1 + + async def _response_closed(self, stream_id: int) -> None: + await self._max_streams_semaphore.release() + del self._events[stream_id] + async with self._state_lock: + if self._connection_terminated and not self._events: + await self.aclose() + + elif self._state == HTTPConnectionState.ACTIVE and not self._events: + self._state = HTTPConnectionState.IDLE + if self._keepalive_expiry is not None: + now = time.monotonic() + self._expire_at = now + self._keepalive_expiry + if self._used_all_stream_ids: # pragma: nocover + await self.aclose() + + async def aclose(self) -> None: + # Note that this method unilaterally closes the connection, and does + # not have any kind of locking in place around it. + self._h2_state.close_connection() + self._state = HTTPConnectionState.CLOSED + await self._network_stream.aclose() + + # Wrappers around network read/write operations... + + async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + if self._read_exception is not None: + raise self._read_exception # pragma: nocover + + try: + data = await self._network_stream.read(self.READ_NUM_BYTES, timeout) + if data == b"": + raise RemoteProtocolError("Server disconnected") + except Exception as exc: + # If we get a network error we should: + # + # 1. Save the exception and just raise it immediately on any future reads. + # (For example, this means that a single read timeout or disconnect will + # immediately close all pending streams. Without requiring multiple + # sequential timeouts.) + # 2. Mark the connection as errored, so that we don't accept any other + # incoming requests. + self._read_exception = exc + self._connection_error = True + raise exc + + events: list[h2.events.Event] = self._h2_state.receive_data(data) + + return events + + async def _write_outgoing_data(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + async with self._write_lock: + data_to_send = self._h2_state.data_to_send() + + if self._write_exception is not None: + raise self._write_exception # pragma: nocover + + try: + await self._network_stream.write(data_to_send, timeout) + except Exception as exc: # pragma: nocover + # If we get a network error we should: + # + # 1. Save the exception and just raise it immediately on any future write. + # (For example, this means that a single write timeout or disconnect will + # immediately close all pending streams. Without requiring multiple + # sequential timeouts.) + # 2. Mark the connection as errored, so that we don't accept any other + # incoming requests. + self._write_exception = exc + self._connection_error = True + raise exc + + # Flow control... + + async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: + """ + Returns the maximum allowable outgoing flow for a given stream. + + If the allowable flow is zero, then waits on the network until + WindowUpdated frames have increased the flow rate. + https://tools.ietf.org/html/rfc7540#section-6.9 + """ + local_flow: int = self._h2_state.local_flow_control_window(stream_id) + max_frame_size: int = self._h2_state.max_outbound_frame_size + flow = min(local_flow, max_frame_size) + while flow == 0: + await self._receive_events(request) + local_flow = self._h2_state.local_flow_control_window(stream_id) + max_frame_size = self._h2_state.max_outbound_frame_size + flow = min(local_flow, max_frame_size) + return flow + + # Interface for connection pooling... + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + def is_available(self) -> bool: + return ( + self._state != HTTPConnectionState.CLOSED + and not self._connection_error + and not self._used_all_stream_ids + and not ( + self._h2_state.state_machine.state + == h2.connection.ConnectionState.CLOSED + ) + ) + + def has_expired(self) -> bool: + now = time.monotonic() + return self._expire_at is not None and now > self._expire_at + + def is_idle(self) -> bool: + return self._state == HTTPConnectionState.IDLE + + def is_closed(self) -> bool: + return self._state == HTTPConnectionState.CLOSED + + def info(self) -> str: + origin = str(self._origin) + return ( + f"{origin!r}, HTTP/2, {self._state.name}, " + f"Request Count: {self._request_count}" + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + origin = str(self._origin) + return ( + f"<{class_name} [{origin!r}, {self._state.name}, " + f"Request Count: {self._request_count}]>" + ) + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + async def __aenter__(self) -> AsyncHTTP2Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + await self.aclose() + + +class HTTP2ConnectionByteStream: + def __init__( + self, connection: AsyncHTTP2Connection, request: Request, stream_id: int + ) -> None: + self._connection = connection + self._request = request + self._stream_id = stream_id + self._closed = False + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + kwargs = {"request": self._request, "stream_id": self._stream_id} + try: + async with Trace("receive_response_body", logger, self._request, kwargs): + async for chunk in self._connection._receive_response_body( + request=self._request, stream_id=self._stream_id + ): + yield chunk + except BaseException as exc: + # If we get an exception while streaming the response, + # we want to close the response (and possibly the connection) + # before raising that exception. + with AsyncShieldCancellation(): + await self.aclose() + raise exc + + async def aclose(self) -> None: + if not self._closed: + self._closed = True + kwargs = {"stream_id": self._stream_id} + async with Trace("response_closed", logger, self._request, kwargs): + await self._connection._response_closed(stream_id=self._stream_id) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http_proxy.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9d92066e1680576846e46ccdf645a2b1dd5718 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/http_proxy.py @@ -0,0 +1,367 @@ +from __future__ import annotations + +import base64 +import logging +import ssl +import typing + +from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend +from .._exceptions import ProxyError +from .._models import ( + URL, + Origin, + Request, + Response, + enforce_bytes, + enforce_headers, + enforce_url, +) +from .._ssl import default_ssl_context +from .._synchronization import AsyncLock +from .._trace import Trace +from .connection import AsyncHTTPConnection +from .connection_pool import AsyncConnectionPool +from .http11 import AsyncHTTP11Connection +from .interfaces import AsyncConnectionInterface + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] + + +logger = logging.getLogger("httpcore.proxy") + + +def merge_headers( + default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, +) -> list[tuple[bytes, bytes]]: + """ + Append default_headers and override_headers, de-duplicating if a key exists + in both cases. + """ + default_headers = [] if default_headers is None else list(default_headers) + override_headers = [] if override_headers is None else list(override_headers) + has_override = set(key.lower() for key, value in override_headers) + default_headers = [ + (key, value) + for key, value in default_headers + if key.lower() not in has_override + ] + return default_headers + override_headers + + +class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover + """ + A connection pool that sends requests via an HTTP proxy. + """ + + def __init__( + self, + proxy_url: URL | bytes | str, + proxy_auth: tuple[bytes | str, bytes | str] | None = None, + proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: AsyncNetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + proxy_url: The URL to use when connecting to the proxy server. + For example `"http://127.0.0.1:8080/"`. + proxy_auth: Any proxy authentication as a two-tuple of + (username, password). May be either bytes or ascii-only str. + proxy_headers: Any HTTP headers to use for the proxy requests. + For example `{"Proxy-Authorization": "Basic :"}`. + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish + a connection. + local_address: Local address to connect from. Can also be used to + connect using a particular address family. Using + `local_address="0.0.0.0"` will connect using an `AF_INET` address + (IPv4), while using `local_address="::"` will connect using an + `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + """ + super().__init__( + ssl_context=ssl_context, + max_connections=max_connections, + max_keepalive_connections=max_keepalive_connections, + keepalive_expiry=keepalive_expiry, + http1=http1, + http2=http2, + network_backend=network_backend, + retries=retries, + local_address=local_address, + uds=uds, + socket_options=socket_options, + ) + + self._proxy_url = enforce_url(proxy_url, name="proxy_url") + if ( + self._proxy_url.scheme == b"http" and proxy_ssl_context is not None + ): # pragma: no cover + raise RuntimeError( + "The `proxy_ssl_context` argument is not allowed for the http scheme" + ) + + self._ssl_context = ssl_context + self._proxy_ssl_context = proxy_ssl_context + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + if proxy_auth is not None: + username = enforce_bytes(proxy_auth[0], name="proxy_auth") + password = enforce_bytes(proxy_auth[1], name="proxy_auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self._proxy_headers = [ + (b"Proxy-Authorization", authorization) + ] + self._proxy_headers + + def create_connection(self, origin: Origin) -> AsyncConnectionInterface: + if origin.scheme == b"http": + return AsyncForwardHTTPConnection( + proxy_origin=self._proxy_url.origin, + proxy_headers=self._proxy_headers, + remote_origin=origin, + keepalive_expiry=self._keepalive_expiry, + network_backend=self._network_backend, + proxy_ssl_context=self._proxy_ssl_context, + ) + return AsyncTunnelHTTPConnection( + proxy_origin=self._proxy_url.origin, + proxy_headers=self._proxy_headers, + remote_origin=origin, + ssl_context=self._ssl_context, + proxy_ssl_context=self._proxy_ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + +class AsyncForwardHTTPConnection(AsyncConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, + keepalive_expiry: float | None = None, + network_backend: AsyncNetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + ) -> None: + self._connection = AsyncHTTPConnection( + origin=proxy_origin, + keepalive_expiry=keepalive_expiry, + network_backend=network_backend, + socket_options=socket_options, + ssl_context=proxy_ssl_context, + ) + self._proxy_origin = proxy_origin + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + self._remote_origin = remote_origin + + async def handle_async_request(self, request: Request) -> Response: + headers = merge_headers(self._proxy_headers, request.headers) + url = URL( + scheme=self._proxy_origin.scheme, + host=self._proxy_origin.host, + port=self._proxy_origin.port, + target=bytes(request.url), + ) + proxy_request = Request( + method=request.method, + url=url, + headers=headers, + content=request.stream, + extensions=request.extensions, + ) + return await self._connection.handle_async_request(proxy_request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + async def aclose(self) -> None: + await self._connection.aclose() + + def info(self) -> str: + return self._connection.info() + + def is_available(self) -> bool: + return self._connection.is_available() + + def has_expired(self) -> bool: + return self._connection.has_expired() + + def is_idle(self) -> bool: + return self._connection.is_idle() + + def is_closed(self) -> bool: + return self._connection.is_closed() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" + + +class AsyncTunnelHTTPConnection(AsyncConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + ssl_context: ssl.SSLContext | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + network_backend: AsyncNetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + self._connection: AsyncConnectionInterface = AsyncHTTPConnection( + origin=proxy_origin, + keepalive_expiry=keepalive_expiry, + network_backend=network_backend, + socket_options=socket_options, + ssl_context=proxy_ssl_context, + ) + self._proxy_origin = proxy_origin + self._remote_origin = remote_origin + self._ssl_context = ssl_context + self._proxy_ssl_context = proxy_ssl_context + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._connect_lock = AsyncLock() + self._connected = False + + async def handle_async_request(self, request: Request) -> Response: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("connect", None) + + async with self._connect_lock: + if not self._connected: + target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port) + + connect_url = URL( + scheme=self._proxy_origin.scheme, + host=self._proxy_origin.host, + port=self._proxy_origin.port, + target=target, + ) + connect_headers = merge_headers( + [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers + ) + connect_request = Request( + method=b"CONNECT", + url=connect_url, + headers=connect_headers, + extensions=request.extensions, + ) + connect_response = await self._connection.handle_async_request( + connect_request + ) + + if connect_response.status < 200 or connect_response.status > 299: + reason_bytes = connect_response.extensions.get("reason_phrase", b"") + reason_str = reason_bytes.decode("ascii", errors="ignore") + msg = "%d %s" % (connect_response.status, reason_str) + await self._connection.aclose() + raise ProxyError(msg) + + stream = connect_response.extensions["network_stream"] + + # Upgrade the stream to SSL + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": self._remote_origin.host.decode("ascii"), + "timeout": timeout, + } + async with Trace("start_tls", logger, request, kwargs) as trace: + stream = await stream.start_tls(**kwargs) + trace.return_value = stream + + # Determine if we should be using HTTP/1.1 or HTTP/2 + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + + # Create the HTTP/1.1 or HTTP/2 connection + if http2_negotiated or (self._http2 and not self._http1): + from .http2 import AsyncHTTP2Connection + + self._connection = AsyncHTTP2Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = AsyncHTTP11Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + + self._connected = True + return await self._connection.handle_async_request(request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + async def aclose(self) -> None: + await self._connection.aclose() + + def info(self) -> str: + return self._connection.info() + + def is_available(self) -> bool: + return self._connection.is_available() + + def has_expired(self) -> bool: + return self._connection.has_expired() + + def is_idle(self) -> bool: + return self._connection.is_idle() + + def is_closed(self) -> bool: + return self._connection.is_closed() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/interfaces.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..361583bede6b2b84088b38054d5d8116ef9f1597 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/interfaces.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import contextlib +import typing + +from .._models import ( + URL, + Extensions, + HeaderTypes, + Origin, + Request, + Response, + enforce_bytes, + enforce_headers, + enforce_url, + include_request_headers, +) + + +class AsyncRequestInterface: + async def request( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.AsyncIterator[bytes] | None = None, + extensions: Extensions | None = None, + ) -> Response: + # Strict type checking on our parameters. + method = enforce_bytes(method, name="method") + url = enforce_url(url, name="url") + headers = enforce_headers(headers, name="headers") + + # Include Host header, and optionally Content-Length or Transfer-Encoding. + headers = include_request_headers(headers, url=url, content=content) + + request = Request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + response = await self.handle_async_request(request) + try: + await response.aread() + finally: + await response.aclose() + return response + + @contextlib.asynccontextmanager + async def stream( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.AsyncIterator[bytes] | None = None, + extensions: Extensions | None = None, + ) -> typing.AsyncIterator[Response]: + # Strict type checking on our parameters. + method = enforce_bytes(method, name="method") + url = enforce_url(url, name="url") + headers = enforce_headers(headers, name="headers") + + # Include Host header, and optionally Content-Length or Transfer-Encoding. + headers = include_request_headers(headers, url=url, content=content) + + request = Request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + response = await self.handle_async_request(request) + try: + yield response + finally: + await response.aclose() + + async def handle_async_request(self, request: Request) -> Response: + raise NotImplementedError() # pragma: nocover + + +class AsyncConnectionInterface(AsyncRequestInterface): + async def aclose(self) -> None: + raise NotImplementedError() # pragma: nocover + + def info(self) -> str: + raise NotImplementedError() # pragma: nocover + + def can_handle_request(self, origin: Origin) -> bool: + raise NotImplementedError() # pragma: nocover + + def is_available(self) -> bool: + """ + Return `True` if the connection is currently able to accept an + outgoing request. + + An HTTP/1.1 connection will only be available if it is currently idle. + + An HTTP/2 connection will be available so long as the stream ID space is + not yet exhausted, and the connection is not in an error state. + + While the connection is being established we may not yet know if it is going + to result in an HTTP/1.1 or HTTP/2 connection. The connection should be + treated as being available, but might ultimately raise `NewConnectionRequired` + required exceptions if multiple requests are attempted over a connection + that ends up being established as HTTP/1.1. + """ + raise NotImplementedError() # pragma: nocover + + def has_expired(self) -> bool: + """ + Return `True` if the connection is in a state where it should be closed. + + This either means that the connection is idle and it has passed the + expiry time on its keep-alive, or that server has sent an EOF. + """ + raise NotImplementedError() # pragma: nocover + + def is_idle(self) -> bool: + """ + Return `True` if the connection is currently idle. + """ + raise NotImplementedError() # pragma: nocover + + def is_closed(self) -> bool: + """ + Return `True` if the connection has been closed. + + Used when a response is closed to determine if the connection may be + returned to the connection pool or not. + """ + raise NotImplementedError() # pragma: nocover diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/socks_proxy.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/socks_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..b363f55a0b071de6c5f377726be82dc2110e373c --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_async/socks_proxy.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +import logging +import ssl + +import socksio + +from .._backends.auto import AutoBackend +from .._backends.base import AsyncNetworkBackend, AsyncNetworkStream +from .._exceptions import ConnectionNotAvailable, ProxyError +from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url +from .._ssl import default_ssl_context +from .._synchronization import AsyncLock +from .._trace import Trace +from .connection_pool import AsyncConnectionPool +from .http11 import AsyncHTTP11Connection +from .interfaces import AsyncConnectionInterface + +logger = logging.getLogger("httpcore.socks") + + +AUTH_METHODS = { + b"\x00": "NO AUTHENTICATION REQUIRED", + b"\x01": "GSSAPI", + b"\x02": "USERNAME/PASSWORD", + b"\xff": "NO ACCEPTABLE METHODS", +} + +REPLY_CODES = { + b"\x00": "Succeeded", + b"\x01": "General SOCKS server failure", + b"\x02": "Connection not allowed by ruleset", + b"\x03": "Network unreachable", + b"\x04": "Host unreachable", + b"\x05": "Connection refused", + b"\x06": "TTL expired", + b"\x07": "Command not supported", + b"\x08": "Address type not supported", +} + + +async def _init_socks5_connection( + stream: AsyncNetworkStream, + *, + host: bytes, + port: int, + auth: tuple[bytes, bytes] | None = None, +) -> None: + conn = socksio.socks5.SOCKS5Connection() + + # Auth method request + auth_method = ( + socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED + if auth is None + else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD + ) + conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) + outgoing_bytes = conn.data_to_send() + await stream.write(outgoing_bytes) + + # Auth method response + incoming_bytes = await stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5AuthReply) + if response.method != auth_method: + requested = AUTH_METHODS.get(auth_method, "UNKNOWN") + responded = AUTH_METHODS.get(response.method, "UNKNOWN") + raise ProxyError( + f"Requested {requested} from proxy server, but got {responded}." + ) + + if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: + # Username/password request + assert auth is not None + username, password = auth + conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) + outgoing_bytes = conn.data_to_send() + await stream.write(outgoing_bytes) + + # Username/password response + incoming_bytes = await stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) + if not response.success: + raise ProxyError("Invalid username/password") + + # Connect request + conn.send( + socksio.socks5.SOCKS5CommandRequest.from_address( + socksio.socks5.SOCKS5Command.CONNECT, (host, port) + ) + ) + outgoing_bytes = conn.data_to_send() + await stream.write(outgoing_bytes) + + # Connect response + incoming_bytes = await stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5Reply) + if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: + reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") + raise ProxyError(f"Proxy Server could not connect: {reply_code}.") + + +class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover + """ + A connection pool that sends requests via an HTTP proxy. + """ + + def __init__( + self, + proxy_url: URL | bytes | str, + proxy_auth: tuple[bytes | str, bytes | str] | None = None, + ssl_context: ssl.SSLContext | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + network_backend: AsyncNetworkBackend | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + proxy_url: The URL to use when connecting to the proxy server. + For example `"http://127.0.0.1:8080/"`. + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish + a connection. + local_address: Local address to connect from. Can also be used to + connect using a particular address family. Using + `local_address="0.0.0.0"` will connect using an `AF_INET` address + (IPv4), while using `local_address="::"` will connect using an + `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + """ + super().__init__( + ssl_context=ssl_context, + max_connections=max_connections, + max_keepalive_connections=max_keepalive_connections, + keepalive_expiry=keepalive_expiry, + http1=http1, + http2=http2, + network_backend=network_backend, + retries=retries, + ) + self._ssl_context = ssl_context + self._proxy_url = enforce_url(proxy_url, name="proxy_url") + if proxy_auth is not None: + username, password = proxy_auth + username_bytes = enforce_bytes(username, name="proxy_auth") + password_bytes = enforce_bytes(password, name="proxy_auth") + self._proxy_auth: tuple[bytes, bytes] | None = ( + username_bytes, + password_bytes, + ) + else: + self._proxy_auth = None + + def create_connection(self, origin: Origin) -> AsyncConnectionInterface: + return AsyncSocks5Connection( + proxy_origin=self._proxy_url.origin, + remote_origin=origin, + proxy_auth=self._proxy_auth, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + +class AsyncSocks5Connection(AsyncConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + proxy_auth: tuple[bytes, bytes] | None = None, + ssl_context: ssl.SSLContext | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + network_backend: AsyncNetworkBackend | None = None, + ) -> None: + self._proxy_origin = proxy_origin + self._remote_origin = remote_origin + self._proxy_auth = proxy_auth + self._ssl_context = ssl_context + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + + self._network_backend: AsyncNetworkBackend = ( + AutoBackend() if network_backend is None else network_backend + ) + self._connect_lock = AsyncLock() + self._connection: AsyncConnectionInterface | None = None + self._connect_failed = False + + async def handle_async_request(self, request: Request) -> Response: + timeouts = request.extensions.get("timeout", {}) + sni_hostname = request.extensions.get("sni_hostname", None) + timeout = timeouts.get("connect", None) + + async with self._connect_lock: + if self._connection is None: + try: + # Connect to the proxy + kwargs = { + "host": self._proxy_origin.host.decode("ascii"), + "port": self._proxy_origin.port, + "timeout": timeout, + } + async with Trace("connect_tcp", logger, request, kwargs) as trace: + stream = await self._network_backend.connect_tcp(**kwargs) + trace.return_value = stream + + # Connect to the remote host using socks5 + kwargs = { + "stream": stream, + "host": self._remote_origin.host.decode("ascii"), + "port": self._remote_origin.port, + "auth": self._proxy_auth, + } + async with Trace( + "setup_socks5_connection", logger, request, kwargs + ) as trace: + await _init_socks5_connection(**kwargs) + trace.return_value = stream + + # Upgrade the stream to SSL + if self._remote_origin.scheme == b"https": + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ( + ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ) + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": sni_hostname + or self._remote_origin.host.decode("ascii"), + "timeout": timeout, + } + async with Trace("start_tls", logger, request, kwargs) as trace: + stream = await stream.start_tls(**kwargs) + trace.return_value = stream + + # Determine if we should be using HTTP/1.1 or HTTP/2 + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + + # Create the HTTP/1.1 or HTTP/2 connection + if http2_negotiated or ( + self._http2 and not self._http1 + ): # pragma: nocover + from .http2 import AsyncHTTP2Connection + + self._connection = AsyncHTTP2Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = AsyncHTTP11Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + except Exception as exc: + self._connect_failed = True + raise exc + elif not self._connection.is_available(): # pragma: nocover + raise ConnectionNotAvailable() + + return await self._connection.handle_async_request(request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + async def aclose(self) -> None: + if self._connection is not None: + await self._connection.aclose() + + def is_available(self) -> bool: + if self._connection is None: # pragma: nocover + # If HTTP/2 support is enabled, and the resulting connection could + # end up as HTTP/2 then we should indicate the connection as being + # available to service multiple requests. + return ( + self._http2 + and (self._remote_origin.scheme == b"https" or not self._http1) + and not self._connect_failed + ) + return self._connection.is_available() + + def has_expired(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.has_expired() + + def is_idle(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.is_idle() + + def is_closed(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.is_closed() + + def info(self) -> str: + if self._connection is None: # pragma: nocover + return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" + return self._connection.info() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/__init__.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/anyio.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/anyio.py new file mode 100644 index 0000000000000000000000000000000000000000..a140095e1b8de022f321a41c0125e0e5febc0749 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/anyio.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import ssl +import typing + +import anyio + +from .._exceptions import ( + ConnectError, + ConnectTimeout, + ReadError, + ReadTimeout, + WriteError, + WriteTimeout, + map_exceptions, +) +from .._utils import is_socket_readable +from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream + + +class AnyIOStream(AsyncNetworkStream): + def __init__(self, stream: anyio.abc.ByteStream) -> None: + self._stream = stream + + async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + exc_map = { + TimeoutError: ReadTimeout, + anyio.BrokenResourceError: ReadError, + anyio.ClosedResourceError: ReadError, + anyio.EndOfStream: ReadError, + } + with map_exceptions(exc_map): + with anyio.fail_after(timeout): + try: + return await self._stream.receive(max_bytes=max_bytes) + except anyio.EndOfStream: # pragma: nocover + return b"" + + async def write(self, buffer: bytes, timeout: float | None = None) -> None: + if not buffer: + return + + exc_map = { + TimeoutError: WriteTimeout, + anyio.BrokenResourceError: WriteError, + anyio.ClosedResourceError: WriteError, + } + with map_exceptions(exc_map): + with anyio.fail_after(timeout): + await self._stream.send(item=buffer) + + async def aclose(self) -> None: + await self._stream.aclose() + + async def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> AsyncNetworkStream: + exc_map = { + TimeoutError: ConnectTimeout, + anyio.BrokenResourceError: ConnectError, + anyio.EndOfStream: ConnectError, + ssl.SSLError: ConnectError, + } + with map_exceptions(exc_map): + try: + with anyio.fail_after(timeout): + ssl_stream = await anyio.streams.tls.TLSStream.wrap( + self._stream, + ssl_context=ssl_context, + hostname=server_hostname, + standard_compatible=False, + server_side=False, + ) + except Exception as exc: # pragma: nocover + await self.aclose() + raise exc + return AnyIOStream(ssl_stream) + + def get_extra_info(self, info: str) -> typing.Any: + if info == "ssl_object": + return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None) + if info == "client_addr": + return self._stream.extra(anyio.abc.SocketAttribute.local_address, None) + if info == "server_addr": + return self._stream.extra(anyio.abc.SocketAttribute.remote_address, None) + if info == "socket": + return self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) + if info == "is_readable": + sock = self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) + return is_socket_readable(sock) + return None + + +class AnyIOBackend(AsyncNetworkBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: # pragma: nocover + if socket_options is None: + socket_options = [] + exc_map = { + TimeoutError: ConnectTimeout, + OSError: ConnectError, + anyio.BrokenResourceError: ConnectError, + } + with map_exceptions(exc_map): + with anyio.fail_after(timeout): + stream: anyio.abc.ByteStream = await anyio.connect_tcp( + remote_host=host, + remote_port=port, + local_host=local_address, + ) + # By default TCP sockets opened in `asyncio` include TCP_NODELAY. + for option in socket_options: + stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover + return AnyIOStream(stream) + + async def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: # pragma: nocover + if socket_options is None: + socket_options = [] + exc_map = { + TimeoutError: ConnectTimeout, + OSError: ConnectError, + anyio.BrokenResourceError: ConnectError, + } + with map_exceptions(exc_map): + with anyio.fail_after(timeout): + stream: anyio.abc.ByteStream = await anyio.connect_unix(path) + for option in socket_options: + stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover + return AnyIOStream(stream) + + async def sleep(self, seconds: float) -> None: + await anyio.sleep(seconds) # pragma: nocover diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/auto.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..49f0e698c97ad5623f376d8182675352e21c2c3c --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/auto.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import typing + +from .._synchronization import current_async_library +from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream + + +class AutoBackend(AsyncNetworkBackend): + async def _init_backend(self) -> None: + if not (hasattr(self, "_backend")): + backend = current_async_library() + if backend == "trio": + from .trio import TrioBackend + + self._backend: AsyncNetworkBackend = TrioBackend() + else: + from .anyio import AnyIOBackend + + self._backend = AnyIOBackend() + + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + await self._init_backend() + return await self._backend.connect_tcp( + host, + port, + timeout=timeout, + local_address=local_address, + socket_options=socket_options, + ) + + async def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: # pragma: nocover + await self._init_backend() + return await self._backend.connect_unix_socket( + path, timeout=timeout, socket_options=socket_options + ) + + async def sleep(self, seconds: float) -> None: # pragma: nocover + await self._init_backend() + return await self._backend.sleep(seconds) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/base.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..cf55c8b10eb543872550be863206fe2f760d0d8d --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/base.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import ssl +import time +import typing + +SOCKET_OPTION = typing.Union[ + typing.Tuple[int, int, int], + typing.Tuple[int, int, typing.Union[bytes, bytearray]], + typing.Tuple[int, int, None, int], +] + + +class NetworkStream: + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + raise NotImplementedError() # pragma: nocover + + def write(self, buffer: bytes, timeout: float | None = None) -> None: + raise NotImplementedError() # pragma: nocover + + def close(self) -> None: + raise NotImplementedError() # pragma: nocover + + def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> NetworkStream: + raise NotImplementedError() # pragma: nocover + + def get_extra_info(self, info: str) -> typing.Any: + return None # pragma: nocover + + +class NetworkBackend: + def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: + raise NotImplementedError() # pragma: nocover + + def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: + raise NotImplementedError() # pragma: nocover + + def sleep(self, seconds: float) -> None: + time.sleep(seconds) # pragma: nocover + + +class AsyncNetworkStream: + async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + raise NotImplementedError() # pragma: nocover + + async def write(self, buffer: bytes, timeout: float | None = None) -> None: + raise NotImplementedError() # pragma: nocover + + async def aclose(self) -> None: + raise NotImplementedError() # pragma: nocover + + async def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> AsyncNetworkStream: + raise NotImplementedError() # pragma: nocover + + def get_extra_info(self, info: str) -> typing.Any: + return None # pragma: nocover + + +class AsyncNetworkBackend: + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + raise NotImplementedError() # pragma: nocover + + async def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + raise NotImplementedError() # pragma: nocover + + async def sleep(self, seconds: float) -> None: + raise NotImplementedError() # pragma: nocover diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/mock.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6edca03d4d4b34f355fd53e49d4b4c699c972c --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/mock.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +import ssl +import typing + +from .._exceptions import ReadError +from .base import ( + SOCKET_OPTION, + AsyncNetworkBackend, + AsyncNetworkStream, + NetworkBackend, + NetworkStream, +) + + +class MockSSLObject: + def __init__(self, http2: bool): + self._http2 = http2 + + def selected_alpn_protocol(self) -> str: + return "h2" if self._http2 else "http/1.1" + + +class MockStream(NetworkStream): + def __init__(self, buffer: list[bytes], http2: bool = False) -> None: + self._buffer = buffer + self._http2 = http2 + self._closed = False + + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + if self._closed: + raise ReadError("Connection closed") + if not self._buffer: + return b"" + return self._buffer.pop(0) + + def write(self, buffer: bytes, timeout: float | None = None) -> None: + pass + + def close(self) -> None: + self._closed = True + + def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> NetworkStream: + return self + + def get_extra_info(self, info: str) -> typing.Any: + return MockSSLObject(http2=self._http2) if info == "ssl_object" else None + + def __repr__(self) -> str: + return "" + + +class MockBackend(NetworkBackend): + def __init__(self, buffer: list[bytes], http2: bool = False) -> None: + self._buffer = buffer + self._http2 = http2 + + def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: + return MockStream(list(self._buffer), http2=self._http2) + + def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: + return MockStream(list(self._buffer), http2=self._http2) + + def sleep(self, seconds: float) -> None: + pass + + +class AsyncMockStream(AsyncNetworkStream): + def __init__(self, buffer: list[bytes], http2: bool = False) -> None: + self._buffer = buffer + self._http2 = http2 + self._closed = False + + async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + if self._closed: + raise ReadError("Connection closed") + if not self._buffer: + return b"" + return self._buffer.pop(0) + + async def write(self, buffer: bytes, timeout: float | None = None) -> None: + pass + + async def aclose(self) -> None: + self._closed = True + + async def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> AsyncNetworkStream: + return self + + def get_extra_info(self, info: str) -> typing.Any: + return MockSSLObject(http2=self._http2) if info == "ssl_object" else None + + def __repr__(self) -> str: + return "" + + +class AsyncMockBackend(AsyncNetworkBackend): + def __init__(self, buffer: list[bytes], http2: bool = False) -> None: + self._buffer = buffer + self._http2 = http2 + + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + return AsyncMockStream(list(self._buffer), http2=self._http2) + + async def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + return AsyncMockStream(list(self._buffer), http2=self._http2) + + async def sleep(self, seconds: float) -> None: + pass diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/sync.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..4018a09c6fb1e0ef1b03ab8d84b13ebef4031f7c --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/sync.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import functools +import socket +import ssl +import sys +import typing + +from .._exceptions import ( + ConnectError, + ConnectTimeout, + ExceptionMapping, + ReadError, + ReadTimeout, + WriteError, + WriteTimeout, + map_exceptions, +) +from .._utils import is_socket_readable +from .base import SOCKET_OPTION, NetworkBackend, NetworkStream + + +class TLSinTLSStream(NetworkStream): # pragma: no cover + """ + Because the standard `SSLContext.wrap_socket` method does + not work for `SSLSocket` objects, we need this class + to implement TLS stream using an underlying `SSLObject` + instance in order to support TLS on top of TLS. + """ + + # Defined in RFC 8449 + TLS_RECORD_SIZE = 16384 + + def __init__( + self, + sock: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ): + self._sock = sock + self._incoming = ssl.MemoryBIO() + self._outgoing = ssl.MemoryBIO() + + self.ssl_obj = ssl_context.wrap_bio( + incoming=self._incoming, + outgoing=self._outgoing, + server_hostname=server_hostname, + ) + + self._sock.settimeout(timeout) + self._perform_io(self.ssl_obj.do_handshake) + + def _perform_io( + self, + func: typing.Callable[..., typing.Any], + ) -> typing.Any: + ret = None + + while True: + errno = None + try: + ret = func() + except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e: + errno = e.errno + + self._sock.sendall(self._outgoing.read()) + + if errno == ssl.SSL_ERROR_WANT_READ: + buf = self._sock.recv(self.TLS_RECORD_SIZE) + + if buf: + self._incoming.write(buf) + else: + self._incoming.write_eof() + if errno is None: + return ret + + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} + with map_exceptions(exc_map): + self._sock.settimeout(timeout) + return typing.cast( + bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes)) + ) + + def write(self, buffer: bytes, timeout: float | None = None) -> None: + exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} + with map_exceptions(exc_map): + self._sock.settimeout(timeout) + while buffer: + nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer)) + buffer = buffer[nsent:] + + def close(self) -> None: + self._sock.close() + + def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> NetworkStream: + raise NotImplementedError() + + def get_extra_info(self, info: str) -> typing.Any: + if info == "ssl_object": + return self.ssl_obj + if info == "client_addr": + return self._sock.getsockname() + if info == "server_addr": + return self._sock.getpeername() + if info == "socket": + return self._sock + if info == "is_readable": + return is_socket_readable(self._sock) + return None + + +class SyncStream(NetworkStream): + def __init__(self, sock: socket.socket) -> None: + self._sock = sock + + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} + with map_exceptions(exc_map): + self._sock.settimeout(timeout) + return self._sock.recv(max_bytes) + + def write(self, buffer: bytes, timeout: float | None = None) -> None: + if not buffer: + return + + exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} + with map_exceptions(exc_map): + while buffer: + self._sock.settimeout(timeout) + n = self._sock.send(buffer) + buffer = buffer[n:] + + def close(self) -> None: + self._sock.close() + + def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> NetworkStream: + exc_map: ExceptionMapping = { + socket.timeout: ConnectTimeout, + OSError: ConnectError, + } + with map_exceptions(exc_map): + try: + if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover + # If the underlying socket has already been upgraded + # to the TLS layer (i.e. is an instance of SSLSocket), + # we need some additional smarts to support TLS-in-TLS. + return TLSinTLSStream( + self._sock, ssl_context, server_hostname, timeout + ) + else: + self._sock.settimeout(timeout) + sock = ssl_context.wrap_socket( + self._sock, server_hostname=server_hostname + ) + except Exception as exc: # pragma: nocover + self.close() + raise exc + return SyncStream(sock) + + def get_extra_info(self, info: str) -> typing.Any: + if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket): + return self._sock._sslobj # type: ignore + if info == "client_addr": + return self._sock.getsockname() + if info == "server_addr": + return self._sock.getpeername() + if info == "socket": + return self._sock + if info == "is_readable": + return is_socket_readable(self._sock) + return None + + +class SyncBackend(NetworkBackend): + def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: + # Note that we automatically include `TCP_NODELAY` + # in addition to any other custom socket options. + if socket_options is None: + socket_options = [] # pragma: no cover + address = (host, port) + source_address = None if local_address is None else (local_address, 0) + exc_map: ExceptionMapping = { + socket.timeout: ConnectTimeout, + OSError: ConnectError, + } + + with map_exceptions(exc_map): + sock = socket.create_connection( + address, + timeout, + source_address=source_address, + ) + for option in socket_options: + sock.setsockopt(*option) # pragma: no cover + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + return SyncStream(sock) + + def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> NetworkStream: # pragma: nocover + if sys.platform == "win32": + raise RuntimeError( + "Attempted to connect to a UNIX socket on a Windows system." + ) + if socket_options is None: + socket_options = [] + + exc_map: ExceptionMapping = { + socket.timeout: ConnectTimeout, + OSError: ConnectError, + } + with map_exceptions(exc_map): + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + for option in socket_options: + sock.setsockopt(*option) + sock.settimeout(timeout) + sock.connect(path) + return SyncStream(sock) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/trio.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/trio.py new file mode 100644 index 0000000000000000000000000000000000000000..6f53f5f2a025e01e9949e2530bd9ca6928859251 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_backends/trio.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +import ssl +import typing + +import trio + +from .._exceptions import ( + ConnectError, + ConnectTimeout, + ExceptionMapping, + ReadError, + ReadTimeout, + WriteError, + WriteTimeout, + map_exceptions, +) +from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream + + +class TrioStream(AsyncNetworkStream): + def __init__(self, stream: trio.abc.Stream) -> None: + self._stream = stream + + async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + timeout_or_inf = float("inf") if timeout is None else timeout + exc_map: ExceptionMapping = { + trio.TooSlowError: ReadTimeout, + trio.BrokenResourceError: ReadError, + trio.ClosedResourceError: ReadError, + } + with map_exceptions(exc_map): + with trio.fail_after(timeout_or_inf): + data: bytes = await self._stream.receive_some(max_bytes=max_bytes) + return data + + async def write(self, buffer: bytes, timeout: float | None = None) -> None: + if not buffer: + return + + timeout_or_inf = float("inf") if timeout is None else timeout + exc_map: ExceptionMapping = { + trio.TooSlowError: WriteTimeout, + trio.BrokenResourceError: WriteError, + trio.ClosedResourceError: WriteError, + } + with map_exceptions(exc_map): + with trio.fail_after(timeout_or_inf): + await self._stream.send_all(data=buffer) + + async def aclose(self) -> None: + await self._stream.aclose() + + async def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> AsyncNetworkStream: + timeout_or_inf = float("inf") if timeout is None else timeout + exc_map: ExceptionMapping = { + trio.TooSlowError: ConnectTimeout, + trio.BrokenResourceError: ConnectError, + } + ssl_stream = trio.SSLStream( + self._stream, + ssl_context=ssl_context, + server_hostname=server_hostname, + https_compatible=True, + server_side=False, + ) + with map_exceptions(exc_map): + try: + with trio.fail_after(timeout_or_inf): + await ssl_stream.do_handshake() + except Exception as exc: # pragma: nocover + await self.aclose() + raise exc + return TrioStream(ssl_stream) + + def get_extra_info(self, info: str) -> typing.Any: + if info == "ssl_object" and isinstance(self._stream, trio.SSLStream): + # Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__. + # Tracked at https://github.com/python-trio/trio/issues/542 + return self._stream._ssl_object # type: ignore[attr-defined] + if info == "client_addr": + return self._get_socket_stream().socket.getsockname() + if info == "server_addr": + return self._get_socket_stream().socket.getpeername() + if info == "socket": + stream = self._stream + while isinstance(stream, trio.SSLStream): + stream = stream.transport_stream + assert isinstance(stream, trio.SocketStream) + return stream.socket + if info == "is_readable": + socket = self.get_extra_info("socket") + return socket.is_readable() + return None + + def _get_socket_stream(self) -> trio.SocketStream: + stream = self._stream + while isinstance(stream, trio.SSLStream): + stream = stream.transport_stream + assert isinstance(stream, trio.SocketStream) + return stream + + +class TrioBackend(AsyncNetworkBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: + # By default for TCP sockets, trio enables TCP_NODELAY. + # https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream + if socket_options is None: + socket_options = [] # pragma: no cover + timeout_or_inf = float("inf") if timeout is None else timeout + exc_map: ExceptionMapping = { + trio.TooSlowError: ConnectTimeout, + trio.BrokenResourceError: ConnectError, + OSError: ConnectError, + } + with map_exceptions(exc_map): + with trio.fail_after(timeout_or_inf): + stream: trio.abc.Stream = await trio.open_tcp_stream( + host=host, port=port, local_address=local_address + ) + for option in socket_options: + stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover + return TrioStream(stream) + + async def connect_unix_socket( + self, + path: str, + timeout: float | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> AsyncNetworkStream: # pragma: nocover + if socket_options is None: + socket_options = [] + timeout_or_inf = float("inf") if timeout is None else timeout + exc_map: ExceptionMapping = { + trio.TooSlowError: ConnectTimeout, + trio.BrokenResourceError: ConnectError, + OSError: ConnectError, + } + with map_exceptions(exc_map): + with trio.fail_after(timeout_or_inf): + stream: trio.abc.Stream = await trio.open_unix_socket(path) + for option in socket_options: + stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover + return TrioStream(stream) + + async def sleep(self, seconds: float) -> None: + await trio.sleep(seconds) # pragma: nocover diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_exceptions.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bc28d44f55bdc4b872951a74780469a3999d9ab4 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_exceptions.py @@ -0,0 +1,81 @@ +import contextlib +import typing + +ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] + + +@contextlib.contextmanager +def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: + try: + yield + except Exception as exc: # noqa: PIE786 + for from_exc, to_exc in map.items(): + if isinstance(exc, from_exc): + raise to_exc(exc) from exc + raise # pragma: nocover + + +class ConnectionNotAvailable(Exception): + pass + + +class ProxyError(Exception): + pass + + +class UnsupportedProtocol(Exception): + pass + + +class ProtocolError(Exception): + pass + + +class RemoteProtocolError(ProtocolError): + pass + + +class LocalProtocolError(ProtocolError): + pass + + +# Timeout errors + + +class TimeoutException(Exception): + pass + + +class PoolTimeout(TimeoutException): + pass + + +class ConnectTimeout(TimeoutException): + pass + + +class ReadTimeout(TimeoutException): + pass + + +class WriteTimeout(TimeoutException): + pass + + +# Network errors + + +class NetworkError(Exception): + pass + + +class ConnectError(NetworkError): + pass + + +class ReadError(NetworkError): + pass + + +class WriteError(NetworkError): + pass diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_models.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a65f13347d6621289a166d08123cbc8e1ad0157 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_models.py @@ -0,0 +1,516 @@ +from __future__ import annotations + +import base64 +import ssl +import typing +import urllib.parse + +# Functions for typechecking... + + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] +HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] + +Extensions = typing.MutableMapping[str, typing.Any] + + +def enforce_bytes(value: bytes | str, *, name: str) -> bytes: + """ + Any arguments that are ultimately represented as bytes can be specified + either as bytes or as strings. + + However we enforce that any string arguments must only contain characters in + the plain ASCII range. chr(0)...chr(127). If you need to use characters + outside that range then be precise, and use a byte-wise argument. + """ + if isinstance(value, str): + try: + return value.encode("ascii") + except UnicodeEncodeError: + raise TypeError(f"{name} strings may not include unicode characters.") + elif isinstance(value, bytes): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be bytes or str, but got {seen_type}.") + + +def enforce_url(value: URL | bytes | str, *, name: str) -> URL: + """ + Type check for URL parameters. + """ + if isinstance(value, (bytes, str)): + return URL(value) + elif isinstance(value, URL): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.") + + +def enforce_headers( + value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str +) -> list[tuple[bytes, bytes]]: + """ + Convienence function that ensure all items in request or response headers + are either bytes or strings in the plain ASCII range. + """ + if value is None: + return [] + elif isinstance(value, typing.Mapping): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value.items() + ] + elif isinstance(value, typing.Sequence): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value + ] + + seen_type = type(value).__name__ + raise TypeError( + f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}." + ) + + +def enforce_stream( + value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, + *, + name: str, +) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: + if value is None: + return ByteStream(b"") + elif isinstance(value, bytes): + return ByteStream(value) + return value + + +# * https://tools.ietf.org/html/rfc3986#section-3.2.3 +# * https://url.spec.whatwg.org/#url-miscellaneous +# * https://url.spec.whatwg.org/#scheme-state +DEFAULT_PORTS = { + b"ftp": 21, + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, +} + + +def include_request_headers( + headers: list[tuple[bytes, bytes]], + *, + url: "URL", + content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], +) -> list[tuple[bytes, bytes]]: + headers_set = set(k.lower() for k, v in headers) + + if b"host" not in headers_set: + default_port = DEFAULT_PORTS.get(url.scheme) + if url.port is None or url.port == default_port: + header_value = url.host + else: + header_value = b"%b:%d" % (url.host, url.port) + headers = [(b"Host", header_value)] + headers + + if ( + content is not None + and b"content-length" not in headers_set + and b"transfer-encoding" not in headers_set + ): + if isinstance(content, bytes): + content_length = str(len(content)).encode("ascii") + headers += [(b"Content-Length", content_length)] + else: + headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover + + return headers + + +# Interfaces for byte streams... + + +class ByteStream: + """ + A container for non-streaming content, and that supports both sync and async + stream iteration. + """ + + def __init__(self, content: bytes) -> None: + self._content = content + + def __iter__(self) -> typing.Iterator[bytes]: + yield self._content + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{len(self._content)} bytes]>" + + +class Origin: + def __init__(self, scheme: bytes, host: bytes, port: int) -> None: + self.scheme = scheme + self.host = host + self.port = port + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, Origin) + and self.scheme == other.scheme + and self.host == other.host + and self.port == other.port + ) + + def __str__(self) -> str: + scheme = self.scheme.decode("ascii") + host = self.host.decode("ascii") + port = str(self.port) + return f"{scheme}://{host}:{port}" + + +class URL: + """ + Represents the URL against which an HTTP request may be made. + + The URL may either be specified as a plain string, for convienence: + + ```python + url = httpcore.URL("https://www.example.com/") + ``` + + Or be constructed with explicitily pre-parsed components: + + ```python + url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/') + ``` + + Using this second more explicit style allows integrations that are using + `httpcore` to pass through URLs that have already been parsed in order to use + libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures + that URL parsing is treated identically at both the networking level and at any + higher layers of abstraction. + + The four components are important here, as they allow the URL to be precisely + specified in a pre-parsed format. They also allow certain types of request to + be created that could not otherwise be expressed. + + For example, an HTTP request to `http://www.example.com/` forwarded via a proxy + at `http://localhost:8080`... + + ```python + # Constructs an HTTP request with a complete URL as the target: + # GET https://www.example.com/ HTTP/1.1 + url = httpcore.URL( + scheme=b'http', + host=b'localhost', + port=8080, + target=b'https://www.example.com/' + ) + request = httpcore.Request( + method="GET", + url=url + ) + ``` + + Another example is constructing an `OPTIONS *` request... + + ```python + # Constructs an 'OPTIONS *' HTTP request: + # OPTIONS * HTTP/1.1 + url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*') + request = httpcore.Request(method="OPTIONS", url=url) + ``` + + This kind of request is not possible to formulate with a URL string, + because the `/` delimiter is always used to demark the target from the + host/port portion of the URL. + + For convenience, string-like arguments may be specified either as strings or + as bytes. However, once a request is being issue over-the-wire, the URL + components are always ultimately required to be a bytewise representation. + + In order to avoid any ambiguity over character encodings, when strings are used + as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`. + If you require a bytewise representation that is outside this range you must + handle the character encoding directly, and pass a bytes instance. + """ + + def __init__( + self, + url: bytes | str = "", + *, + scheme: bytes | str = b"", + host: bytes | str = b"", + port: int | None = None, + target: bytes | str = b"", + ) -> None: + """ + Parameters: + url: The complete URL as a string or bytes. + scheme: The URL scheme as a string or bytes. + Typically either `"http"` or `"https"`. + host: The URL host as a string or bytes. Such as `"www.example.com"`. + port: The port to connect to. Either an integer or `None`. + target: The target of the HTTP request. Such as `"/items?search=red"`. + """ + if url: + parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) + self.scheme = parsed.scheme + self.host = parsed.hostname or b"" + self.port = parsed.port + self.target = (parsed.path or b"/") + ( + b"?" + parsed.query if parsed.query else b"" + ) + else: + self.scheme = enforce_bytes(scheme, name="scheme") + self.host = enforce_bytes(host, name="host") + self.port = port + self.target = enforce_bytes(target, name="target") + + @property + def origin(self) -> Origin: + default_port = { + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, + b"socks5": 1080, + b"socks5h": 1080, + }[self.scheme] + return Origin( + scheme=self.scheme, host=self.host, port=self.port or default_port + ) + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, URL) + and other.scheme == self.scheme + and other.host == self.host + and other.port == self.port + and other.target == self.target + ) + + def __bytes__(self) -> bytes: + if self.port is None: + return b"%b://%b%b" % (self.scheme, self.host, self.target) + return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(scheme={self.scheme!r}, " + f"host={self.host!r}, port={self.port!r}, target={self.target!r})" + ) + + +class Request: + """ + An HTTP request. + """ + + def __init__( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + method: The HTTP request method, either as a string or bytes. + For example: `GET`. + url: The request URL, either as a `URL` instance, or as a string or bytes. + For example: `"https://www.example.com".` + headers: The HTTP request headers. + content: The content of the request body. + extensions: A dictionary of optional extra information included on + the request. Possible keys include `"timeout"`, and `"trace"`. + """ + self.method: bytes = enforce_bytes(method, name="method") + self.url: URL = enforce_url(url, name="url") + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + if "target" in self.extensions: + self.url = URL( + scheme=self.url.scheme, + host=self.url.host, + port=self.url.port, + target=self.extensions["target"], + ) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.method!r}]>" + + +class Response: + """ + An HTTP response. + """ + + def __init__( + self, + status: int, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + status: The HTTP status code of the response. For example `200`. + headers: The HTTP response headers. + content: The content of the response body. + extensions: A dictionary of optional extra information included on + the responseself.Possible keys include `"http_version"`, + `"reason_phrase"`, and `"network_stream"`. + """ + self.status: int = status + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + self._stream_consumed = False + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + if isinstance(self.stream, typing.Iterable): + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'response.read()' first." + ) + else: + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'await response.aread()' first." + ) + return self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.status}]>" + + # Sync interface... + + def read(self) -> bytes: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an asynchronous response using 'response.read()'. " + "You should use 'await response.aread()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part for part in self.iter_stream()]) + return self._content + + def iter_stream(self) -> typing.Iterator[bytes]: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an asynchronous response using 'for ... in " + "response.iter_stream()'. " + "You should use 'async for ... in response.aiter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'for ... in response.iter_stream()' more than once." + ) + self._stream_consumed = True + for chunk in self.stream: + yield chunk + + def close(self) -> None: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to close an asynchronous response using 'response.close()'. " + "You should use 'await response.aclose()' instead." + ) + if hasattr(self.stream, "close"): + self.stream.close() + + # Async interface... + + async def aread(self) -> bytes: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an synchronous response using " + "'await response.aread()'. " + "You should use 'response.read()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_stream()]) + return self._content + + async def aiter_stream(self) -> typing.AsyncIterator[bytes]: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an synchronous response using 'async for ... in " + "response.aiter_stream()'. " + "You should use 'for ... in response.iter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'async for ... in response.aiter_stream()' " + "more than once." + ) + self._stream_consumed = True + async for chunk in self.stream: + yield chunk + + async def aclose(self) -> None: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to close a synchronous response using " + "'await response.aclose()'. " + "You should use 'response.close()' instead." + ) + if hasattr(self.stream, "aclose"): + await self.stream.aclose() + + +class Proxy: + def __init__( + self, + url: URL | bytes | str, + auth: tuple[bytes | str, bytes | str] | None = None, + headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + ): + self.url = enforce_url(url, name="url") + self.headers = enforce_headers(headers, name="headers") + self.ssl_context = ssl_context + + if auth is not None: + username = enforce_bytes(auth[0], name="auth") + password = enforce_bytes(auth[1], name="auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self.auth: tuple[bytes, bytes] | None = (username, password) + self.headers = [(b"Proxy-Authorization", authorization)] + self.headers + else: + self.auth = None diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_ssl.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c99c5a67945b8a3a3544d481e979c791ab45fe23 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_ssl.py @@ -0,0 +1,9 @@ +import ssl + +import certifi + + +def default_ssl_context() -> ssl.SSLContext: + context = ssl.create_default_context() + context.load_verify_locations(certifi.where()) + return context diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/__init__.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b476d76d9a7ff45de8d18ec22d33d6af2982f92e --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/__init__.py @@ -0,0 +1,39 @@ +from .connection import HTTPConnection +from .connection_pool import ConnectionPool +from .http11 import HTTP11Connection +from .http_proxy import HTTPProxy +from .interfaces import ConnectionInterface + +try: + from .http2 import HTTP2Connection +except ImportError: # pragma: nocover + + class HTTP2Connection: # type: ignore + def __init__(self, *args, **kwargs) -> None: # type: ignore + raise RuntimeError( + "Attempted to use http2 support, but the `h2` package is not " + "installed. Use 'pip install httpcore[http2]'." + ) + + +try: + from .socks_proxy import SOCKSProxy +except ImportError: # pragma: nocover + + class SOCKSProxy: # type: ignore + def __init__(self, *args, **kwargs) -> None: # type: ignore + raise RuntimeError( + "Attempted to use SOCKS support, but the `socksio` package is not " + "installed. Use 'pip install httpcore[socks]'." + ) + + +__all__ = [ + "HTTPConnection", + "ConnectionPool", + "HTTPProxy", + "HTTP11Connection", + "HTTP2Connection", + "ConnectionInterface", + "SOCKSProxy", +] diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..363f8be819d2576ea65365e625dd1596ea40429a --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import itertools +import logging +import ssl +import types +import typing + +from .._backends.sync import SyncBackend +from .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStream +from .._exceptions import ConnectError, ConnectTimeout +from .._models import Origin, Request, Response +from .._ssl import default_ssl_context +from .._synchronization import Lock +from .._trace import Trace +from .http11 import HTTP11Connection +from .interfaces import ConnectionInterface + +RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc. + + +logger = logging.getLogger("httpcore.connection") + + +def exponential_backoff(factor: float) -> typing.Iterator[float]: + """ + Generate a geometric sequence that has a ratio of 2 and starts with 0. + + For example: + - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` + - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` + """ + yield 0 + for n in itertools.count(): + yield factor * 2**n + + +class HTTPConnection(ConnectionInterface): + def __init__( + self, + origin: Origin, + ssl_context: ssl.SSLContext | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: NetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + self._origin = origin + self._ssl_context = ssl_context + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._retries = retries + self._local_address = local_address + self._uds = uds + + self._network_backend: NetworkBackend = ( + SyncBackend() if network_backend is None else network_backend + ) + self._connection: ConnectionInterface | None = None + self._connect_failed: bool = False + self._request_lock = Lock() + self._socket_options = socket_options + + def handle_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection to {self._origin}" + ) + + try: + with self._request_lock: + if self._connection is None: + stream = self._connect(request) + + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + if http2_negotiated or (self._http2 and not self._http1): + from .http2 import HTTP2Connection + + self._connection = HTTP2Connection( + origin=self._origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = HTTP11Connection( + origin=self._origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + except BaseException as exc: + self._connect_failed = True + raise exc + + return self._connection.handle_request(request) + + def _connect(self, request: Request) -> NetworkStream: + timeouts = request.extensions.get("timeout", {}) + sni_hostname = request.extensions.get("sni_hostname", None) + timeout = timeouts.get("connect", None) + + retries_left = self._retries + delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) + + while True: + try: + if self._uds is None: + kwargs = { + "host": self._origin.host.decode("ascii"), + "port": self._origin.port, + "local_address": self._local_address, + "timeout": timeout, + "socket_options": self._socket_options, + } + with Trace("connect_tcp", logger, request, kwargs) as trace: + stream = self._network_backend.connect_tcp(**kwargs) + trace.return_value = stream + else: + kwargs = { + "path": self._uds, + "timeout": timeout, + "socket_options": self._socket_options, + } + with Trace( + "connect_unix_socket", logger, request, kwargs + ) as trace: + stream = self._network_backend.connect_unix_socket( + **kwargs + ) + trace.return_value = stream + + if self._origin.scheme in (b"https", b"wss"): + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": sni_hostname + or self._origin.host.decode("ascii"), + "timeout": timeout, + } + with Trace("start_tls", logger, request, kwargs) as trace: + stream = stream.start_tls(**kwargs) + trace.return_value = stream + return stream + except (ConnectError, ConnectTimeout): + if retries_left <= 0: + raise + retries_left -= 1 + delay = next(delays) + with Trace("retry", logger, request, kwargs) as trace: + self._network_backend.sleep(delay) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + def close(self) -> None: + if self._connection is not None: + with Trace("close", logger, None, {}): + self._connection.close() + + def is_available(self) -> bool: + if self._connection is None: + # If HTTP/2 support is enabled, and the resulting connection could + # end up as HTTP/2 then we should indicate the connection as being + # available to service multiple requests. + return ( + self._http2 + and (self._origin.scheme == b"https" or not self._http1) + and not self._connect_failed + ) + return self._connection.is_available() + + def has_expired(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.has_expired() + + def is_idle(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.is_idle() + + def is_closed(self) -> bool: + if self._connection is None: + return self._connect_failed + return self._connection.is_closed() + + def info(self) -> str: + if self._connection is None: + return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" + return self._connection.info() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + def __enter__(self) -> HTTPConnection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self.close() diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection_pool.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..9ccfa53e597a29ee387f9d16f3af4f695ac0d33a --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/connection_pool.py @@ -0,0 +1,420 @@ +from __future__ import annotations + +import ssl +import sys +import types +import typing + +from .._backends.sync import SyncBackend +from .._backends.base import SOCKET_OPTION, NetworkBackend +from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol +from .._models import Origin, Proxy, Request, Response +from .._synchronization import Event, ShieldCancellation, ThreadLock +from .connection import HTTPConnection +from .interfaces import ConnectionInterface, RequestInterface + + +class PoolRequest: + def __init__(self, request: Request) -> None: + self.request = request + self.connection: ConnectionInterface | None = None + self._connection_acquired = Event() + + def assign_to_connection(self, connection: ConnectionInterface | None) -> None: + self.connection = connection + self._connection_acquired.set() + + def clear_connection(self) -> None: + self.connection = None + self._connection_acquired = Event() + + def wait_for_connection( + self, timeout: float | None = None + ) -> ConnectionInterface: + if self.connection is None: + self._connection_acquired.wait(timeout=timeout) + assert self.connection is not None + return self.connection + + def is_queued(self) -> bool: + return self.connection is None + + +class ConnectionPool(RequestInterface): + """ + A connection pool for making HTTP requests. + """ + + def __init__( + self, + ssl_context: ssl.SSLContext | None = None, + proxy: Proxy | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: NetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish a + connection. + local_address: Local address to connect from. Can also be used to connect + using a particular address family. Using `local_address="0.0.0.0"` + will connect using an `AF_INET` address (IPv4), while using + `local_address="::"` will connect using an `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + socket_options: Socket options that have to be included + in the TCP socket when the connection was established. + """ + self._ssl_context = ssl_context + self._proxy = proxy + self._max_connections = ( + sys.maxsize if max_connections is None else max_connections + ) + self._max_keepalive_connections = ( + sys.maxsize + if max_keepalive_connections is None + else max_keepalive_connections + ) + self._max_keepalive_connections = min( + self._max_connections, self._max_keepalive_connections + ) + + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._retries = retries + self._local_address = local_address + self._uds = uds + + self._network_backend = ( + SyncBackend() if network_backend is None else network_backend + ) + self._socket_options = socket_options + + # The mutable state on a connection pool is the queue of incoming requests, + # and the set of connections that are servicing those requests. + self._connections: list[ConnectionInterface] = [] + self._requests: list[PoolRequest] = [] + + # We only mutate the state of the connection pool within an 'optional_thread_lock' + # context. This holds a threading lock unless we're running in async mode, + # in which case it is a no-op. + self._optional_thread_lock = ThreadLock() + + def create_connection(self, origin: Origin) -> ConnectionInterface: + if self._proxy is not None: + if self._proxy.url.scheme in (b"socks5", b"socks5h"): + from .socks_proxy import Socks5Connection + + return Socks5Connection( + proxy_origin=self._proxy.url.origin, + proxy_auth=self._proxy.auth, + remote_origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + elif origin.scheme == b"http": + from .http_proxy import ForwardHTTPConnection + + return ForwardHTTPConnection( + proxy_origin=self._proxy.url.origin, + proxy_headers=self._proxy.headers, + proxy_ssl_context=self._proxy.ssl_context, + remote_origin=origin, + keepalive_expiry=self._keepalive_expiry, + network_backend=self._network_backend, + ) + from .http_proxy import TunnelHTTPConnection + + return TunnelHTTPConnection( + proxy_origin=self._proxy.url.origin, + proxy_headers=self._proxy.headers, + proxy_ssl_context=self._proxy.ssl_context, + remote_origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + return HTTPConnection( + origin=origin, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + retries=self._retries, + local_address=self._local_address, + uds=self._uds, + network_backend=self._network_backend, + socket_options=self._socket_options, + ) + + @property + def connections(self) -> list[ConnectionInterface]: + """ + Return a list of the connections currently in the pool. + + For example: + + ```python + >>> pool.connections + [ + , + , + , + ] + ``` + """ + return list(self._connections) + + def handle_request(self, request: Request) -> Response: + """ + Send an HTTP request, and return an HTTP response. + + This is the core implementation that is called into by `.request()` or `.stream()`. + """ + scheme = request.url.scheme.decode() + if scheme == "": + raise UnsupportedProtocol( + "Request URL is missing an 'http://' or 'https://' protocol." + ) + if scheme not in ("http", "https", "ws", "wss"): + raise UnsupportedProtocol( + f"Request URL has an unsupported protocol '{scheme}://'." + ) + + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("pool", None) + + with self._optional_thread_lock: + # Add the incoming request to our request queue. + pool_request = PoolRequest(request) + self._requests.append(pool_request) + + try: + while True: + with self._optional_thread_lock: + # Assign incoming requests to available connections, + # closing or creating new connections as required. + closing = self._assign_requests_to_connections() + self._close_connections(closing) + + # Wait until this request has an assigned connection. + connection = pool_request.wait_for_connection(timeout=timeout) + + try: + # Send the request on the assigned connection. + response = connection.handle_request( + pool_request.request + ) + except ConnectionNotAvailable: + # In some cases a connection may initially be available to + # handle a request, but then become unavailable. + # + # In this case we clear the connection and try again. + pool_request.clear_connection() + else: + break # pragma: nocover + + except BaseException as exc: + with self._optional_thread_lock: + # For any exception or cancellation we remove the request from + # the queue, and then re-assign requests to connections. + self._requests.remove(pool_request) + closing = self._assign_requests_to_connections() + + self._close_connections(closing) + raise exc from None + + # Return the response. Note that in this case we still have to manage + # the point at which the response is closed. + assert isinstance(response.stream, typing.Iterable) + return Response( + status=response.status, + headers=response.headers, + content=PoolByteStream( + stream=response.stream, pool_request=pool_request, pool=self + ), + extensions=response.extensions, + ) + + def _assign_requests_to_connections(self) -> list[ConnectionInterface]: + """ + Manage the state of the connection pool, assigning incoming + requests to connections as available. + + Called whenever a new request is added or removed from the pool. + + Any closing connections are returned, allowing the I/O for closing + those connections to be handled seperately. + """ + closing_connections = [] + + # First we handle cleaning up any connections that are closed, + # have expired their keep-alive, or surplus idle connections. + for connection in list(self._connections): + if connection.is_closed(): + # log: "removing closed connection" + self._connections.remove(connection) + elif connection.has_expired(): + # log: "closing expired connection" + self._connections.remove(connection) + closing_connections.append(connection) + elif ( + connection.is_idle() + and len([connection.is_idle() for connection in self._connections]) + > self._max_keepalive_connections + ): + # log: "closing idle connection" + self._connections.remove(connection) + closing_connections.append(connection) + + # Assign queued requests to connections. + queued_requests = [request for request in self._requests if request.is_queued()] + for pool_request in queued_requests: + origin = pool_request.request.url.origin + available_connections = [ + connection + for connection in self._connections + if connection.can_handle_request(origin) and connection.is_available() + ] + idle_connections = [ + connection for connection in self._connections if connection.is_idle() + ] + + # There are three cases for how we may be able to handle the request: + # + # 1. There is an existing connection that can handle the request. + # 2. We can create a new connection to handle the request. + # 3. We can close an idle connection and then create a new connection + # to handle the request. + if available_connections: + # log: "reusing existing connection" + connection = available_connections[0] + pool_request.assign_to_connection(connection) + elif len(self._connections) < self._max_connections: + # log: "creating new connection" + connection = self.create_connection(origin) + self._connections.append(connection) + pool_request.assign_to_connection(connection) + elif idle_connections: + # log: "closing idle connection" + connection = idle_connections[0] + self._connections.remove(connection) + closing_connections.append(connection) + # log: "creating new connection" + connection = self.create_connection(origin) + self._connections.append(connection) + pool_request.assign_to_connection(connection) + + return closing_connections + + def _close_connections(self, closing: list[ConnectionInterface]) -> None: + # Close connections which have been removed from the pool. + with ShieldCancellation(): + for connection in closing: + connection.close() + + def close(self) -> None: + # Explicitly close the connection pool. + # Clears all existing requests and connections. + with self._optional_thread_lock: + closing_connections = list(self._connections) + self._connections = [] + self._close_connections(closing_connections) + + def __enter__(self) -> ConnectionPool: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self.close() + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + with self._optional_thread_lock: + request_is_queued = [request.is_queued() for request in self._requests] + connection_is_idle = [ + connection.is_idle() for connection in self._connections + ] + + num_active_requests = request_is_queued.count(False) + num_queued_requests = request_is_queued.count(True) + num_active_connections = connection_is_idle.count(False) + num_idle_connections = connection_is_idle.count(True) + + requests_info = ( + f"Requests: {num_active_requests} active, {num_queued_requests} queued" + ) + connection_info = ( + f"Connections: {num_active_connections} active, {num_idle_connections} idle" + ) + + return f"<{class_name} [{requests_info} | {connection_info}]>" + + +class PoolByteStream: + def __init__( + self, + stream: typing.Iterable[bytes], + pool_request: PoolRequest, + pool: ConnectionPool, + ) -> None: + self._stream = stream + self._pool_request = pool_request + self._pool = pool + self._closed = False + + def __iter__(self) -> typing.Iterator[bytes]: + try: + for part in self._stream: + yield part + except BaseException as exc: + self.close() + raise exc from None + + def close(self) -> None: + if not self._closed: + self._closed = True + with ShieldCancellation(): + if hasattr(self._stream, "close"): + self._stream.close() + + with self._pool._optional_thread_lock: + self._pool._requests.remove(self._pool_request) + closing = self._pool._assign_requests_to_connections() + + self._pool._close_connections(closing) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http11.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http11.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd3a97480c720d418acb1285a7b75da19b62c8c --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http11.py @@ -0,0 +1,379 @@ +from __future__ import annotations + +import enum +import logging +import ssl +import time +import types +import typing + +import h11 + +from .._backends.base import NetworkStream +from .._exceptions import ( + ConnectionNotAvailable, + LocalProtocolError, + RemoteProtocolError, + WriteError, + map_exceptions, +) +from .._models import Origin, Request, Response +from .._synchronization import Lock, ShieldCancellation +from .._trace import Trace +from .interfaces import ConnectionInterface + +logger = logging.getLogger("httpcore.http11") + + +# A subset of `h11.Event` types supported by `_send_event` +H11SendEvent = typing.Union[ + h11.Request, + h11.Data, + h11.EndOfMessage, +] + + +class HTTPConnectionState(enum.IntEnum): + NEW = 0 + ACTIVE = 1 + IDLE = 2 + CLOSED = 3 + + +class HTTP11Connection(ConnectionInterface): + READ_NUM_BYTES = 64 * 1024 + MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024 + + def __init__( + self, + origin: Origin, + stream: NetworkStream, + keepalive_expiry: float | None = None, + ) -> None: + self._origin = origin + self._network_stream = stream + self._keepalive_expiry: float | None = keepalive_expiry + self._expire_at: float | None = None + self._state = HTTPConnectionState.NEW + self._state_lock = Lock() + self._request_count = 0 + self._h11_state = h11.Connection( + our_role=h11.CLIENT, + max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, + ) + + def handle_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection " + f"to {self._origin}" + ) + + with self._state_lock: + if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): + self._request_count += 1 + self._state = HTTPConnectionState.ACTIVE + self._expire_at = None + else: + raise ConnectionNotAvailable() + + try: + kwargs = {"request": request} + try: + with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + self._send_request_headers(**kwargs) + with Trace("send_request_body", logger, request, kwargs) as trace: + self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + + with Trace( + "receive_response_headers", logger, request, kwargs + ) as trace: + ( + http_version, + status, + reason_phrase, + headers, + trailing_data, + ) = self._receive_response_headers(**kwargs) + trace.return_value = ( + http_version, + status, + reason_phrase, + headers, + ) + + network_stream = self._network_stream + + # CONNECT or Upgrade request + if (status == 101) or ( + (request.method == b"CONNECT") and (200 <= status < 300) + ): + network_stream = HTTP11UpgradeStream(network_stream, trailing_data) + + return Response( + status=status, + headers=headers, + content=HTTP11ConnectionByteStream(self, request), + extensions={ + "http_version": http_version, + "reason_phrase": reason_phrase, + "network_stream": network_stream, + }, + ) + except BaseException as exc: + with ShieldCancellation(): + with Trace("response_closed", logger, request) as trace: + self._response_closed() + raise exc + + # Sending the request... + + def _send_request_headers(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): + event = h11.Request( + method=request.method, + target=request.url.target, + headers=request.headers, + ) + self._send_event(event, timeout=timeout) + + def _send_request_body(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + assert isinstance(request.stream, typing.Iterable) + for chunk in request.stream: + event = h11.Data(data=chunk) + self._send_event(event, timeout=timeout) + + self._send_event(h11.EndOfMessage(), timeout=timeout) + + def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: + bytes_to_send = self._h11_state.send(event) + if bytes_to_send is not None: + self._network_stream.write(bytes_to_send, timeout=timeout) + + # Receiving the response... + + def _receive_response_headers( + self, request: Request + ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + while True: + event = self._receive_event(timeout=timeout) + if isinstance(event, h11.Response): + break + if ( + isinstance(event, h11.InformationalResponse) + and event.status_code == 101 + ): + break + + http_version = b"HTTP/" + event.http_version + + # h11 version 0.11+ supports a `raw_items` interface to get the + # raw header casing, rather than the enforced lowercase headers. + headers = event.headers.raw_items() + + trailing_data, _ = self._h11_state.trailing_data + + return http_version, event.status_code, event.reason, headers, trailing_data + + def _receive_response_body( + self, request: Request + ) -> typing.Iterator[bytes]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + while True: + event = self._receive_event(timeout=timeout) + if isinstance(event, h11.Data): + yield bytes(event.data) + elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): + break + + def _receive_event( + self, timeout: float | None = None + ) -> h11.Event | type[h11.PAUSED]: + while True: + with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): + event = self._h11_state.next_event() + + if event is h11.NEED_DATA: + data = self._network_stream.read( + self.READ_NUM_BYTES, timeout=timeout + ) + + # If we feed this case through h11 we'll raise an exception like: + # + # httpcore.RemoteProtocolError: can't handle event type + # ConnectionClosed when role=SERVER and state=SEND_RESPONSE + # + # Which is accurate, but not very informative from an end-user + # perspective. Instead we handle this case distinctly and treat + # it as a ConnectError. + if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: + msg = "Server disconnected without sending a response." + raise RemoteProtocolError(msg) + + self._h11_state.receive_data(data) + else: + # mypy fails to narrow the type in the above if statement above + return event # type: ignore[return-value] + + def _response_closed(self) -> None: + with self._state_lock: + if ( + self._h11_state.our_state is h11.DONE + and self._h11_state.their_state is h11.DONE + ): + self._state = HTTPConnectionState.IDLE + self._h11_state.start_next_cycle() + if self._keepalive_expiry is not None: + now = time.monotonic() + self._expire_at = now + self._keepalive_expiry + else: + self.close() + + # Once the connection is no longer required... + + def close(self) -> None: + # Note that this method unilaterally closes the connection, and does + # not have any kind of locking in place around it. + self._state = HTTPConnectionState.CLOSED + self._network_stream.close() + + # The ConnectionInterface methods provide information about the state of + # the connection, allowing for a connection pooling implementation to + # determine when to reuse and when to close the connection... + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + def is_available(self) -> bool: + # Note that HTTP/1.1 connections in the "NEW" state are not treated as + # being "available". The control flow which created the connection will + # be able to send an outgoing request, but the connection will not be + # acquired from the connection pool for any other request. + return self._state == HTTPConnectionState.IDLE + + def has_expired(self) -> bool: + now = time.monotonic() + keepalive_expired = self._expire_at is not None and now > self._expire_at + + # If the HTTP connection is idle but the socket is readable, then the + # only valid state is that the socket is about to return b"", indicating + # a server-initiated disconnect. + server_disconnected = ( + self._state == HTTPConnectionState.IDLE + and self._network_stream.get_extra_info("is_readable") + ) + + return keepalive_expired or server_disconnected + + def is_idle(self) -> bool: + return self._state == HTTPConnectionState.IDLE + + def is_closed(self) -> bool: + return self._state == HTTPConnectionState.CLOSED + + def info(self) -> str: + origin = str(self._origin) + return ( + f"{origin!r}, HTTP/1.1, {self._state.name}, " + f"Request Count: {self._request_count}" + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + origin = str(self._origin) + return ( + f"<{class_name} [{origin!r}, {self._state.name}, " + f"Request Count: {self._request_count}]>" + ) + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + def __enter__(self) -> HTTP11Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self.close() + + +class HTTP11ConnectionByteStream: + def __init__(self, connection: HTTP11Connection, request: Request) -> None: + self._connection = connection + self._request = request + self._closed = False + + def __iter__(self) -> typing.Iterator[bytes]: + kwargs = {"request": self._request} + try: + with Trace("receive_response_body", logger, self._request, kwargs): + for chunk in self._connection._receive_response_body(**kwargs): + yield chunk + except BaseException as exc: + # If we get an exception while streaming the response, + # we want to close the response (and possibly the connection) + # before raising that exception. + with ShieldCancellation(): + self.close() + raise exc + + def close(self) -> None: + if not self._closed: + self._closed = True + with Trace("response_closed", logger, self._request): + self._connection._response_closed() + + +class HTTP11UpgradeStream(NetworkStream): + def __init__(self, stream: NetworkStream, leading_data: bytes) -> None: + self._stream = stream + self._leading_data = leading_data + + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + if self._leading_data: + buffer = self._leading_data[:max_bytes] + self._leading_data = self._leading_data[max_bytes:] + return buffer + else: + return self._stream.read(max_bytes, timeout) + + def write(self, buffer: bytes, timeout: float | None = None) -> None: + self._stream.write(buffer, timeout) + + def close(self) -> None: + self._stream.close() + + def start_tls( + self, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + timeout: float | None = None, + ) -> NetworkStream: + return self._stream.start_tls(ssl_context, server_hostname, timeout) + + def get_extra_info(self, info: str) -> typing.Any: + return self._stream.get_extra_info(info) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http2.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http2.py new file mode 100644 index 0000000000000000000000000000000000000000..ddcc189001c50c37c6a03810dc21d955df919f10 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http2.py @@ -0,0 +1,592 @@ +from __future__ import annotations + +import enum +import logging +import time +import types +import typing + +import h2.config +import h2.connection +import h2.events +import h2.exceptions +import h2.settings + +from .._backends.base import NetworkStream +from .._exceptions import ( + ConnectionNotAvailable, + LocalProtocolError, + RemoteProtocolError, +) +from .._models import Origin, Request, Response +from .._synchronization import Lock, Semaphore, ShieldCancellation +from .._trace import Trace +from .interfaces import ConnectionInterface + +logger = logging.getLogger("httpcore.http2") + + +def has_body_headers(request: Request) -> bool: + return any( + k.lower() == b"content-length" or k.lower() == b"transfer-encoding" + for k, v in request.headers + ) + + +class HTTPConnectionState(enum.IntEnum): + ACTIVE = 1 + IDLE = 2 + CLOSED = 3 + + +class HTTP2Connection(ConnectionInterface): + READ_NUM_BYTES = 64 * 1024 + CONFIG = h2.config.H2Configuration(validate_inbound_headers=False) + + def __init__( + self, + origin: Origin, + stream: NetworkStream, + keepalive_expiry: float | None = None, + ): + self._origin = origin + self._network_stream = stream + self._keepalive_expiry: float | None = keepalive_expiry + self._h2_state = h2.connection.H2Connection(config=self.CONFIG) + self._state = HTTPConnectionState.IDLE + self._expire_at: float | None = None + self._request_count = 0 + self._init_lock = Lock() + self._state_lock = Lock() + self._read_lock = Lock() + self._write_lock = Lock() + self._sent_connection_init = False + self._used_all_stream_ids = False + self._connection_error = False + + # Mapping from stream ID to response stream events. + self._events: dict[ + int, + list[ + h2.events.ResponseReceived + | h2.events.DataReceived + | h2.events.StreamEnded + | h2.events.StreamReset, + ], + ] = {} + + # Connection terminated events are stored as state since + # we need to handle them for all streams. + self._connection_terminated: h2.events.ConnectionTerminated | None = None + + self._read_exception: Exception | None = None + self._write_exception: Exception | None = None + + def handle_request(self, request: Request) -> Response: + if not self.can_handle_request(request.url.origin): + # This cannot occur in normal operation, since the connection pool + # will only send requests on connections that handle them. + # It's in place simply for resilience as a guard against incorrect + # usage, for anyone working directly with httpcore connections. + raise RuntimeError( + f"Attempted to send request to {request.url.origin} on connection " + f"to {self._origin}" + ) + + with self._state_lock: + if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): + self._request_count += 1 + self._expire_at = None + self._state = HTTPConnectionState.ACTIVE + else: + raise ConnectionNotAvailable() + + with self._init_lock: + if not self._sent_connection_init: + try: + sci_kwargs = {"request": request} + with Trace( + "send_connection_init", logger, request, sci_kwargs + ): + self._send_connection_init(**sci_kwargs) + except BaseException as exc: + with ShieldCancellation(): + self.close() + raise exc + + self._sent_connection_init = True + + # Initially start with just 1 until the remote server provides + # its max_concurrent_streams value + self._max_streams = 1 + + local_settings_max_streams = ( + self._h2_state.local_settings.max_concurrent_streams + ) + self._max_streams_semaphore = Semaphore(local_settings_max_streams) + + for _ in range(local_settings_max_streams - self._max_streams): + self._max_streams_semaphore.acquire() + + self._max_streams_semaphore.acquire() + + try: + stream_id = self._h2_state.get_next_available_stream_id() + self._events[stream_id] = [] + except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover + self._used_all_stream_ids = True + self._request_count -= 1 + raise ConnectionNotAvailable() + + try: + kwargs = {"request": request, "stream_id": stream_id} + with Trace("send_request_headers", logger, request, kwargs): + self._send_request_headers(request=request, stream_id=stream_id) + with Trace("send_request_body", logger, request, kwargs): + self._send_request_body(request=request, stream_id=stream_id) + with Trace( + "receive_response_headers", logger, request, kwargs + ) as trace: + status, headers = self._receive_response( + request=request, stream_id=stream_id + ) + trace.return_value = (status, headers) + + return Response( + status=status, + headers=headers, + content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), + extensions={ + "http_version": b"HTTP/2", + "network_stream": self._network_stream, + "stream_id": stream_id, + }, + ) + except BaseException as exc: # noqa: PIE786 + with ShieldCancellation(): + kwargs = {"stream_id": stream_id} + with Trace("response_closed", logger, request, kwargs): + self._response_closed(stream_id=stream_id) + + if isinstance(exc, h2.exceptions.ProtocolError): + # One case where h2 can raise a protocol error is when a + # closed frame has been seen by the state machine. + # + # This happens when one stream is reading, and encounters + # a GOAWAY event. Other flows of control may then raise + # a protocol error at any point they interact with the 'h2_state'. + # + # In this case we'll have stored the event, and should raise + # it as a RemoteProtocolError. + if self._connection_terminated: # pragma: nocover + raise RemoteProtocolError(self._connection_terminated) + # If h2 raises a protocol error in some other state then we + # must somehow have made a protocol violation. + raise LocalProtocolError(exc) # pragma: nocover + + raise exc + + def _send_connection_init(self, request: Request) -> None: + """ + The HTTP/2 connection requires some initial setup before we can start + using individual request/response streams on it. + """ + # Need to set these manually here instead of manipulating via + # __setitem__() otherwise the H2Connection will emit SettingsUpdate + # frames in addition to sending the undesired defaults. + self._h2_state.local_settings = h2.settings.Settings( + client=True, + initial_values={ + # Disable PUSH_PROMISE frames from the server since we don't do anything + # with them for now. Maybe when we support caching? + h2.settings.SettingCodes.ENABLE_PUSH: 0, + # These two are taken from h2 for safe defaults + h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, + h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, + }, + ) + + # Some websites (*cough* Yahoo *cough*) balk at this setting being + # present in the initial handshake since it's not defined in the original + # RFC despite the RFC mandating ignoring settings you don't know about. + del self._h2_state.local_settings[ + h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL + ] + + self._h2_state.initiate_connection() + self._h2_state.increment_flow_control_window(2**24) + self._write_outgoing_data(request) + + # Sending the request... + + def _send_request_headers(self, request: Request, stream_id: int) -> None: + """ + Send the request headers to a given stream ID. + """ + end_stream = not has_body_headers(request) + + # In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. + # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require + # HTTP/1.1 style headers, and map them appropriately if we end up on + # an HTTP/2 connection. + authority = [v for k, v in request.headers if k.lower() == b"host"][0] + + headers = [ + (b":method", request.method), + (b":authority", authority), + (b":scheme", request.url.scheme), + (b":path", request.url.target), + ] + [ + (k.lower(), v) + for k, v in request.headers + if k.lower() + not in ( + b"host", + b"transfer-encoding", + ) + ] + + self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) + self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) + self._write_outgoing_data(request) + + def _send_request_body(self, request: Request, stream_id: int) -> None: + """ + Iterate over the request body sending it to a given stream ID. + """ + if not has_body_headers(request): + return + + assert isinstance(request.stream, typing.Iterable) + for data in request.stream: + self._send_stream_data(request, stream_id, data) + self._send_end_stream(request, stream_id) + + def _send_stream_data( + self, request: Request, stream_id: int, data: bytes + ) -> None: + """ + Send a single chunk of data in one or more data frames. + """ + while data: + max_flow = self._wait_for_outgoing_flow(request, stream_id) + chunk_size = min(len(data), max_flow) + chunk, data = data[:chunk_size], data[chunk_size:] + self._h2_state.send_data(stream_id, chunk) + self._write_outgoing_data(request) + + def _send_end_stream(self, request: Request, stream_id: int) -> None: + """ + Send an empty data frame on on a given stream ID with the END_STREAM flag set. + """ + self._h2_state.end_stream(stream_id) + self._write_outgoing_data(request) + + # Receiving the response... + + def _receive_response( + self, request: Request, stream_id: int + ) -> tuple[int, list[tuple[bytes, bytes]]]: + """ + Return the response status code and headers for a given stream ID. + """ + while True: + event = self._receive_stream_event(request, stream_id) + if isinstance(event, h2.events.ResponseReceived): + break + + status_code = 200 + headers = [] + assert event.headers is not None + for k, v in event.headers: + if k == b":status": + status_code = int(v.decode("ascii", errors="ignore")) + elif not k.startswith(b":"): + headers.append((k, v)) + + return (status_code, headers) + + def _receive_response_body( + self, request: Request, stream_id: int + ) -> typing.Iterator[bytes]: + """ + Iterator that returns the bytes of the response body for a given stream ID. + """ + while True: + event = self._receive_stream_event(request, stream_id) + if isinstance(event, h2.events.DataReceived): + assert event.flow_controlled_length is not None + assert event.data is not None + amount = event.flow_controlled_length + self._h2_state.acknowledge_received_data(amount, stream_id) + self._write_outgoing_data(request) + yield event.data + elif isinstance(event, h2.events.StreamEnded): + break + + def _receive_stream_event( + self, request: Request, stream_id: int + ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: + """ + Return the next available event for a given stream ID. + + Will read more data from the network if required. + """ + while not self._events.get(stream_id): + self._receive_events(request, stream_id) + event = self._events[stream_id].pop(0) + if isinstance(event, h2.events.StreamReset): + raise RemoteProtocolError(event) + return event + + def _receive_events( + self, request: Request, stream_id: int | None = None + ) -> None: + """ + Read some data from the network until we see one or more events + for a given stream ID. + """ + with self._read_lock: + if self._connection_terminated is not None: + last_stream_id = self._connection_terminated.last_stream_id + if stream_id and last_stream_id and stream_id > last_stream_id: + self._request_count -= 1 + raise ConnectionNotAvailable() + raise RemoteProtocolError(self._connection_terminated) + + # This conditional is a bit icky. We don't want to block reading if we've + # actually got an event to return for a given stream. We need to do that + # check *within* the atomic read lock. Though it also need to be optional, + # because when we call it from `_wait_for_outgoing_flow` we *do* want to + # block until we've available flow control, event when we have events + # pending for the stream ID we're attempting to send on. + if stream_id is None or not self._events.get(stream_id): + events = self._read_incoming_data(request) + for event in events: + if isinstance(event, h2.events.RemoteSettingsChanged): + with Trace( + "receive_remote_settings", logger, request + ) as trace: + self._receive_remote_settings_change(event) + trace.return_value = event + + elif isinstance( + event, + ( + h2.events.ResponseReceived, + h2.events.DataReceived, + h2.events.StreamEnded, + h2.events.StreamReset, + ), + ): + if event.stream_id in self._events: + self._events[event.stream_id].append(event) + + elif isinstance(event, h2.events.ConnectionTerminated): + self._connection_terminated = event + + self._write_outgoing_data(request) + + def _receive_remote_settings_change( + self, event: h2.events.RemoteSettingsChanged + ) -> None: + max_concurrent_streams = event.changed_settings.get( + h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS + ) + if max_concurrent_streams: + new_max_streams = min( + max_concurrent_streams.new_value, + self._h2_state.local_settings.max_concurrent_streams, + ) + if new_max_streams and new_max_streams != self._max_streams: + while new_max_streams > self._max_streams: + self._max_streams_semaphore.release() + self._max_streams += 1 + while new_max_streams < self._max_streams: + self._max_streams_semaphore.acquire() + self._max_streams -= 1 + + def _response_closed(self, stream_id: int) -> None: + self._max_streams_semaphore.release() + del self._events[stream_id] + with self._state_lock: + if self._connection_terminated and not self._events: + self.close() + + elif self._state == HTTPConnectionState.ACTIVE and not self._events: + self._state = HTTPConnectionState.IDLE + if self._keepalive_expiry is not None: + now = time.monotonic() + self._expire_at = now + self._keepalive_expiry + if self._used_all_stream_ids: # pragma: nocover + self.close() + + def close(self) -> None: + # Note that this method unilaterally closes the connection, and does + # not have any kind of locking in place around it. + self._h2_state.close_connection() + self._state = HTTPConnectionState.CLOSED + self._network_stream.close() + + # Wrappers around network read/write operations... + + def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("read", None) + + if self._read_exception is not None: + raise self._read_exception # pragma: nocover + + try: + data = self._network_stream.read(self.READ_NUM_BYTES, timeout) + if data == b"": + raise RemoteProtocolError("Server disconnected") + except Exception as exc: + # If we get a network error we should: + # + # 1. Save the exception and just raise it immediately on any future reads. + # (For example, this means that a single read timeout or disconnect will + # immediately close all pending streams. Without requiring multiple + # sequential timeouts.) + # 2. Mark the connection as errored, so that we don't accept any other + # incoming requests. + self._read_exception = exc + self._connection_error = True + raise exc + + events: list[h2.events.Event] = self._h2_state.receive_data(data) + + return events + + def _write_outgoing_data(self, request: Request) -> None: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("write", None) + + with self._write_lock: + data_to_send = self._h2_state.data_to_send() + + if self._write_exception is not None: + raise self._write_exception # pragma: nocover + + try: + self._network_stream.write(data_to_send, timeout) + except Exception as exc: # pragma: nocover + # If we get a network error we should: + # + # 1. Save the exception and just raise it immediately on any future write. + # (For example, this means that a single write timeout or disconnect will + # immediately close all pending streams. Without requiring multiple + # sequential timeouts.) + # 2. Mark the connection as errored, so that we don't accept any other + # incoming requests. + self._write_exception = exc + self._connection_error = True + raise exc + + # Flow control... + + def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: + """ + Returns the maximum allowable outgoing flow for a given stream. + + If the allowable flow is zero, then waits on the network until + WindowUpdated frames have increased the flow rate. + https://tools.ietf.org/html/rfc7540#section-6.9 + """ + local_flow: int = self._h2_state.local_flow_control_window(stream_id) + max_frame_size: int = self._h2_state.max_outbound_frame_size + flow = min(local_flow, max_frame_size) + while flow == 0: + self._receive_events(request) + local_flow = self._h2_state.local_flow_control_window(stream_id) + max_frame_size = self._h2_state.max_outbound_frame_size + flow = min(local_flow, max_frame_size) + return flow + + # Interface for connection pooling... + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._origin + + def is_available(self) -> bool: + return ( + self._state != HTTPConnectionState.CLOSED + and not self._connection_error + and not self._used_all_stream_ids + and not ( + self._h2_state.state_machine.state + == h2.connection.ConnectionState.CLOSED + ) + ) + + def has_expired(self) -> bool: + now = time.monotonic() + return self._expire_at is not None and now > self._expire_at + + def is_idle(self) -> bool: + return self._state == HTTPConnectionState.IDLE + + def is_closed(self) -> bool: + return self._state == HTTPConnectionState.CLOSED + + def info(self) -> str: + origin = str(self._origin) + return ( + f"{origin!r}, HTTP/2, {self._state.name}, " + f"Request Count: {self._request_count}" + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + origin = str(self._origin) + return ( + f"<{class_name} [{origin!r}, {self._state.name}, " + f"Request Count: {self._request_count}]>" + ) + + # These context managers are not used in the standard flow, but are + # useful for testing or working with connection instances directly. + + def __enter__(self) -> HTTP2Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self.close() + + +class HTTP2ConnectionByteStream: + def __init__( + self, connection: HTTP2Connection, request: Request, stream_id: int + ) -> None: + self._connection = connection + self._request = request + self._stream_id = stream_id + self._closed = False + + def __iter__(self) -> typing.Iterator[bytes]: + kwargs = {"request": self._request, "stream_id": self._stream_id} + try: + with Trace("receive_response_body", logger, self._request, kwargs): + for chunk in self._connection._receive_response_body( + request=self._request, stream_id=self._stream_id + ): + yield chunk + except BaseException as exc: + # If we get an exception while streaming the response, + # we want to close the response (and possibly the connection) + # before raising that exception. + with ShieldCancellation(): + self.close() + raise exc + + def close(self) -> None: + if not self._closed: + self._closed = True + kwargs = {"stream_id": self._stream_id} + with Trace("response_closed", logger, self._request, kwargs): + self._connection._response_closed(stream_id=self._stream_id) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http_proxy.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..ecca88f7dc93b78f2aa26f16cf29d17a8a83ae27 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/http_proxy.py @@ -0,0 +1,367 @@ +from __future__ import annotations + +import base64 +import logging +import ssl +import typing + +from .._backends.base import SOCKET_OPTION, NetworkBackend +from .._exceptions import ProxyError +from .._models import ( + URL, + Origin, + Request, + Response, + enforce_bytes, + enforce_headers, + enforce_url, +) +from .._ssl import default_ssl_context +from .._synchronization import Lock +from .._trace import Trace +from .connection import HTTPConnection +from .connection_pool import ConnectionPool +from .http11 import HTTP11Connection +from .interfaces import ConnectionInterface + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] + + +logger = logging.getLogger("httpcore.proxy") + + +def merge_headers( + default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, +) -> list[tuple[bytes, bytes]]: + """ + Append default_headers and override_headers, de-duplicating if a key exists + in both cases. + """ + default_headers = [] if default_headers is None else list(default_headers) + override_headers = [] if override_headers is None else list(override_headers) + has_override = set(key.lower() for key, value in override_headers) + default_headers = [ + (key, value) + for key, value in default_headers + if key.lower() not in has_override + ] + return default_headers + override_headers + + +class HTTPProxy(ConnectionPool): # pragma: nocover + """ + A connection pool that sends requests via an HTTP proxy. + """ + + def __init__( + self, + proxy_url: URL | bytes | str, + proxy_auth: tuple[bytes | str, bytes | str] | None = None, + proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + local_address: str | None = None, + uds: str | None = None, + network_backend: NetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + proxy_url: The URL to use when connecting to the proxy server. + For example `"http://127.0.0.1:8080/"`. + proxy_auth: Any proxy authentication as a two-tuple of + (username, password). May be either bytes or ascii-only str. + proxy_headers: Any HTTP headers to use for the proxy requests. + For example `{"Proxy-Authorization": "Basic :"}`. + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish + a connection. + local_address: Local address to connect from. Can also be used to + connect using a particular address family. Using + `local_address="0.0.0.0"` will connect using an `AF_INET` address + (IPv4), while using `local_address="::"` will connect using an + `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + """ + super().__init__( + ssl_context=ssl_context, + max_connections=max_connections, + max_keepalive_connections=max_keepalive_connections, + keepalive_expiry=keepalive_expiry, + http1=http1, + http2=http2, + network_backend=network_backend, + retries=retries, + local_address=local_address, + uds=uds, + socket_options=socket_options, + ) + + self._proxy_url = enforce_url(proxy_url, name="proxy_url") + if ( + self._proxy_url.scheme == b"http" and proxy_ssl_context is not None + ): # pragma: no cover + raise RuntimeError( + "The `proxy_ssl_context` argument is not allowed for the http scheme" + ) + + self._ssl_context = ssl_context + self._proxy_ssl_context = proxy_ssl_context + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + if proxy_auth is not None: + username = enforce_bytes(proxy_auth[0], name="proxy_auth") + password = enforce_bytes(proxy_auth[1], name="proxy_auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self._proxy_headers = [ + (b"Proxy-Authorization", authorization) + ] + self._proxy_headers + + def create_connection(self, origin: Origin) -> ConnectionInterface: + if origin.scheme == b"http": + return ForwardHTTPConnection( + proxy_origin=self._proxy_url.origin, + proxy_headers=self._proxy_headers, + remote_origin=origin, + keepalive_expiry=self._keepalive_expiry, + network_backend=self._network_backend, + proxy_ssl_context=self._proxy_ssl_context, + ) + return TunnelHTTPConnection( + proxy_origin=self._proxy_url.origin, + proxy_headers=self._proxy_headers, + remote_origin=origin, + ssl_context=self._ssl_context, + proxy_ssl_context=self._proxy_ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + +class ForwardHTTPConnection(ConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, + keepalive_expiry: float | None = None, + network_backend: NetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + ) -> None: + self._connection = HTTPConnection( + origin=proxy_origin, + keepalive_expiry=keepalive_expiry, + network_backend=network_backend, + socket_options=socket_options, + ssl_context=proxy_ssl_context, + ) + self._proxy_origin = proxy_origin + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + self._remote_origin = remote_origin + + def handle_request(self, request: Request) -> Response: + headers = merge_headers(self._proxy_headers, request.headers) + url = URL( + scheme=self._proxy_origin.scheme, + host=self._proxy_origin.host, + port=self._proxy_origin.port, + target=bytes(request.url), + ) + proxy_request = Request( + method=request.method, + url=url, + headers=headers, + content=request.stream, + extensions=request.extensions, + ) + return self._connection.handle_request(proxy_request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + def close(self) -> None: + self._connection.close() + + def info(self) -> str: + return self._connection.info() + + def is_available(self) -> bool: + return self._connection.is_available() + + def has_expired(self) -> bool: + return self._connection.has_expired() + + def is_idle(self) -> bool: + return self._connection.is_idle() + + def is_closed(self) -> bool: + return self._connection.is_closed() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" + + +class TunnelHTTPConnection(ConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + ssl_context: ssl.SSLContext | None = None, + proxy_ssl_context: ssl.SSLContext | None = None, + proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + network_backend: NetworkBackend | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + self._connection: ConnectionInterface = HTTPConnection( + origin=proxy_origin, + keepalive_expiry=keepalive_expiry, + network_backend=network_backend, + socket_options=socket_options, + ssl_context=proxy_ssl_context, + ) + self._proxy_origin = proxy_origin + self._remote_origin = remote_origin + self._ssl_context = ssl_context + self._proxy_ssl_context = proxy_ssl_context + self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + self._connect_lock = Lock() + self._connected = False + + def handle_request(self, request: Request) -> Response: + timeouts = request.extensions.get("timeout", {}) + timeout = timeouts.get("connect", None) + + with self._connect_lock: + if not self._connected: + target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port) + + connect_url = URL( + scheme=self._proxy_origin.scheme, + host=self._proxy_origin.host, + port=self._proxy_origin.port, + target=target, + ) + connect_headers = merge_headers( + [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers + ) + connect_request = Request( + method=b"CONNECT", + url=connect_url, + headers=connect_headers, + extensions=request.extensions, + ) + connect_response = self._connection.handle_request( + connect_request + ) + + if connect_response.status < 200 or connect_response.status > 299: + reason_bytes = connect_response.extensions.get("reason_phrase", b"") + reason_str = reason_bytes.decode("ascii", errors="ignore") + msg = "%d %s" % (connect_response.status, reason_str) + self._connection.close() + raise ProxyError(msg) + + stream = connect_response.extensions["network_stream"] + + # Upgrade the stream to SSL + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": self._remote_origin.host.decode("ascii"), + "timeout": timeout, + } + with Trace("start_tls", logger, request, kwargs) as trace: + stream = stream.start_tls(**kwargs) + trace.return_value = stream + + # Determine if we should be using HTTP/1.1 or HTTP/2 + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + + # Create the HTTP/1.1 or HTTP/2 connection + if http2_negotiated or (self._http2 and not self._http1): + from .http2 import HTTP2Connection + + self._connection = HTTP2Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = HTTP11Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + + self._connected = True + return self._connection.handle_request(request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + def close(self) -> None: + self._connection.close() + + def info(self) -> str: + return self._connection.info() + + def is_available(self) -> bool: + return self._connection.is_available() + + def has_expired(self) -> bool: + return self._connection.has_expired() + + def is_idle(self) -> bool: + return self._connection.is_idle() + + def is_closed(self) -> bool: + return self._connection.is_closed() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/interfaces.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..e673d4cc1b1dd7e7ecdbde91fd6ada386c3de03f --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/interfaces.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import contextlib +import typing + +from .._models import ( + URL, + Extensions, + HeaderTypes, + Origin, + Request, + Response, + enforce_bytes, + enforce_headers, + enforce_url, + include_request_headers, +) + + +class RequestInterface: + def request( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, + ) -> Response: + # Strict type checking on our parameters. + method = enforce_bytes(method, name="method") + url = enforce_url(url, name="url") + headers = enforce_headers(headers, name="headers") + + # Include Host header, and optionally Content-Length or Transfer-Encoding. + headers = include_request_headers(headers, url=url, content=content) + + request = Request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + response = self.handle_request(request) + try: + response.read() + finally: + response.close() + return response + + @contextlib.contextmanager + def stream( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, + ) -> typing.Iterator[Response]: + # Strict type checking on our parameters. + method = enforce_bytes(method, name="method") + url = enforce_url(url, name="url") + headers = enforce_headers(headers, name="headers") + + # Include Host header, and optionally Content-Length or Transfer-Encoding. + headers = include_request_headers(headers, url=url, content=content) + + request = Request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + response = self.handle_request(request) + try: + yield response + finally: + response.close() + + def handle_request(self, request: Request) -> Response: + raise NotImplementedError() # pragma: nocover + + +class ConnectionInterface(RequestInterface): + def close(self) -> None: + raise NotImplementedError() # pragma: nocover + + def info(self) -> str: + raise NotImplementedError() # pragma: nocover + + def can_handle_request(self, origin: Origin) -> bool: + raise NotImplementedError() # pragma: nocover + + def is_available(self) -> bool: + """ + Return `True` if the connection is currently able to accept an + outgoing request. + + An HTTP/1.1 connection will only be available if it is currently idle. + + An HTTP/2 connection will be available so long as the stream ID space is + not yet exhausted, and the connection is not in an error state. + + While the connection is being established we may not yet know if it is going + to result in an HTTP/1.1 or HTTP/2 connection. The connection should be + treated as being available, but might ultimately raise `NewConnectionRequired` + required exceptions if multiple requests are attempted over a connection + that ends up being established as HTTP/1.1. + """ + raise NotImplementedError() # pragma: nocover + + def has_expired(self) -> bool: + """ + Return `True` if the connection is in a state where it should be closed. + + This either means that the connection is idle and it has passed the + expiry time on its keep-alive, or that server has sent an EOF. + """ + raise NotImplementedError() # pragma: nocover + + def is_idle(self) -> bool: + """ + Return `True` if the connection is currently idle. + """ + raise NotImplementedError() # pragma: nocover + + def is_closed(self) -> bool: + """ + Return `True` if the connection has been closed. + + Used when a response is closed to determine if the connection may be + returned to the connection pool or not. + """ + raise NotImplementedError() # pragma: nocover diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/socks_proxy.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/socks_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca96ddfb580b19413797f41e79f7abcecdd9d79 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_sync/socks_proxy.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +import logging +import ssl + +import socksio + +from .._backends.sync import SyncBackend +from .._backends.base import NetworkBackend, NetworkStream +from .._exceptions import ConnectionNotAvailable, ProxyError +from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url +from .._ssl import default_ssl_context +from .._synchronization import Lock +from .._trace import Trace +from .connection_pool import ConnectionPool +from .http11 import HTTP11Connection +from .interfaces import ConnectionInterface + +logger = logging.getLogger("httpcore.socks") + + +AUTH_METHODS = { + b"\x00": "NO AUTHENTICATION REQUIRED", + b"\x01": "GSSAPI", + b"\x02": "USERNAME/PASSWORD", + b"\xff": "NO ACCEPTABLE METHODS", +} + +REPLY_CODES = { + b"\x00": "Succeeded", + b"\x01": "General SOCKS server failure", + b"\x02": "Connection not allowed by ruleset", + b"\x03": "Network unreachable", + b"\x04": "Host unreachable", + b"\x05": "Connection refused", + b"\x06": "TTL expired", + b"\x07": "Command not supported", + b"\x08": "Address type not supported", +} + + +def _init_socks5_connection( + stream: NetworkStream, + *, + host: bytes, + port: int, + auth: tuple[bytes, bytes] | None = None, +) -> None: + conn = socksio.socks5.SOCKS5Connection() + + # Auth method request + auth_method = ( + socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED + if auth is None + else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD + ) + conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) + outgoing_bytes = conn.data_to_send() + stream.write(outgoing_bytes) + + # Auth method response + incoming_bytes = stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5AuthReply) + if response.method != auth_method: + requested = AUTH_METHODS.get(auth_method, "UNKNOWN") + responded = AUTH_METHODS.get(response.method, "UNKNOWN") + raise ProxyError( + f"Requested {requested} from proxy server, but got {responded}." + ) + + if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: + # Username/password request + assert auth is not None + username, password = auth + conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) + outgoing_bytes = conn.data_to_send() + stream.write(outgoing_bytes) + + # Username/password response + incoming_bytes = stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) + if not response.success: + raise ProxyError("Invalid username/password") + + # Connect request + conn.send( + socksio.socks5.SOCKS5CommandRequest.from_address( + socksio.socks5.SOCKS5Command.CONNECT, (host, port) + ) + ) + outgoing_bytes = conn.data_to_send() + stream.write(outgoing_bytes) + + # Connect response + incoming_bytes = stream.read(max_bytes=4096) + response = conn.receive_data(incoming_bytes) + assert isinstance(response, socksio.socks5.SOCKS5Reply) + if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: + reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") + raise ProxyError(f"Proxy Server could not connect: {reply_code}.") + + +class SOCKSProxy(ConnectionPool): # pragma: nocover + """ + A connection pool that sends requests via an HTTP proxy. + """ + + def __init__( + self, + proxy_url: URL | bytes | str, + proxy_auth: tuple[bytes | str, bytes | str] | None = None, + ssl_context: ssl.SSLContext | None = None, + max_connections: int | None = 10, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + retries: int = 0, + network_backend: NetworkBackend | None = None, + ) -> None: + """ + A connection pool for making HTTP requests. + + Parameters: + proxy_url: The URL to use when connecting to the proxy server. + For example `"http://127.0.0.1:8080/"`. + ssl_context: An SSL context to use for verifying connections. + If not specified, the default `httpcore.default_ssl_context()` + will be used. + max_connections: The maximum number of concurrent HTTP connections that + the pool should allow. Any attempt to send a request on a pool that + would exceed this amount will block until a connection is available. + max_keepalive_connections: The maximum number of idle HTTP connections + that will be maintained in the pool. + keepalive_expiry: The duration in seconds that an idle HTTP connection + may be maintained for before being expired from the pool. + http1: A boolean indicating if HTTP/1.1 requests should be supported + by the connection pool. Defaults to True. + http2: A boolean indicating if HTTP/2 requests should be supported by + the connection pool. Defaults to False. + retries: The maximum number of retries when trying to establish + a connection. + local_address: Local address to connect from. Can also be used to + connect using a particular address family. Using + `local_address="0.0.0.0"` will connect using an `AF_INET` address + (IPv4), while using `local_address="::"` will connect using an + `AF_INET6` address (IPv6). + uds: Path to a Unix Domain Socket to use instead of TCP sockets. + network_backend: A backend instance to use for handling network I/O. + """ + super().__init__( + ssl_context=ssl_context, + max_connections=max_connections, + max_keepalive_connections=max_keepalive_connections, + keepalive_expiry=keepalive_expiry, + http1=http1, + http2=http2, + network_backend=network_backend, + retries=retries, + ) + self._ssl_context = ssl_context + self._proxy_url = enforce_url(proxy_url, name="proxy_url") + if proxy_auth is not None: + username, password = proxy_auth + username_bytes = enforce_bytes(username, name="proxy_auth") + password_bytes = enforce_bytes(password, name="proxy_auth") + self._proxy_auth: tuple[bytes, bytes] | None = ( + username_bytes, + password_bytes, + ) + else: + self._proxy_auth = None + + def create_connection(self, origin: Origin) -> ConnectionInterface: + return Socks5Connection( + proxy_origin=self._proxy_url.origin, + remote_origin=origin, + proxy_auth=self._proxy_auth, + ssl_context=self._ssl_context, + keepalive_expiry=self._keepalive_expiry, + http1=self._http1, + http2=self._http2, + network_backend=self._network_backend, + ) + + +class Socks5Connection(ConnectionInterface): + def __init__( + self, + proxy_origin: Origin, + remote_origin: Origin, + proxy_auth: tuple[bytes, bytes] | None = None, + ssl_context: ssl.SSLContext | None = None, + keepalive_expiry: float | None = None, + http1: bool = True, + http2: bool = False, + network_backend: NetworkBackend | None = None, + ) -> None: + self._proxy_origin = proxy_origin + self._remote_origin = remote_origin + self._proxy_auth = proxy_auth + self._ssl_context = ssl_context + self._keepalive_expiry = keepalive_expiry + self._http1 = http1 + self._http2 = http2 + + self._network_backend: NetworkBackend = ( + SyncBackend() if network_backend is None else network_backend + ) + self._connect_lock = Lock() + self._connection: ConnectionInterface | None = None + self._connect_failed = False + + def handle_request(self, request: Request) -> Response: + timeouts = request.extensions.get("timeout", {}) + sni_hostname = request.extensions.get("sni_hostname", None) + timeout = timeouts.get("connect", None) + + with self._connect_lock: + if self._connection is None: + try: + # Connect to the proxy + kwargs = { + "host": self._proxy_origin.host.decode("ascii"), + "port": self._proxy_origin.port, + "timeout": timeout, + } + with Trace("connect_tcp", logger, request, kwargs) as trace: + stream = self._network_backend.connect_tcp(**kwargs) + trace.return_value = stream + + # Connect to the remote host using socks5 + kwargs = { + "stream": stream, + "host": self._remote_origin.host.decode("ascii"), + "port": self._remote_origin.port, + "auth": self._proxy_auth, + } + with Trace( + "setup_socks5_connection", logger, request, kwargs + ) as trace: + _init_socks5_connection(**kwargs) + trace.return_value = stream + + # Upgrade the stream to SSL + if self._remote_origin.scheme == b"https": + ssl_context = ( + default_ssl_context() + if self._ssl_context is None + else self._ssl_context + ) + alpn_protocols = ( + ["http/1.1", "h2"] if self._http2 else ["http/1.1"] + ) + ssl_context.set_alpn_protocols(alpn_protocols) + + kwargs = { + "ssl_context": ssl_context, + "server_hostname": sni_hostname + or self._remote_origin.host.decode("ascii"), + "timeout": timeout, + } + with Trace("start_tls", logger, request, kwargs) as trace: + stream = stream.start_tls(**kwargs) + trace.return_value = stream + + # Determine if we should be using HTTP/1.1 or HTTP/2 + ssl_object = stream.get_extra_info("ssl_object") + http2_negotiated = ( + ssl_object is not None + and ssl_object.selected_alpn_protocol() == "h2" + ) + + # Create the HTTP/1.1 or HTTP/2 connection + if http2_negotiated or ( + self._http2 and not self._http1 + ): # pragma: nocover + from .http2 import HTTP2Connection + + self._connection = HTTP2Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + else: + self._connection = HTTP11Connection( + origin=self._remote_origin, + stream=stream, + keepalive_expiry=self._keepalive_expiry, + ) + except Exception as exc: + self._connect_failed = True + raise exc + elif not self._connection.is_available(): # pragma: nocover + raise ConnectionNotAvailable() + + return self._connection.handle_request(request) + + def can_handle_request(self, origin: Origin) -> bool: + return origin == self._remote_origin + + def close(self) -> None: + if self._connection is not None: + self._connection.close() + + def is_available(self) -> bool: + if self._connection is None: # pragma: nocover + # If HTTP/2 support is enabled, and the resulting connection could + # end up as HTTP/2 then we should indicate the connection as being + # available to service multiple requests. + return ( + self._http2 + and (self._remote_origin.scheme == b"https" or not self._http1) + and not self._connect_failed + ) + return self._connection.is_available() + + def has_expired(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.has_expired() + + def is_idle(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.is_idle() + + def is_closed(self) -> bool: + if self._connection is None: # pragma: nocover + return self._connect_failed + return self._connection.is_closed() + + def info(self) -> str: + if self._connection is None: # pragma: nocover + return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" + return self._connection.info() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_synchronization.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecc9e9c363e2f16c4f934cf41cf871826d6a495 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_synchronization.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import threading +import types + +from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions + +# Our async synchronization primatives use either 'anyio' or 'trio' depending +# on if they're running under asyncio or trio. + +try: + import trio +except (ImportError, NotImplementedError): # pragma: nocover + trio = None # type: ignore + +try: + import anyio +except ImportError: # pragma: nocover + anyio = None # type: ignore + + +def current_async_library() -> str: + # Determine if we're running under trio or asyncio. + # See https://sniffio.readthedocs.io/en/latest/ + try: + import sniffio + except ImportError: # pragma: nocover + environment = "asyncio" + else: + environment = sniffio.current_async_library() + + if environment not in ("asyncio", "trio"): # pragma: nocover + raise RuntimeError("Running under an unsupported async environment.") + + if environment == "asyncio" and anyio is None: # pragma: nocover + raise RuntimeError( + "Running with asyncio requires installation of 'httpcore[asyncio]'." + ) + + if environment == "trio" and trio is None: # pragma: nocover + raise RuntimeError( + "Running with trio requires installation of 'httpcore[trio]'." + ) + + return environment + + +class AsyncLock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_lock = trio.Lock() + elif self._backend == "asyncio": + self._anyio_lock = anyio.Lock() + + async def __aenter__(self) -> AsyncLock: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_lock.acquire() + elif self._backend == "asyncio": + await self._anyio_lock.acquire() + + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_lock.release() + elif self._backend == "asyncio": + self._anyio_lock.release() + + +class AsyncThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __enter__(self) -> AsyncThreadLock: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass + + +class AsyncEvent: + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_event = trio.Event() + elif self._backend == "asyncio": + self._anyio_event = anyio.Event() + + def set(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + self._trio_event.set() + elif self._backend == "asyncio": + self._anyio_event.set() + + async def wait(self, timeout: float | None = None) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} + timeout_or_inf = float("inf") if timeout is None else timeout + with map_exceptions(trio_exc_map): + with trio.fail_after(timeout_or_inf): + await self._trio_event.wait() + elif self._backend == "asyncio": + anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} + with map_exceptions(anyio_exc_map): + with anyio.fail_after(timeout): + await self._anyio_event.wait() + + +class AsyncSemaphore: + def __init__(self, bound: int) -> None: + self._bound = bound + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a semaphore with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_semaphore = trio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + elif self._backend == "asyncio": + self._anyio_semaphore = anyio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + + async def acquire(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_semaphore.acquire() + elif self._backend == "asyncio": + await self._anyio_semaphore.acquire() + + async def release(self) -> None: + if self._backend == "trio": + self._trio_semaphore.release() + elif self._backend == "asyncio": + self._anyio_semaphore.release() + + +class AsyncShieldCancellation: + # For certain portions of our codebase where we're dealing with + # closing connections during exception handling we want to shield + # the operation from being cancelled. + # + # with AsyncShieldCancellation(): + # ... # clean-up operations, shielded from cancellation. + + def __init__(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a shielded scope with the correct implementation. + """ + self._backend = current_async_library() + + if self._backend == "trio": + self._trio_shield = trio.CancelScope(shield=True) + elif self._backend == "asyncio": + self._anyio_shield = anyio.CancelScope(shield=True) + + def __enter__(self) -> AsyncShieldCancellation: + if self._backend == "trio": + self._trio_shield.__enter__() + elif self._backend == "asyncio": + self._anyio_shield.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_shield.__exit__(exc_type, exc_value, traceback) + elif self._backend == "asyncio": + self._anyio_shield.__exit__(exc_type, exc_value, traceback) + + +# Our thread-based synchronization primitives... + + +class Lock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> Lock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class ThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> ThreadLock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class Event: + def __init__(self) -> None: + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def wait(self, timeout: float | None = None) -> None: + if timeout == float("inf"): # pragma: no cover + timeout = None + if not self._event.wait(timeout=timeout): + raise PoolTimeout() # pragma: nocover + + +class Semaphore: + def __init__(self, bound: int) -> None: + self._semaphore = threading.Semaphore(value=bound) + + def acquire(self) -> None: + self._semaphore.acquire() + + def release(self) -> None: + self._semaphore.release() + + +class ShieldCancellation: + # Thread-synchronous codebases don't support cancellation semantics. + # We have this class because we need to mirror the async and sync + # cases within our package, but it's just a no-op. + def __enter__(self) -> ShieldCancellation: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_trace.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1cd7c47829ce17dbcf651ab56b4ffdce04a485 --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_trace.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import inspect +import logging +import types +import typing + +from ._models import Request + + +class Trace: + def __init__( + self, + name: str, + logger: logging.Logger, + request: Request | None = None, + kwargs: dict[str, typing.Any] | None = None, + ) -> None: + self.name = name + self.logger = logger + self.trace_extension = ( + None if request is None else request.extensions.get("trace") + ) + self.debug = self.logger.isEnabledFor(logging.DEBUG) + self.kwargs = kwargs or {} + self.return_value: typing.Any = None + self.should_trace = self.debug or self.trace_extension is not None + self.prefix = self.logger.name.split(".")[-1] + + def trace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + ret = self.trace_extension(prefix_and_name, info) + if inspect.iscoroutine(ret): # pragma: no cover + raise TypeError( + "If you are using a synchronous interface, " + "the callback of the `trace` extension should " + "be a normal function instead of an asynchronous function." + ) + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + def __enter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + self.trace(f"{self.name}.started", info) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + self.trace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + self.trace(f"{self.name}.failed", info) + + async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + coro = self.trace_extension(prefix_and_name, info) + if not inspect.iscoroutine(coro): # pragma: no cover + raise TypeError( + "If you're using an asynchronous interface, " + "the callback of the `trace` extension should " + "be an asynchronous function rather than a normal function." + ) + await coro + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + async def __aenter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + await self.atrace(f"{self.name}.started", info) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + await self.atrace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + await self.atrace(f"{self.name}.failed", info) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_utils.py b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c44ff93cb2f572afc6e679308024b744b65c3b0a --- /dev/null +++ b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/_utils.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import select +import socket +import sys + + +def is_socket_readable(sock: socket.socket | None) -> bool: + """ + Return whether a socket, as identifed by its file descriptor, is readable. + "A socket is readable" means that the read buffer isn't empty, i.e. that calling + .recv() on it would immediately return some data. + """ + # NOTE: we want check for readability without actually attempting to read, because + # we don't want to block forever if it's not readable. + + # In the case that the socket no longer exists, or cannot return a file + # descriptor, we treat it as being readable, as if it the next read operation + # on it is ready to return the terminating `b""`. + sock_fd = None if sock is None else sock.fileno() + if sock_fd is None or sock_fd < 0: # pragma: nocover + return True + + # The implementation below was stolen from: + # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 + # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316 + + # Use select.select on Windows, and when poll is unavailable and select.poll + # everywhere else. (E.g. When eventlet is in use. See #327) + if ( + sys.platform == "win32" or getattr(select, "poll", None) is None + ): # pragma: nocover + rready, _, _ = select.select([sock_fd], [], [], 0) + return bool(rready) + p = select.poll() + p.register(sock_fd, select.POLLIN) + return bool(p.poll(0)) diff --git a/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/py.typed b/miniconda3/pkgs/httpcore-1.0.9-py313h06a4308_0/lib/python3.13/site-packages/httpcore/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/bin/httpx b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/bin/httpx new file mode 100644 index 0000000000000000000000000000000000000000..724c7ef1fdf819765ca66c402da6b926f69aa2b6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/bin/httpx @@ -0,0 +1,11 @@ +#!/home/task_176044729083783/conda-bld/httpx_1760447344657/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python + +# -*- coding: utf-8 -*- +import re +import sys + +from httpx import main + +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/about.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/about.json new file mode 100644 index 0000000000000000000000000000000000000000..0db9954a244eff9c6bb7bb3d9794affd9b25e5f7 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/about.json @@ -0,0 +1,162 @@ +{ + "channels": [ + "https://repo.anaconda.com/pkgs/main", + "https://repo.anaconda.com/pkgs/r", + "https://repo.anaconda.com/pkgs/r" + ], + "conda_build_version": "25.1.2", + "conda_version": "25.1.1", + "description": "HTTPX is a fully featured HTTP client library for Python 3.\nIt includes an integrated command line client, has support\nfor both HTTP/1.1 and HTTP/2, and provides both sync and async APIs.\n", + "dev_url": "https://github.com/encode/httpx", + "doc_url": "https://www.python-httpx.org", + "env_vars": { + "CIO_TEST": "" + }, + "extra": { + "copy_test_source_files": true, + "final": true, + "recipe-maintainers": [ + "primozgodec", + "florimondmanca", + "thewchan" + ] + }, + "home": "https://github.com/encode/httpx", + "identifiers": [], + "keywords": [], + "license": "BSD-3-Clause", + "license_family": "BSD", + "license_file": "LICENSE.md", + "root_pkgs": [ + "_libgcc_mutex 0.1 main", + "ca-certificates 2025.9.9 h06a4308_0", + "ld_impl_linux-64 2.40 h12ee557_0", + "libstdcxx-ng 11.2.0 h1234567_1", + "nlohmann_json 3.11.2 h6a678d5_0", + "pybind11-abi 5 hd3eb1b0_0", + "tzdata 2025a h04d1e81_0", + "libgomp 11.2.0 h1234567_1", + "_openmp_mutex 5.1 1_gnu", + "libgcc-ng 11.2.0 h1234567_1", + "bzip2 1.0.8 h5eee18b_6", + "c-ares 1.19.1 h5eee18b_0", + "cpp-expected 1.1.0 hdb19cb5_0", + "expat 2.6.4 h6a678d5_0", + "fmt 9.1.0 hdb19cb5_1", + "icu 73.1 h6a678d5_0", + "libev 4.33 h7f8727e_1", + "libffi 3.4.4 h6a678d5_1", + "libuuid 1.41.5 h5eee18b_0", + "lz4-c 1.9.4 h6a678d5_1", + "ncurses 6.4 h6a678d5_0", + "liblief 0.12.3 h6a678d5_0", + "reproc 14.2.4 h6a678d5_2", + "simdjson 3.10.1 hdb19cb5_0", + "xz 5.4.6 h5eee18b_1", + "yaml-cpp 0.8.0 h6a678d5_1", + "zlib 1.2.13 h5eee18b_1", + "libedit 3.1.20230828 h5eee18b_0", + "libnghttp2 1.57.0 h2d74bed_0", + "libssh2 1.11.1 h251f7ec_0", + "libxml2 2.13.5 hfdd30dd_0", + "pcre2 10.42 hebb0a14_1", + "readline 8.2 h5eee18b_0", + "reproc-cpp 14.2.4 h6a678d5_2", + "spdlog 1.11.0 hdb19cb5_0", + "tk 8.6.14 h39e8969_0", + "zstd 1.5.6 hc292b87_0", + "krb5 1.20.1 h143b758_1", + "libarchive 3.7.7 hfab0078_0", + "libsolv 0.7.30 he621ea3_1", + "sqlite 3.45.3 h5eee18b_0", + "libcurl 8.11.1 hc9e6f67_0", + "python 3.12.9 h5148396_0", + "libmamba 2.0.5 haf1ee3a_1", + "menuinst 2.2.0 py312h06a4308_1", + "anaconda-anon-usage 0.5.0 py312hfc0e8ea_100", + "annotated-types 0.6.0 py312h06a4308_0", + "archspec 0.2.3 pyhd3eb1b0_0", + "boltons 24.1.0 py312h06a4308_0", + "brotli-python 1.0.9 py312h6a678d5_9", + "charset-normalizer 3.3.2 pyhd3eb1b0_0", + "distro 1.9.0 py312h06a4308_0", + "frozendict 2.4.2 py312h06a4308_0", + "idna 3.7 py312h06a4308_0", + "jsonpointer 2.1 pyhd3eb1b0_0", + "libmambapy 2.0.5 py312hdb19cb5_1", + "mdurl 0.1.0 py312h06a4308_0", + "packaging 24.2 py312h06a4308_0", + "platformdirs 3.10.0 py312h06a4308_0", + "pluggy 1.5.0 py312h06a4308_0", + "pycosat 0.6.6 py312h5eee18b_2", + "pycparser 2.21 pyhd3eb1b0_0", + "pygments 2.15.1 py312h06a4308_1", + "pysocks 1.7.1 py312h06a4308_0", + "ruamel.yaml.clib 0.2.8 py312h5eee18b_0", + "setuptools 75.8.0 py312h06a4308_0", + "tqdm 4.67.1 py312he106c6f_0", + "truststore 0.10.0 py312h06a4308_0", + "typing_extensions 4.12.2 py312h06a4308_0", + "wheel 0.45.1 py312h06a4308_0", + "cffi 1.17.1 py312h1fdaa30_1", + "jsonpatch 1.33 py312h06a4308_1", + "markdown-it-py 2.2.0 py312h06a4308_1", + "pip 25.0 py312h06a4308_0", + "ruamel.yaml 0.18.6 py312h5eee18b_0", + "typing-extensions 4.12.2 py312h06a4308_0", + "urllib3 2.3.0 py312h06a4308_0", + "cryptography 43.0.3 py312h7825ff9_1", + "pydantic-core 2.27.1 py312h4aa5aa6_0", + "requests 2.32.3 py312h06a4308_1", + "rich 13.9.4 py312h06a4308_0", + "zstandard 0.23.0 py312h2c38b39_1", + "conda-content-trust 0.2.0 py312h06a4308_1", + "conda-package-streaming 0.11.0 py312h06a4308_0", + "pydantic 2.10.3 py312h06a4308_0", + "conda-package-handling 2.4.0 py312h06a4308_0", + "conda 25.1.1 py312h06a4308_0", + "conda-anaconda-tos 0.1.2 py312h06a4308_0", + "conda-libmamba-solver 25.1.1 pyhd3eb1b0_0", + "libsodium 1.0.20 heac8642_0", + "openssl 3.0.18 hd6dcaed_0", + "patch 2.8 hb25bd0a_0", + "patchelf 0.17.2 h6a678d5_0", + "yaml 0.2.5 h7b6447c_0", + "argcomplete 3.6.2 py312h06a4308_0", + "attrs 24.3.0 py312h06a4308_0", + "certifi 2025.8.3 py312h06a4308_0", + "chardet 5.2.0 py312h06a4308_0", + "click 8.2.1 py312h06a4308_0", + "filelock 3.17.0 py312h06a4308_0", + "jmespath 1.0.1 py312h06a4308_0", + "markupsafe 3.0.2 py312h5eee18b_0", + "more-itertools 10.3.0 py312h06a4308_0", + "pkginfo 1.12.0 py312h06a4308_0", + "psutil 7.0.0 py312hee96239_0", + "py-lief 0.12.3 py312h6a678d5_0", + "python-libarchive-c 5.1 pyhd3eb1b0_0", + "pytz 2025.2 py312h06a4308_0", + "pyyaml 6.0.2 py312h5eee18b_0", + "rpds-py 0.22.3 py312h4aa5aa6_0", + "six 1.17.0 py312h06a4308_0", + "soupsieve 2.5 py312h06a4308_0", + "tomlkit 0.13.2 py312h06a4308_0", + "xmltodict 0.14.2 py312h06a4308_0", + "jinja2 3.1.6 py312h06a4308_0", + "python-dateutil 2.9.0post0 py312h06a4308_2", + "referencing 0.30.2 py312h06a4308_0", + "yq 3.4.3 py312h06a4308_0", + "beautifulsoup4 4.13.5 py312h06a4308_0", + "botocore 1.37.10 py312h06a4308_0", + "jsonschema-specifications 2023.7.1 py312h06a4308_0", + "pynacl 1.5.0 py312h2630517_2", + "jsonschema 4.25.0 py312h06a4308_0", + "s3transfer 0.11.2 py312h06a4308_0", + "boto3 1.37.10 py312h06a4308_0", + "conda-anaconda-telemetry 0.3.0 pyhd3eb1b0_1", + "conda-index 0.5.0 py312h06a4308_0", + "conda-build 25.1.2 py312h06a4308_0" + ], + "summary": "A next-generation HTTP client for Python.", + "tags": [] +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/files b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/files new file mode 100644 index 0000000000000000000000000000000000000000..e23c86a6b4c6e4d0c29e02a677d575a36e675f05 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/files @@ -0,0 +1,56 @@ +bin/httpx +lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER +lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA +lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD +lib/python3.13/site-packages/httpx-0.28.1.dist-info/REQUESTED +lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL +lib/python3.13/site-packages/httpx-0.28.1.dist-info/direct_url.json +lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt +lib/python3.13/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md +lib/python3.13/site-packages/httpx/__init__.py +lib/python3.13/site-packages/httpx/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/__version__.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_api.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_auth.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_client.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_config.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_content.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_decoders.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_exceptions.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_main.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_models.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_multipart.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_status_codes.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_types.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_urlparse.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_urls.cpython-313.pyc +lib/python3.13/site-packages/httpx/__pycache__/_utils.cpython-313.pyc +lib/python3.13/site-packages/httpx/__version__.py +lib/python3.13/site-packages/httpx/_api.py +lib/python3.13/site-packages/httpx/_auth.py +lib/python3.13/site-packages/httpx/_client.py +lib/python3.13/site-packages/httpx/_config.py +lib/python3.13/site-packages/httpx/_content.py +lib/python3.13/site-packages/httpx/_decoders.py +lib/python3.13/site-packages/httpx/_exceptions.py +lib/python3.13/site-packages/httpx/_main.py +lib/python3.13/site-packages/httpx/_models.py +lib/python3.13/site-packages/httpx/_multipart.py +lib/python3.13/site-packages/httpx/_status_codes.py +lib/python3.13/site-packages/httpx/_transports/__init__.py +lib/python3.13/site-packages/httpx/_transports/__pycache__/__init__.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/__pycache__/asgi.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/__pycache__/base.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/__pycache__/default.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/__pycache__/mock.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/__pycache__/wsgi.cpython-313.pyc +lib/python3.13/site-packages/httpx/_transports/asgi.py +lib/python3.13/site-packages/httpx/_transports/base.py +lib/python3.13/site-packages/httpx/_transports/default.py +lib/python3.13/site-packages/httpx/_transports/mock.py +lib/python3.13/site-packages/httpx/_transports/wsgi.py +lib/python3.13/site-packages/httpx/_types.py +lib/python3.13/site-packages/httpx/_urlparse.py +lib/python3.13/site-packages/httpx/_urls.py +lib/python3.13/site-packages/httpx/_utils.py +lib/python3.13/site-packages/httpx/py.typed diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/git b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/git new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/has_prefix b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/has_prefix new file mode 100644 index 0000000000000000000000000000000000000000..2c8d6aa7a59334a55bb00c2f93b2e0a507c41a0b --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/has_prefix @@ -0,0 +1 @@ +/home/task_176044729083783/conda-bld/httpx_1760447344657/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p text bin/httpx diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/hash_input.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/hash_input.json new file mode 100644 index 0000000000000000000000000000000000000000..54f8fb2da41bdb4962a008606b017773d2fef48e --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/hash_input.json @@ -0,0 +1,4 @@ +{ + "target_platform": "linux-64", + "channel_targets": "defaults" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/index.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/index.json new file mode 100644 index 0000000000000000000000000000000000000000..88f21ca72eaa595fc474cc6cfcada0e83e20f040 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/index.json @@ -0,0 +1,27 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_1", + "build_number": 1, + "constrains": [ + "click >=8.0.0,<9.0.0a0", + "h2 >=3.0.0,<5.0.0a0", + "zstandard >=0.18.0", + "socksio >=1.0.0,<2.0.0a0", + "pygments >=2.0.0,<3.0.0a0" + ], + "depends": [ + "anyio", + "certifi", + "httpcore 1.*", + "idna", + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "license": "BSD-3-Clause", + "license_family": "BSD", + "name": "httpx", + "platform": "linux", + "subdir": "linux-64", + "timestamp": 1760447364823, + "version": "0.28.1" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/licenses/LICENSE.md b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ab79d16a3f4c6c894c028d1f7431811e8711b42b --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/licenses/LICENSE.md @@ -0,0 +1,12 @@ +Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/paths.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/paths.json new file mode 100644 index 0000000000000000000000000000000000000000..b02c6c3f4272129548d1e3f5207784263d7152bc --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/paths.json @@ -0,0 +1,343 @@ +{ + "paths": [ + { + "_path": "bin/httpx", + "file_mode": "text", + "path_type": "hardlink", + "prefix_placeholder": "/home/task_176044729083783/conda-bld/httpx_1760447344657/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p", + "sha256": "ebd8946cc852cfafa72cec46dcc00bde31b39d17747d916019b0433a01bcc7d2", + "size_in_bytes": 458 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER", + "path_type": "hardlink", + "sha256": "d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8", + "size_in_bytes": 5 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA", + "path_type": "hardlink", + "sha256": "b8c5c999f4c028b9e58635a7468b9a8170ae0796fb017586e6c42ec48adeb9d8", + "size_in_bytes": 7088 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD", + "path_type": "hardlink", + "sha256": "9ba188befff5c423b4d50c7c343f7feec5340b3e0658fbc3a1d99bfea8d96f90", + "size_in_bytes": 3703 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/REQUESTED", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL", + "path_type": "hardlink", + "sha256": "aad0b0a12256807936d52d4a6f88a1773236ae527564a688bab4e3fe780e8724", + "size_in_bytes": 87 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/direct_url.json", + "path_type": "hardlink", + "sha256": "76a927f069557318abf5f2bfa5da4df6b2b40d167dec793817aa0fbe4c7e391f", + "size_in_bytes": 95 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt", + "path_type": "hardlink", + "sha256": "da55647509b12c0d6934c812376795f3da3dd070997b3866370b32eabc8a0d20", + "size_in_bytes": 37 + }, + { + "_path": "lib/python3.13/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md", + "path_type": "hardlink", + "sha256": "4ec59d544f12b5f539a3a716fd321ac58ccd8030b465221f2c880200cdf28d8d", + "size_in_bytes": 1508 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__init__.py", + "path_type": "hardlink", + "sha256": "0ac6997bac998f4ac783adf6d8058a587193315afdb718047c3e4fdff46bcfad", + "size_in_bytes": 2171 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "1453633a9ab02e1256f5188fce8fa9461e70042e14a6a113ce70582ffc8035ea", + "size_in_bytes": 2100 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/__version__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "8b5e4ad1c1292c07f06ae39487d347670825cdbc8c714a5136e9cf46f50544aa", + "size_in_bytes": 272 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_api.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "142929fdefeb3808fb737c0d277c8a06520acfadb6d9ff55cc579976b404c510", + "size_in_bytes": 10003 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_auth.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "251e8506f6e2399ccd822783e544d26a9bc46ff58a3a686ef86e7efdbeafe024", + "size_in_bytes": 15582 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_client.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "9d4c6acfd4d318e6abd75b76a138105d9af6b7fe2c8ffc3a0a3a7f8ce4caa461", + "size_in_bytes": 63446 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_config.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "21f2ecfbca87b75336341d47e3679151f9c478c192253bd643a81434a2047ee7", + "size_in_bytes": 11358 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_content.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "b14bb7f9344b015fadcd409d5729a831500e93c81519ffdbd4d8c48503777666", + "size_in_bytes": 10712 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_decoders.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "54ca5216166afe29aabc46722fea068258836ada9ae4a39cd1502bee5b508e91", + "size_in_bytes": 17222 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_exceptions.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "460ba7585e5098986ac4eeade57d3f15a1bbe3a9773560ff0515af8037614aef", + "size_in_bytes": 12321 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_main.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "62f3eb04e86ca5064a6918aaa309d8899baed44993a2c57474ff888974bc8ff2", + "size_in_bytes": 20595 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_models.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "da41e503b392b9c526eedf59c417823d8ec90b4bc0d759f02d00bd91540f5973", + "size_in_bytes": 58543 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_multipart.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "c3c31c214ecd6395e10f80a03489118f1b076eb0caab00cfa351d622d5fda55f", + "size_in_bytes": 13934 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_status_codes.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "f22ebdf31fb22804423dd2e08f0a074a6cfefa8c67149fd376292b598b5d090e", + "size_in_bytes": 7126 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_types.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "4466aa34ccb8726b9342c620d3b1cbc98597d1369f8ac9267d2625026c07ae15", + "size_in_bytes": 3861 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_urlparse.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "047a372a60835b452c6cfc634e6cd7fd40134fd63f1bff6dd0ad92b6d9b26e36", + "size_in_bytes": 18064 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_urls.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "d392bad8ccf1963001179caafbaeaf33547c5ed62a3e14a051652aebd9309bc1", + "size_in_bytes": 26906 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__pycache__/_utils.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "7c562843381684aaa2181c46ba225dba8ec6807b126bba382ca77ad7a51ebc21", + "size_in_bytes": 9503 + }, + { + "_path": "lib/python3.13/site-packages/httpx/__version__.py", + "path_type": "hardlink", + "sha256": "2e853261e3974e2786cee3ffeb850bd30c5db718eebbf41b3af13b34e83e22a5", + "size_in_bytes": 108 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_api.py", + "path_type": "hardlink", + "sha256": "aff660b388c8a5c3c92ea2b975b6d26b2aa8fe254c2856b164277ea0e1f12c4b", + "size_in_bytes": 11743 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_auth.py", + "path_type": "hardlink", + "sha256": "62bdd0c1a5122b5eeb198c7eee3f85762705233cf863d14557ed45e3eed15d7e", + "size_in_bytes": 11891 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_client.py", + "path_type": "hardlink", + "sha256": "c43f941baefe58c91e96d00039e1868fe719d91453026d7db1647194563bff8d", + "size_in_bytes": 65714 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_config.py", + "path_type": "hardlink", + "sha256": "a4fa7653ec2271f70ab05f8a6111352d876dddee84446788a1767c1a3a372d67", + "size_in_bytes": 8547 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_content.py", + "path_type": "hardlink", + "sha256": "2c61b3ac94d1dcebcde0c6f519554d2d7917247fbaa0a97002db4ef69e70ff28", + "size_in_bytes": 8161 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_decoders.py", + "path_type": "hardlink", + "sha256": "a74757f08d0d1077b1b37506a784ac66eb62321b17aeb5a5ebe1a7a956f488a3", + "size_in_bytes": 12041 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_exceptions.py", + "path_type": "hardlink", + "sha256": "6f15bb7f1ce054c01d3536f04f4567ab4e202435b5fe023f1858903ee3328cbd", + "size_in_bytes": 8527 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_main.py", + "path_type": "hardlink", + "sha256": "0a0f4631a6e24d3fecc1a0df5202118ad4b0c4b44c4b05033a6ecb7521aa940e", + "size_in_bytes": 15626 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_models.py", + "path_type": "hardlink", + "sha256": "e3ffc6bb2bf580bc6e6428708a6f247d036220e709f5a72b785392babbd97e6b", + "size_in_bytes": 44700 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_multipart.py", + "path_type": "hardlink", + "sha256": "28e1c465997aa28860f663da2b2caedf8e6aab5ac92e0df94d41b7600cd70776", + "size_in_bytes": 9843 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_status_codes.py", + "path_type": "hardlink", + "sha256": "0d89fedae7c180c797cb9b3cc77fd307bc2302e00031ec136a43eb9b9ad712c7", + "size_in_bytes": 5639 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__init__.py", + "path_type": "hardlink", + "sha256": "19b52805200ea7bcfe97ef63e5884c851dc3308727e8554b863d3bd8edcd9e7a", + "size_in_bytes": 275 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/__init__.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "f3ceeddc5a297fdd58a0481a3e1bcebdce8ae292105a4a081b24e8de529db9a8", + "size_in_bytes": 401 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/asgi.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "bc0662558ce09a68487007ff19fccce17b2e36c5b627fb819e926a673d0e9224", + "size_in_bytes": 7701 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/base.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "8a0c4e020053c1e130207dd645d7d6a175f2d8b957adbb18606c8fa79f369777", + "size_in_bytes": 3741 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/default.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "c0fea1765f3aa37497c28b1ec01f8df84f6ed944110412fdc4f137b2774e4e6d", + "size_in_bytes": 17266 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/mock.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "fb08b63a90d609f892adb29e0348495780923d560e691a5d0c88c2b0e4f389e7", + "size_in_bytes": 1983 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/__pycache__/wsgi.cpython-313.pyc", + "path_type": "hardlink", + "sha256": "f9a1dabf6ac776a32ebd6edc58c34e63f3461ea1cfe7eec57b6d26c954e45294", + "size_in_bytes": 6858 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/asgi.py", + "path_type": "hardlink", + "sha256": "1d17e20d830fb78c101f6805807660e1cfa2dec6e5a3a6cbe464ea7044fec73f", + "size_in_bytes": 5501 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/base.py", + "path_type": "hardlink", + "sha256": "9194bf54c6d58987c5e7bd29a205022756ee973fb26df2f9d4faacf7292d79b5", + "size_in_bytes": 2523 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/default.py", + "path_type": "hardlink", + "sha256": "03379a454c95c0271c4f2c8d25ec437f49f57457f3cf2769748420bf0ecf2e79", + "size_in_bytes": 13983 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/mock.py", + "path_type": "hardlink", + "sha256": "3d3a34779ebb4484d7c46ae48ba90deffebbc300317f088c0dcb972626428c4a", + "size_in_bytes": 1232 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_transports/wsgi.py", + "path_type": "hardlink", + "sha256": "35c3d7dd76a9fc4c0215958efce692c9036e227098c7540c35b3bc1807a2ea36", + "size_in_bytes": 4825 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_types.py", + "path_type": "hardlink", + "sha256": "272878d4642aec039ebfc20e58a0c083bcc26ef1c07ee7e65b983f3e24ed12b6", + "size_in_bytes": 2965 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_urlparse.py", + "path_type": "hardlink", + "sha256": "640987e3b38d7e4c6bae3f8f3d88467a21e36fa0232824be00d58837838bfca6", + "size_in_bytes": 18546 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_urls.py", + "path_type": "hardlink", + "sha256": "757f7d551d4348e1e9828f40abb3f360ee0529dc6a2a3c32369f20adff1d1cdd", + "size_in_bytes": 21550 + }, + { + "_path": "lib/python3.13/site-packages/httpx/_utils.py", + "path_type": "hardlink", + "sha256": "fd355ea802afc4990a1ddcfb74579be2cd0b66a41781e1645d281f88704aff5a", + "size_in_bytes": 8285 + }, + { + "_path": "lib/python3.13/site-packages/httpx/py.typed", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + } + ], + "paths_version": 1 +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/conda_build_config.yaml b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/conda_build_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e56919892f1377d88a619e7ba2ff64239b6b3b6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/conda_build_config.yaml @@ -0,0 +1,28 @@ +c_compiler: gcc +channel_targets: defaults +cpu_optimization_target: nocona +cran_mirror: https://cran.r-project.org +cxx_compiler: gxx +extend_keys: +- ignore_build_only_deps +- extend_keys +- ignore_version +- pin_run_as_build +fortran_compiler: gfortran +ignore_build_only_deps: +- numpy +- python +lua: '5' +numpy: '1.26' +perl: 5.26.2 +pin_run_as_build: + python: + max_pin: x.x + min_pin: x.x + r-base: + max_pin: x.x + min_pin: x.x +platform: linux-64 +python: '3.13' +r_base: '3.5' +target_platform: linux-64 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..20aca5df479beafc90ca3618ab5e618699c3cce5 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml @@ -0,0 +1,114 @@ +# This file created by conda-build 25.1.2 +# meta.yaml template originally from: +# /home/task_176044729083783/httpx-feedstock/recipe, last modified Tue Oct 14 13:08:24 2025 +# ------------------------------------------------ + +package: + name: httpx + version: 0.28.1 +source: + sha256: 75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc + url: https://pypi.io/packages/source/h/httpx/httpx-0.28.1.tar.gz +build: + entry_points: + - httpx = httpx:main + number: '1' + script: /home/task_176044729083783/conda-bld/httpx_1760447344657/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python + -m pip install . -vv --no-deps --no-build-isolation + string: py313h06a4308_1 +requirements: + host: + - _libgcc_mutex 0.1 main + - _openmp_mutex 5.1 1_gnu + - bzip2 1.0.8 h5eee18b_6 + - ca-certificates 2025.9.9 h06a4308_0 + - expat 2.7.1 h6a678d5_0 + - hatch-fancy-pypi-readme 24.1.0 py313h06a4308_0 + - hatchling 1.27.0 py313h06a4308_0 + - ld_impl_linux-64 2.44 h153f514_2 + - libffi 3.4.4 h6a678d5_1 + - libgcc-ng 11.2.0 h1234567_1 + - libgomp 11.2.0 h1234567_1 + - libmpdec 4.0.0 h5eee18b_0 + - libstdcxx-ng 11.2.0 h1234567_1 + - libuuid 1.41.5 h5eee18b_0 + - libxcb 1.17.0 h9b100fa_0 + - libzlib 1.3.1 hb25bd0a_0 + - ncurses 6.5 h7934f7d_0 + - openssl 3.0.18 hd6dcaed_0 + - packaging 25.0 py313h06a4308_0 + - pathspec 0.12.1 py313h06a4308_0 + - pip 25.2 pyhc872135_0 + - pluggy 1.5.0 py313h06a4308_0 + - pthread-stubs 0.3 h0ce48e5_1 + - python 3.13.7 h7e8bc2b_100_cp313 + - python_abi 3.13 1_cp313 + - readline 8.3 hc2a1206_0 + - setuptools 80.9.0 py313h06a4308_0 + - sqlite 3.50.2 hb25bd0a_1 + - tk 8.6.15 h54e0aa7_0 + - trove-classifiers 2025.5.9.12 py313h06a4308_0 + - tzdata 2025b h04d1e81_0 + - wheel 0.45.1 py313h06a4308_0 + - xorg-libx11 1.8.12 h9b100fa_1 + - xorg-libxau 1.0.12 h9b100fa_0 + - xorg-libxdmcp 1.1.5 h9b100fa_0 + - xorg-xorgproto 2024.1 h5eee18b_1 + - xz 5.6.4 h5eee18b_1 + - zlib 1.3.1 hb25bd0a_0 + run: + - anyio + - certifi + - httpcore ==1.* + - idna + - python >=3.13,<3.14.0a0 + - python_abi 3.13.* *_cp313 + run_constrained: + - click >=8.0.0,<9.0.0a0 + - h2 >=3.0.0,<5.0.0a0 + - pygments >=2.0.0,<3.0.0a0 + - socksio >=1.0.0,<2.0.0a0 + - zstandard >=0.18.0 +test: + commands: + - pip check + - httpx --help + - pytest -vv tests -k "not ( test_socks_proxy_deprecated or test_socks_proxy)" + imports: + - httpx + requires: + - brotli-python + - chardet + - click + - h2 + - pip + - pytest + - rich + - trio + - trustme + - uvicorn + - zstandard + source_files: + - tests +about: + description: 'HTTPX is a fully featured HTTP client library for Python 3. + + It includes an integrated command line client, has support + + for both HTTP/1.1 and HTTP/2, and provides both sync and async APIs. + + ' + dev_url: https://github.com/encode/httpx + doc_url: https://www.python-httpx.org + home: https://github.com/encode/httpx + license: BSD-3-Clause + license_family: BSD + license_file: LICENSE.md + summary: A next-generation HTTP client for Python. +extra: + copy_test_source_files: true + final: true + recipe-maintainers: + - florimondmanca + - primozgodec + - thewchan diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml.template b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml.template new file mode 100644 index 0000000000000000000000000000000000000000..7eae25024d40504f6d9e7b4272eafa138b6f18cd --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/recipe/meta.yaml.template @@ -0,0 +1,102 @@ +{% set name = "httpx" %} +{% set version = "0.28.1" %} + +package: + name: {{ name|lower }} + version: {{ version }} + +source: + url: https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz + sha256: 75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc + +build: + number: 1 + script: {{ PYTHON }} -m pip install . -vv --no-deps --no-build-isolation + skip: True # [py<38] + entry_points: + - httpx = httpx:main + +requirements: + host: + - pip + - python + - hatchling + - hatch-fancy-pypi-readme + run: + - python + - certifi + - httpcore ==1.* + - anyio + - idna + run_constrained: + - click >=8.0.0,<9.0.0a0 + - pygments >=2.0.0,<3.0.0a0 + - h2 >=3.0.0,<5.0.0a0 + - socksio >=1.0.0,<2.0.0a0 + - zstandard >=0.18.0 + +{% set tests_to_skip = "" %} +# skip tests using socksio, optional dependency, not available for all platforms +{% set tests_to_skip = tests_to_skip + " test_socks_proxy_deprecated" %} +{% set tests_to_skip = tests_to_skip + " or test_socks_proxy" %} +# skip some tests for Windows +# +# no TypeError raised +{% set tests_to_skip = tests_to_skip + " or test_multipart_encode_files_raises_exception_with_text_mode_file" %} # [win] +# these two fail on assert response.elapsed > timedelta(seconds=0) +{% set tests_to_skip = tests_to_skip + " or test_write_timeout" %} # [win] +{% set tests_to_skip = tests_to_skip + " or test_get[asyncio]" %} # [win] +{% set tests_to_skip = tests_to_skip + " or test_logging_ssl" %} # [win] +# again paths: "tests\\test_utils.py" != "tests/test_utils.py" +{% set tests_to_skip = tests_to_skip + " or test_get_ssl_cert_file" %} # [win] + +test: + source_files: + - tests + imports: + - httpx + requires: + - pip + - pytest + # You want brotli-python here rather than just the brotli that + # "import brotli" might imply + - brotli-python + - chardet + - trio + - trustme + - uvicorn + - h2 + # [cli testing] - pygment unavailable but optional + - click + - zstandard + # - pygment + - rich + commands: + - pip check + # Running the command "httpx --help" from a Windows terminal works. + # PYTHONIOENCODING=utf8 + # Solves + # "UnicodeEncodeError: 'charmap' codec can't encode character" + # during tests. + - set PYTHONIOENCODING=utf8 # [win] + - httpx --help + - pytest -vv tests -k "not ({{ tests_to_skip }})" + +about: + home: https://github.com/encode/httpx + license: BSD-3-Clause + license_family: BSD + license_file: LICENSE.md + summary: A next-generation HTTP client for Python. + description: | + HTTPX is a fully featured HTTP client library for Python 3. + It includes an integrated command line client, has support + for both HTTP/1.1 and HTTP/2, and provides both sync and async APIs. + doc_url: https://www.python-httpx.org + dev_url: https://github.com/encode/httpx + +extra: + recipe-maintainers: + - primozgodec + - florimondmanca + - thewchan diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/repodata_record.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/repodata_record.json new file mode 100644 index 0000000000000000000000000000000000000000..0803a9ad1795ab6e65b77d8b03aad5be12e52936 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/repodata_record.json @@ -0,0 +1,33 @@ +{ + "arch": "x86_64", + "build": "py313h06a4308_1", + "build_number": 1, + "channel": "https://repo.anaconda.com/pkgs/main/linux-64/", + "constrains": [ + "click >=8.0.0,<9.0.0a0", + "h2 >=3.0.0,<5.0.0a0", + "zstandard >=0.18.0", + "socksio >=1.0.0,<2.0.0a0", + "pygments >=2.0.0,<3.0.0a0" + ], + "depends": [ + "anyio", + "certifi", + "httpcore 1.*", + "idna", + "python >=3.13,<3.14.0a0", + "python_abi 3.13.* *_cp313" + ], + "fn": "httpx-0.28.1-py313h06a4308_1.conda", + "license": "BSD-3-Clause", + "license_family": "BSD", + "md5": "d25af3a5cbefe54951cb3dc369b945bb", + "name": "httpx", + "platform": "linux", + "sha256": "ea875a1564f96bd1fdbaf82e6fa51d829f099b7f69a5a9e76c5ea9d5483d9288", + "size": 217558, + "subdir": "linux-64", + "timestamp": 1760447364000, + "url": "https://repo.anaconda.com/pkgs/main/linux-64/httpx-0.28.1-py313h06a4308_1.conda", + "version": "0.28.1" +} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6334d2c4d0d714de96638465264472abf7adff02 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.py @@ -0,0 +1,3 @@ +print("import: 'httpx'") +import httpx + diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.sh b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4db6414cffcbc207f5a94281566c876d2e417f22 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/run_test.sh @@ -0,0 +1,10 @@ + + +set -ex + + + +pip check +httpx --help +pytest -vv tests -k "not ( test_socks_proxy_deprecated or test_socks_proxy)" +exit 0 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/test_time_dependencies.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/test_time_dependencies.json new file mode 100644 index 0000000000000000000000000000000000000000..1d680cf815c3fb0ceed871a9e65b13070faf3bb5 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/test_time_dependencies.json @@ -0,0 +1 @@ +["rich", "click", "trio", "trustme", "brotli-python", "uvicorn", "h2", "chardet", "pytest", "zstandard", "pip"] \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/__init__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/__init__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_async_client.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7eaa3c58ac4f4b334ebb1764d976f12bd8e6cc --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_async_client.py @@ -0,0 +1,375 @@ +from __future__ import annotations + +import typing +from datetime import timedelta + +import pytest + +import httpx + + +@pytest.mark.anyio +async def test_get(server): + url = server.url + async with httpx.AsyncClient(http2=True) as client: + response = await client.get(url) + assert response.status_code == 200 + assert response.text == "Hello, world!" + assert response.http_version == "HTTP/1.1" + assert response.headers + assert repr(response) == "" + assert response.elapsed > timedelta(seconds=0) + + +@pytest.mark.parametrize( + "url", + [ + pytest.param("invalid://example.org", id="scheme-not-http(s)"), + pytest.param("://example.org", id="no-scheme"), + pytest.param("http://", id="no-host"), + ], +) +@pytest.mark.anyio +async def test_get_invalid_url(server, url): + async with httpx.AsyncClient() as client: + with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)): + await client.get(url) + + +@pytest.mark.anyio +async def test_build_request(server): + url = server.url.copy_with(path="/echo_headers") + headers = {"Custom-header": "value"} + async with httpx.AsyncClient() as client: + request = client.build_request("GET", url) + request.headers.update(headers) + response = await client.send(request) + + assert response.status_code == 200 + assert response.url == url + + assert response.json()["Custom-header"] == "value" + + +@pytest.mark.anyio +async def test_post(server): + url = server.url + async with httpx.AsyncClient() as client: + response = await client.post(url, content=b"Hello, world!") + assert response.status_code == 200 + + +@pytest.mark.anyio +async def test_post_json(server): + url = server.url + async with httpx.AsyncClient() as client: + response = await client.post(url, json={"text": "Hello, world!"}) + assert response.status_code == 200 + + +@pytest.mark.anyio +async def test_stream_response(server): + async with httpx.AsyncClient() as client: + async with client.stream("GET", server.url) as response: + body = await response.aread() + + assert response.status_code == 200 + assert body == b"Hello, world!" + assert response.content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_access_content_stream_response(server): + async with httpx.AsyncClient() as client: + async with client.stream("GET", server.url) as response: + pass + + assert response.status_code == 200 + with pytest.raises(httpx.ResponseNotRead): + response.content # noqa: B018 + + +@pytest.mark.anyio +async def test_stream_request(server): + async def hello_world() -> typing.AsyncIterator[bytes]: + yield b"Hello, " + yield b"world!" + + async with httpx.AsyncClient() as client: + response = await client.post(server.url, content=hello_world()) + assert response.status_code == 200 + + +@pytest.mark.anyio +async def test_cannot_stream_sync_request(server): + def hello_world() -> typing.Iterator[bytes]: # pragma: no cover + yield b"Hello, " + yield b"world!" + + async with httpx.AsyncClient() as client: + with pytest.raises(RuntimeError): + await client.post(server.url, content=hello_world()) + + +@pytest.mark.anyio +async def test_raise_for_status(server): + async with httpx.AsyncClient() as client: + for status_code in (200, 400, 404, 500, 505): + response = await client.request( + "GET", server.url.copy_with(path=f"/status/{status_code}") + ) + + if 400 <= status_code < 600: + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert exc_info.value.response == response + else: + assert response.raise_for_status() is response + + +@pytest.mark.anyio +async def test_options(server): + async with httpx.AsyncClient() as client: + response = await client.options(server.url) + assert response.status_code == 200 + assert response.text == "Hello, world!" + + +@pytest.mark.anyio +async def test_head(server): + async with httpx.AsyncClient() as client: + response = await client.head(server.url) + assert response.status_code == 200 + assert response.text == "" + + +@pytest.mark.anyio +async def test_put(server): + async with httpx.AsyncClient() as client: + response = await client.put(server.url, content=b"Hello, world!") + assert response.status_code == 200 + + +@pytest.mark.anyio +async def test_patch(server): + async with httpx.AsyncClient() as client: + response = await client.patch(server.url, content=b"Hello, world!") + assert response.status_code == 200 + + +@pytest.mark.anyio +async def test_delete(server): + async with httpx.AsyncClient() as client: + response = await client.delete(server.url) + assert response.status_code == 200 + assert response.text == "Hello, world!" + + +@pytest.mark.anyio +async def test_100_continue(server): + headers = {"Expect": "100-continue"} + content = b"Echo request body" + + async with httpx.AsyncClient() as client: + response = await client.post( + server.url.copy_with(path="/echo_body"), headers=headers, content=content + ) + + assert response.status_code == 200 + assert response.content == content + + +@pytest.mark.anyio +async def test_context_managed_transport(): + class Transport(httpx.AsyncBaseTransport): + def __init__(self) -> None: + self.events: list[str] = [] + + async def aclose(self): + # The base implementation of httpx.AsyncBaseTransport just + # calls into `.aclose`, so simple transport cases can just override + # this method for any cleanup, where more complex cases + # might want to additionally override `__aenter__`/`__aexit__`. + self.events.append("transport.aclose") + + async def __aenter__(self): + await super().__aenter__() + self.events.append("transport.__aenter__") + + async def __aexit__(self, *args): + await super().__aexit__(*args) + self.events.append("transport.__aexit__") + + transport = Transport() + async with httpx.AsyncClient(transport=transport): + pass + + assert transport.events == [ + "transport.__aenter__", + "transport.aclose", + "transport.__aexit__", + ] + + +@pytest.mark.anyio +async def test_context_managed_transport_and_mount(): + class Transport(httpx.AsyncBaseTransport): + def __init__(self, name: str) -> None: + self.name: str = name + self.events: list[str] = [] + + async def aclose(self): + # The base implementation of httpx.AsyncBaseTransport just + # calls into `.aclose`, so simple transport cases can just override + # this method for any cleanup, where more complex cases + # might want to additionally override `__aenter__`/`__aexit__`. + self.events.append(f"{self.name}.aclose") + + async def __aenter__(self): + await super().__aenter__() + self.events.append(f"{self.name}.__aenter__") + + async def __aexit__(self, *args): + await super().__aexit__(*args) + self.events.append(f"{self.name}.__aexit__") + + transport = Transport(name="transport") + mounted = Transport(name="mounted") + async with httpx.AsyncClient( + transport=transport, mounts={"http://www.example.org": mounted} + ): + pass + + assert transport.events == [ + "transport.__aenter__", + "transport.aclose", + "transport.__aexit__", + ] + assert mounted.events == [ + "mounted.__aenter__", + "mounted.aclose", + "mounted.__aexit__", + ] + + +def hello_world(request): + return httpx.Response(200, text="Hello, world!") + + +@pytest.mark.anyio +async def test_client_closed_state_using_implicit_open(): + client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) + + assert not client.is_closed + await client.get("http://example.com") + + assert not client.is_closed + await client.aclose() + + assert client.is_closed + # Once we're close we cannot make any more requests. + with pytest.raises(RuntimeError): + await client.get("http://example.com") + + # Once we're closed we cannot reopen the client. + with pytest.raises(RuntimeError): + async with client: + pass # pragma: no cover + + +@pytest.mark.anyio +async def test_client_closed_state_using_with_block(): + async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client: + assert not client.is_closed + await client.get("http://example.com") + + assert client.is_closed + with pytest.raises(RuntimeError): + await client.get("http://example.com") + + +def unmounted(request: httpx.Request) -> httpx.Response: + data = {"app": "unmounted"} + return httpx.Response(200, json=data) + + +def mounted(request: httpx.Request) -> httpx.Response: + data = {"app": "mounted"} + return httpx.Response(200, json=data) + + +@pytest.mark.anyio +async def test_mounted_transport(): + transport = httpx.MockTransport(unmounted) + mounts = {"custom://": httpx.MockTransport(mounted)} + + async with httpx.AsyncClient(transport=transport, mounts=mounts) as client: + response = await client.get("https://www.example.com") + assert response.status_code == 200 + assert response.json() == {"app": "unmounted"} + + response = await client.get("custom://www.example.com") + assert response.status_code == 200 + assert response.json() == {"app": "mounted"} + + +@pytest.mark.anyio +async def test_async_mock_transport(): + async def hello_world(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, text="Hello, world!") + + transport = httpx.MockTransport(hello_world) + + async with httpx.AsyncClient(transport=transport) as client: + response = await client.get("https://www.example.com") + assert response.status_code == 200 + assert response.text == "Hello, world!" + + +@pytest.mark.anyio +async def test_cancellation_during_stream(): + """ + If any BaseException is raised during streaming the response, then the + stream should be closed. + + This includes: + + * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.) + * `trio.Cancelled` + * `KeyboardInterrupt` + * `SystemExit` + + See https://github.com/encode/httpx/issues/2139 + """ + stream_was_closed = False + + def response_with_cancel_during_stream(request): + class CancelledStream(httpx.AsyncByteStream): + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield b"Hello" + raise KeyboardInterrupt() + yield b", world" # pragma: no cover + + async def aclose(self) -> None: + nonlocal stream_was_closed + stream_was_closed = True + + return httpx.Response( + 200, headers={"Content-Length": "12"}, stream=CancelledStream() + ) + + transport = httpx.MockTransport(response_with_cancel_during_stream) + + async with httpx.AsyncClient(transport=transport) as client: + with pytest.raises(KeyboardInterrupt): + await client.get("https://www.example.com") + assert stream_was_closed + + +@pytest.mark.anyio +async def test_server_extensions(server): + url = server.url + async with httpx.AsyncClient(http2=True) as client: + response = await client.get(url) + assert response.status_code == 200 + assert response.extensions["http_version"] == b"HTTP/1.1" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_auth.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..7638b8bd68d4e505dc378185c23265361fcbf92b --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_auth.py @@ -0,0 +1,772 @@ +""" +Integration tests for authentication. + +Unit tests for auth classes also exist in tests/test_auth.py +""" + +import hashlib +import netrc +import os +import sys +import threading +import typing +from urllib.request import parse_keqv_list + +import anyio +import pytest + +import httpx + +from ..common import FIXTURES_DIR + + +class App: + """ + A mock app to test auth credentials. + """ + + def __init__(self, auth_header: str = "", status_code: int = 200) -> None: + self.auth_header = auth_header + self.status_code = status_code + + def __call__(self, request: httpx.Request) -> httpx.Response: + headers = {"www-authenticate": self.auth_header} if self.auth_header else {} + data = {"auth": request.headers.get("Authorization")} + return httpx.Response(self.status_code, headers=headers, json=data) + + +class DigestApp: + def __init__( + self, + algorithm: str = "SHA-256", + send_response_after_attempt: int = 1, + qop: str = "auth", + regenerate_nonce: bool = True, + ) -> None: + self.algorithm = algorithm + self.send_response_after_attempt = send_response_after_attempt + self.qop = qop + self._regenerate_nonce = regenerate_nonce + self._response_count = 0 + + def __call__(self, request: httpx.Request) -> httpx.Response: + if self._response_count < self.send_response_after_attempt: + return self.challenge_send(request) + + data = {"auth": request.headers.get("Authorization")} + return httpx.Response(200, json=data) + + def challenge_send(self, request: httpx.Request) -> httpx.Response: + self._response_count += 1 + nonce = ( + hashlib.sha256(os.urandom(8)).hexdigest() + if self._regenerate_nonce + else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3" + ) + challenge_data = { + "nonce": nonce, + "qop": self.qop, + "opaque": ( + "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1" + ), + "algorithm": self.algorithm, + "stale": "FALSE", + } + challenge_str = ", ".join( + '{}="{}"'.format(key, value) + for key, value in challenge_data.items() + if value + ) + + headers = { + "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}', + } + return httpx.Response(401, headers=headers) + + +class RepeatAuth(httpx.Auth): + """ + A mock authentication scheme that requires clients to send + the request a fixed number of times, and then send a last request containing + an aggregation of nonces that the server sent in 'WWW-Authenticate' headers + of intermediate responses. + """ + + requires_request_body = True + + def __init__(self, repeat: int) -> None: + self.repeat = repeat + + def auth_flow( + self, request: httpx.Request + ) -> typing.Generator[httpx.Request, httpx.Response, None]: + nonces = [] + + for index in range(self.repeat): + request.headers["Authorization"] = f"Repeat {index}" + response = yield request + nonces.append(response.headers["www-authenticate"]) + + key = ".".join(nonces) + request.headers["Authorization"] = f"Repeat {key}" + yield request + + +class ResponseBodyAuth(httpx.Auth): + """ + A mock authentication scheme that requires clients to send an 'Authorization' + header, then send back the contents of the response in the 'Authorization' + header. + """ + + requires_response_body = True + + def __init__(self, token: str) -> None: + self.token = token + + def auth_flow( + self, request: httpx.Request + ) -> typing.Generator[httpx.Request, httpx.Response, None]: + request.headers["Authorization"] = self.token + response = yield request + data = response.text + request.headers["Authorization"] = data + yield request + + +class SyncOrAsyncAuth(httpx.Auth): + """ + A mock authentication scheme that uses a different implementation for the + sync and async cases. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._async_lock = anyio.Lock() + + def sync_auth_flow( + self, request: httpx.Request + ) -> typing.Generator[httpx.Request, httpx.Response, None]: + with self._lock: + request.headers["Authorization"] = "sync-auth" + yield request + + async def async_auth_flow( + self, request: httpx.Request + ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]: + async with self._async_lock: + request.headers["Authorization"] = "async-auth" + yield request + + +@pytest.mark.anyio +async def test_basic_auth() -> None: + url = "https://example.org/" + auth = ("user", "password123") + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="} + + +@pytest.mark.anyio +async def test_basic_auth_with_stream() -> None: + """ + See: https://github.com/encode/httpx/pull/1312 + """ + url = "https://example.org/" + auth = ("user", "password123") + app = App() + + async with httpx.AsyncClient( + transport=httpx.MockTransport(app), auth=auth + ) as client: + async with client.stream("GET", url) as response: + await response.aread() + + assert response.status_code == 200 + assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="} + + +@pytest.mark.anyio +async def test_basic_auth_in_url() -> None: + url = "https://user:password123@example.org/" + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url) + + assert response.status_code == 200 + assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="} + + +@pytest.mark.anyio +async def test_basic_auth_on_session() -> None: + url = "https://example.org/" + auth = ("user", "password123") + app = App() + + async with httpx.AsyncClient( + transport=httpx.MockTransport(app), auth=auth + ) as client: + response = await client.get(url) + + assert response.status_code == 200 + assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="} + + +@pytest.mark.anyio +async def test_custom_auth() -> None: + url = "https://example.org/" + app = App() + + def auth(request: httpx.Request) -> httpx.Request: + request.headers["Authorization"] = "Token 123" + return request + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "Token 123"} + + +def test_netrc_auth_credentials_exist() -> None: + """ + When netrc auth is being used and a request is made to a host that is + in the netrc file, then the relevant credentials should be applied. + """ + netrc_file = str(FIXTURES_DIR / ".netrc") + url = "http://netrcexample.org" + app = App() + auth = httpx.NetRCAuth(netrc_file) + + with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client: + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == { + "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk" + } + + +def test_netrc_auth_credentials_do_not_exist() -> None: + """ + When netrc auth is being used and a request is made to a host that is + not in the netrc file, then no credentials should be applied. + """ + netrc_file = str(FIXTURES_DIR / ".netrc") + url = "http://example.org" + app = App() + auth = httpx.NetRCAuth(netrc_file) + + with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client: + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == {"auth": None} + + +@pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="netrc files without a password are valid from Python >= 3.11", +) +def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover + """ + Python has different netrc parsing behaviours with different versions. + For Python < 3.11 a netrc file with no password is invalid. In this case + we want to allow the parse error to be raised. + """ + netrc_file = str(FIXTURES_DIR / ".netrc-nopassword") + with pytest.raises(netrc.NetrcParseError): + httpx.NetRCAuth(netrc_file) + + +@pytest.mark.anyio +async def test_auth_disable_per_request() -> None: + url = "https://example.org/" + auth = ("user", "password123") + app = App() + + async with httpx.AsyncClient( + transport=httpx.MockTransport(app), auth=auth + ) as client: + response = await client.get(url, auth=None) + + assert response.status_code == 200 + assert response.json() == {"auth": None} + + +def test_auth_hidden_url() -> None: + url = "http://example-username:example-password@example.org/" + expected = "URL('http://example-username:[secure]@example.org/')" + assert url == httpx.URL(url) + assert expected == repr(httpx.URL(url)) + + +@pytest.mark.anyio +async def test_auth_hidden_header() -> None: + url = "https://example.org/" + auth = ("example-username", "example-password") + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert "'authorization': '[secure]'" in str(response.request.headers) + + +@pytest.mark.anyio +async def test_auth_property() -> None: + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + assert client.auth is None + + client.auth = ("user", "password123") # type: ignore + assert isinstance(client.auth, httpx.BasicAuth) + + url = "https://example.org/" + response = await client.get(url) + assert response.status_code == 200 + assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="} + + +@pytest.mark.anyio +async def test_auth_invalid_type() -> None: + app = App() + + with pytest.raises(TypeError): + client = httpx.AsyncClient( + transport=httpx.MockTransport(app), + auth="not a tuple, not a callable", # type: ignore + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + with pytest.raises(TypeError): + await client.get(auth="not a tuple, not a callable") # type: ignore + + with pytest.raises(TypeError): + client.auth = "not a tuple, not a callable" # type: ignore + + +@pytest.mark.anyio +async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": None} + assert len(response.history) == 0 + + +def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + auth_header = "Token ..." + app = App(auth_header=auth_header, status_code=401) + + client = httpx.Client(transport=httpx.MockTransport(app)) + response = client.get(url, auth=auth) + + assert response.status_code == 401 + assert response.json() == {"auth": None} + assert len(response.history) == 0 + + +@pytest.mark.anyio +async def test_digest_auth_200_response_including_digest_auth_header() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"' + app = App(auth_header=auth_header, status_code=200) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": None} + assert len(response.history) == 0 + + +@pytest.mark.anyio +async def test_digest_auth_401_response_without_digest_auth_header() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = App(auth_header="", status_code=401) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 401 + assert response.json() == {"auth": None} + assert len(response.history) == 0 + + +@pytest.mark.parametrize( + "algorithm,expected_hash_length,expected_response_length", + [ + ("MD5", 64, 32), + ("MD5-SESS", 64, 32), + ("SHA", 64, 40), + ("SHA-SESS", 64, 40), + ("SHA-256", 64, 64), + ("SHA-256-SESS", 64, 64), + ("SHA-512", 64, 128), + ("SHA-512-SESS", 64, 128), + ], +) +@pytest.mark.anyio +async def test_digest_auth( + algorithm: str, expected_hash_length: int, expected_response_length: int +) -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(algorithm=algorithm) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert len(response.history) == 1 + + authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"] + scheme, _, fields = authorization.partition(" ") + assert scheme == "Digest" + + response_fields = [field.strip() for field in fields.split(",")] + digest_data = dict(field.split("=") for field in response_fields) + + assert digest_data["username"] == '"user"' + assert digest_data["realm"] == '"httpx@example.org"' + assert "nonce" in digest_data + assert digest_data["uri"] == '"/"' + assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes + assert len(digest_data["opaque"]) == expected_hash_length + 2 + assert digest_data["algorithm"] == algorithm + assert digest_data["qop"] == "auth" + assert digest_data["nc"] == "00000001" + assert len(digest_data["cnonce"]) == 16 + 2 + + +@pytest.mark.anyio +async def test_digest_auth_no_specified_qop() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(qop="") + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert len(response.history) == 1 + + authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"] + scheme, _, fields = authorization.partition(" ") + assert scheme == "Digest" + + response_fields = [field.strip() for field in fields.split(",")] + digest_data = dict(field.split("=") for field in response_fields) + + assert "qop" not in digest_data + assert "nc" not in digest_data + assert "cnonce" not in digest_data + assert digest_data["username"] == '"user"' + assert digest_data["realm"] == '"httpx@example.org"' + assert len(digest_data["nonce"]) == 64 + 2 # extra quotes + assert digest_data["uri"] == '"/"' + assert len(digest_data["response"]) == 64 + 2 + assert len(digest_data["opaque"]) == 64 + 2 + assert digest_data["algorithm"] == "SHA-256" + + +@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth")) +@pytest.mark.anyio +async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(qop=qop) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert len(response.history) == 1 + + +@pytest.mark.anyio +async def test_digest_auth_qop_auth_int_not_implemented() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(qop="auth-int") + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + with pytest.raises(NotImplementedError): + await client.get(url, auth=auth) + + +@pytest.mark.anyio +async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(qop="not-auth") + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + with pytest.raises(httpx.ProtocolError): + await client.get(url, auth=auth) + + +@pytest.mark.anyio +async def test_digest_auth_incorrect_credentials() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp(send_response_after_attempt=2) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 401 + assert len(response.history) == 1 + + +@pytest.mark.anyio +async def test_digest_auth_reuses_challenge() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response_1 = await client.get(url, auth=auth) + response_2 = await client.get(url, auth=auth) + + assert response_1.status_code == 200 + assert response_2.status_code == 200 + + assert len(response_1.history) == 1 + assert len(response_2.history) == 0 + + +@pytest.mark.anyio +async def test_digest_auth_resets_nonce_count_after_401() -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response_1 = await client.get(url, auth=auth) + assert response_1.status_code == 200 + assert len(response_1.history) == 1 + + first_nonce = parse_keqv_list( + response_1.request.headers["Authorization"].split(", ") + )["nonce"] + first_nc = parse_keqv_list( + response_1.request.headers["Authorization"].split(", ") + )["nc"] + + # with this we now force a 401 on a subsequent (but initial) request + app.send_response_after_attempt = 2 + + # we expect the client again to try to authenticate, + # i.e. the history length must be 1 + response_2 = await client.get(url, auth=auth) + assert response_2.status_code == 200 + assert len(response_2.history) == 1 + + second_nonce = parse_keqv_list( + response_2.request.headers["Authorization"].split(", ") + )["nonce"] + second_nc = parse_keqv_list( + response_2.request.headers["Authorization"].split(", ") + )["nc"] + + assert first_nonce != second_nonce # ensures that the auth challenge was reset + assert ( + first_nc == second_nc + ) # ensures the nonce count is reset when the authentication failed + + +@pytest.mark.parametrize( + "auth_header", + [ + 'Digest realm="httpx@example.org", qop="auth"', # missing fields + 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list + ], +) +@pytest.mark.anyio +async def test_async_digest_auth_raises_protocol_error_on_malformed_header( + auth_header: str, +) -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = App(auth_header=auth_header, status_code=401) + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + with pytest.raises(httpx.ProtocolError): + await client.get(url, auth=auth) + + +@pytest.mark.parametrize( + "auth_header", + [ + 'Digest realm="httpx@example.org", qop="auth"', # missing fields + 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list + ], +) +def test_sync_digest_auth_raises_protocol_error_on_malformed_header( + auth_header: str, +) -> None: + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = App(auth_header=auth_header, status_code=401) + + with httpx.Client(transport=httpx.MockTransport(app)) as client: + with pytest.raises(httpx.ProtocolError): + client.get(url, auth=auth) + + +@pytest.mark.anyio +async def test_async_auth_history() -> None: + """ + Test that intermediate requests sent as part of an authentication flow + are recorded in the response history. + """ + url = "https://example.org/" + auth = RepeatAuth(repeat=2) + app = App(auth_header="abc") + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "Repeat abc.abc"} + + assert len(response.history) == 2 + resp1, resp2 = response.history + assert resp1.json() == {"auth": "Repeat 0"} + assert resp2.json() == {"auth": "Repeat 1"} + + assert len(resp2.history) == 1 + assert resp2.history == [resp1] + + assert len(resp1.history) == 0 + + +def test_sync_auth_history() -> None: + """ + Test that intermediate requests sent as part of an authentication flow + are recorded in the response history. + """ + url = "https://example.org/" + auth = RepeatAuth(repeat=2) + app = App(auth_header="abc") + + with httpx.Client(transport=httpx.MockTransport(app)) as client: + response = client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "Repeat abc.abc"} + + assert len(response.history) == 2 + resp1, resp2 = response.history + assert resp1.json() == {"auth": "Repeat 0"} + assert resp2.json() == {"auth": "Repeat 1"} + + assert len(resp2.history) == 1 + assert resp2.history == [resp1] + + assert len(resp1.history) == 0 + + +class ConsumeBodyTransport(httpx.MockTransport): + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + assert isinstance(request.stream, httpx.AsyncByteStream) + [_ async for _ in request.stream] + return self.handler(request) # type: ignore[return-value] + + +@pytest.mark.anyio +async def test_digest_auth_unavailable_streaming_body(): + url = "https://example.org/" + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp() + + async def streaming_body() -> typing.AsyncIterator[bytes]: + yield b"Example request body" # pragma: no cover + + async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client: + with pytest.raises(httpx.StreamConsumed): + await client.post(url, content=streaming_body(), auth=auth) + + +@pytest.mark.anyio +async def test_async_auth_reads_response_body() -> None: + """ + Test that we can read the response body in an auth flow if `requires_response_body` + is set. + """ + url = "https://example.org/" + auth = ResponseBodyAuth("xyz") + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": '{"auth":"xyz"}'} + + +def test_sync_auth_reads_response_body() -> None: + """ + Test that we can read the response body in an auth flow if `requires_response_body` + is set. + """ + url = "https://example.org/" + auth = ResponseBodyAuth("xyz") + app = App() + + with httpx.Client(transport=httpx.MockTransport(app)) as client: + response = client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": '{"auth":"xyz"}'} + + +@pytest.mark.anyio +async def test_async_auth() -> None: + """ + Test that we can use an auth implementation specific to the async case, to + support cases that require performing I/O or using concurrency primitives (such + as checking a disk-based cache or fetching a token from a remote auth server). + """ + url = "https://example.org/" + auth = SyncOrAsyncAuth() + app = App() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "async-auth"} + + +def test_sync_auth() -> None: + """ + Test that we can use an auth implementation specific to the sync case. + """ + url = "https://example.org/" + auth = SyncOrAsyncAuth() + app = App() + + with httpx.Client(transport=httpx.MockTransport(app)) as client: + response = client.get(url, auth=auth) + + assert response.status_code == 200 + assert response.json() == {"auth": "sync-auth"} diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_client.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_client.py new file mode 100644 index 0000000000000000000000000000000000000000..657839018ab3ded203937f970eeeb23f26561775 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_client.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import typing +from datetime import timedelta + +import chardet +import pytest + +import httpx + + +def autodetect(content): + return chardet.detect(content).get("encoding") + + +def test_get(server): + url = server.url + with httpx.Client(http2=True) as http: + response = http.get(url) + assert response.status_code == 200 + assert response.url == url + assert response.content == b"Hello, world!" + assert response.text == "Hello, world!" + assert response.http_version == "HTTP/1.1" + assert response.encoding == "utf-8" + assert response.request.url == url + assert response.headers + assert response.is_redirect is False + assert repr(response) == "" + assert response.elapsed > timedelta(0) + + +@pytest.mark.parametrize( + "url", + [ + pytest.param("invalid://example.org", id="scheme-not-http(s)"), + pytest.param("://example.org", id="no-scheme"), + pytest.param("http://", id="no-host"), + ], +) +def test_get_invalid_url(server, url): + with httpx.Client() as client: + with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)): + client.get(url) + + +def test_build_request(server): + url = server.url.copy_with(path="/echo_headers") + headers = {"Custom-header": "value"} + + with httpx.Client() as client: + request = client.build_request("GET", url) + request.headers.update(headers) + response = client.send(request) + + assert response.status_code == 200 + assert response.url == url + + assert response.json()["Custom-header"] == "value" + + +def test_build_post_request(server): + url = server.url.copy_with(path="/echo_headers") + headers = {"Custom-header": "value"} + + with httpx.Client() as client: + request = client.build_request("POST", url) + request.headers.update(headers) + response = client.send(request) + + assert response.status_code == 200 + assert response.url == url + + assert response.json()["Content-length"] == "0" + assert response.json()["Custom-header"] == "value" + + +def test_post(server): + with httpx.Client() as client: + response = client.post(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_post_json(server): + with httpx.Client() as client: + response = client.post(server.url, json={"text": "Hello, world!"}) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_stream_response(server): + with httpx.Client() as client: + with client.stream("GET", server.url) as response: + content = response.read() + assert response.status_code == 200 + assert content == b"Hello, world!" + + +def test_stream_iterator(server): + body = b"" + + with httpx.Client() as client: + with client.stream("GET", server.url) as response: + for chunk in response.iter_bytes(): + body += chunk + + assert response.status_code == 200 + assert body == b"Hello, world!" + + +def test_raw_iterator(server): + body = b"" + + with httpx.Client() as client: + with client.stream("GET", server.url) as response: + for chunk in response.iter_raw(): + body += chunk + + assert response.status_code == 200 + assert body == b"Hello, world!" + + +def test_cannot_stream_async_request(server): + async def hello_world() -> typing.AsyncIterator[bytes]: # pragma: no cover + yield b"Hello, " + yield b"world!" + + with httpx.Client() as client: + with pytest.raises(RuntimeError): + client.post(server.url, content=hello_world()) + + +def test_raise_for_status(server): + with httpx.Client() as client: + for status_code in (200, 400, 404, 500, 505): + response = client.request( + "GET", server.url.copy_with(path=f"/status/{status_code}") + ) + if 400 <= status_code < 600: + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert exc_info.value.response == response + assert exc_info.value.request.url.path == f"/status/{status_code}" + else: + assert response.raise_for_status() is response + + +def test_options(server): + with httpx.Client() as client: + response = client.options(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_head(server): + with httpx.Client() as client: + response = client.head(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_put(server): + with httpx.Client() as client: + response = client.put(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_patch(server): + with httpx.Client() as client: + response = client.patch(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_delete(server): + with httpx.Client() as client: + response = client.delete(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_base_url(server): + base_url = server.url + with httpx.Client(base_url=base_url) as client: + response = client.get("/") + assert response.status_code == 200 + assert response.url == base_url + + +def test_merge_absolute_url(): + client = httpx.Client(base_url="https://www.example.com/") + request = client.build_request("GET", "http://www.example.com/") + assert request.url == "http://www.example.com/" + + +def test_merge_relative_url(): + client = httpx.Client(base_url="https://www.example.com/") + request = client.build_request("GET", "/testing/123") + assert request.url == "https://www.example.com/testing/123" + + +def test_merge_relative_url_with_path(): + client = httpx.Client(base_url="https://www.example.com/some/path") + request = client.build_request("GET", "/testing/123") + assert request.url == "https://www.example.com/some/path/testing/123" + + +def test_merge_relative_url_with_dotted_path(): + client = httpx.Client(base_url="https://www.example.com/some/path") + request = client.build_request("GET", "../testing/123") + assert request.url == "https://www.example.com/some/testing/123" + + +def test_merge_relative_url_with_path_including_colon(): + client = httpx.Client(base_url="https://www.example.com/some/path") + request = client.build_request("GET", "/testing:123") + assert request.url == "https://www.example.com/some/path/testing:123" + + +def test_merge_relative_url_with_encoded_slashes(): + client = httpx.Client(base_url="https://www.example.com/") + request = client.build_request("GET", "/testing%2F123") + assert request.url == "https://www.example.com/testing%2F123" + + client = httpx.Client(base_url="https://www.example.com/base%2Fpath") + request = client.build_request("GET", "/testing") + assert request.url == "https://www.example.com/base%2Fpath/testing" + + +def test_context_managed_transport(): + class Transport(httpx.BaseTransport): + def __init__(self) -> None: + self.events: list[str] = [] + + def close(self): + # The base implementation of httpx.BaseTransport just + # calls into `.close`, so simple transport cases can just override + # this method for any cleanup, where more complex cases + # might want to additionally override `__enter__`/`__exit__`. + self.events.append("transport.close") + + def __enter__(self): + super().__enter__() + self.events.append("transport.__enter__") + + def __exit__(self, *args): + super().__exit__(*args) + self.events.append("transport.__exit__") + + transport = Transport() + with httpx.Client(transport=transport): + pass + + assert transport.events == [ + "transport.__enter__", + "transport.close", + "transport.__exit__", + ] + + +def test_context_managed_transport_and_mount(): + class Transport(httpx.BaseTransport): + def __init__(self, name: str) -> None: + self.name: str = name + self.events: list[str] = [] + + def close(self): + # The base implementation of httpx.BaseTransport just + # calls into `.close`, so simple transport cases can just override + # this method for any cleanup, where more complex cases + # might want to additionally override `__enter__`/`__exit__`. + self.events.append(f"{self.name}.close") + + def __enter__(self): + super().__enter__() + self.events.append(f"{self.name}.__enter__") + + def __exit__(self, *args): + super().__exit__(*args) + self.events.append(f"{self.name}.__exit__") + + transport = Transport(name="transport") + mounted = Transport(name="mounted") + with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}): + pass + + assert transport.events == [ + "transport.__enter__", + "transport.close", + "transport.__exit__", + ] + assert mounted.events == [ + "mounted.__enter__", + "mounted.close", + "mounted.__exit__", + ] + + +def hello_world(request): + return httpx.Response(200, text="Hello, world!") + + +def test_client_closed_state_using_implicit_open(): + client = httpx.Client(transport=httpx.MockTransport(hello_world)) + + assert not client.is_closed + client.get("http://example.com") + + assert not client.is_closed + client.close() + + assert client.is_closed + + # Once we're close we cannot make any more requests. + with pytest.raises(RuntimeError): + client.get("http://example.com") + + # Once we're closed we cannot reopen the client. + with pytest.raises(RuntimeError): + with client: + pass # pragma: no cover + + +def test_client_closed_state_using_with_block(): + with httpx.Client(transport=httpx.MockTransport(hello_world)) as client: + assert not client.is_closed + client.get("http://example.com") + + assert client.is_closed + with pytest.raises(RuntimeError): + client.get("http://example.com") + + +def echo_raw_headers(request: httpx.Request) -> httpx.Response: + data = [ + (name.decode("ascii"), value.decode("ascii")) + for name, value in request.headers.raw + ] + return httpx.Response(200, json=data) + + +def test_raw_client_header(): + """ + Set a header in the Client. + """ + url = "http://example.org/echo_headers" + headers = {"Example-Header": "example-value"} + + client = httpx.Client( + transport=httpx.MockTransport(echo_raw_headers), headers=headers + ) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == [ + ["Host", "example.org"], + ["Accept", "*/*"], + ["Accept-Encoding", "gzip, deflate, br, zstd"], + ["Connection", "keep-alive"], + ["User-Agent", f"python-httpx/{httpx.__version__}"], + ["Example-Header", "example-value"], + ] + + +def unmounted(request: httpx.Request) -> httpx.Response: + data = {"app": "unmounted"} + return httpx.Response(200, json=data) + + +def mounted(request: httpx.Request) -> httpx.Response: + data = {"app": "mounted"} + return httpx.Response(200, json=data) + + +def test_mounted_transport(): + transport = httpx.MockTransport(unmounted) + mounts = {"custom://": httpx.MockTransport(mounted)} + + client = httpx.Client(transport=transport, mounts=mounts) + + response = client.get("https://www.example.com") + assert response.status_code == 200 + assert response.json() == {"app": "unmounted"} + + response = client.get("custom://www.example.com") + assert response.status_code == 200 + assert response.json() == {"app": "mounted"} + + +def test_all_mounted_transport(): + mounts = {"all://": httpx.MockTransport(mounted)} + + client = httpx.Client(mounts=mounts) + + response = client.get("https://www.example.com") + assert response.status_code == 200 + assert response.json() == {"app": "mounted"} + + +def test_server_extensions(server): + url = server.url.copy_with(path="/http_version_2") + with httpx.Client(http2=True) as client: + response = client.get(url) + assert response.status_code == 200 + assert response.extensions["http_version"] == b"HTTP/1.1" + + +def test_client_decode_text_using_autodetect(): + # Ensure that a 'default_encoding=autodetect' on the response allows for + # encoding autodetection to be used when no "Content-Type: text/plain; charset=..." + # info is present. + # + # Here we have some french text encoded with ISO-8859-1, rather than UTF-8. + text = ( + "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains " + "que la France a produits, sans excepter Voltaire lui-même, imprégné de " + "l'esprit anglais par son séjour à Londres, c'est incontestablement " + "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la " + "plus complète le fond du génie français." + ) + + def cp1252_but_no_content_type(request): + content = text.encode("ISO-8859-1") + return httpx.Response(200, content=content) + + transport = httpx.MockTransport(cp1252_but_no_content_type) + with httpx.Client(transport=transport, default_encoding=autodetect) as client: + response = client.get("http://www.example.com") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.encoding == "ISO-8859-1" + assert response.text == text + + +def test_client_decode_text_using_explicit_encoding(): + # Ensure that a 'default_encoding="..."' on the response is used for text decoding + # when no "Content-Type: text/plain; charset=..."" info is present. + # + # Here we have some french text encoded with ISO-8859-1, rather than UTF-8. + text = ( + "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains " + "que la France a produits, sans excepter Voltaire lui-même, imprégné de " + "l'esprit anglais par son séjour à Londres, c'est incontestablement " + "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la " + "plus complète le fond du génie français." + ) + + def cp1252_but_no_content_type(request): + content = text.encode("ISO-8859-1") + return httpx.Response(200, content=content) + + transport = httpx.MockTransport(cp1252_but_no_content_type) + with httpx.Client(transport=transport, default_encoding=autodetect) as client: + response = client.get("http://www.example.com") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.encoding == "ISO-8859-1" + assert response.text == text diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_cookies.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c8352593795d2e048e75dd1e697979cab6f146 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_cookies.py @@ -0,0 +1,168 @@ +from http.cookiejar import Cookie, CookieJar + +import pytest + +import httpx + + +def get_and_set_cookies(request: httpx.Request) -> httpx.Response: + if request.url.path == "/echo_cookies": + data = {"cookies": request.headers.get("cookie")} + return httpx.Response(200, json=data) + elif request.url.path == "/set_cookie": + return httpx.Response(200, headers={"set-cookie": "example-name=example-value"}) + else: + raise NotImplementedError() # pragma: no cover + + +def test_set_cookie() -> None: + """ + Send a request including a cookie. + """ + url = "http://example.org/echo_cookies" + cookies = {"example-name": "example-value"} + + client = httpx.Client( + cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies) + ) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} + + +def test_set_per_request_cookie_is_deprecated() -> None: + """ + Sending a request including a per-request cookie is deprecated. + """ + url = "http://example.org/echo_cookies" + cookies = {"example-name": "example-value"} + + client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies)) + with pytest.warns(DeprecationWarning): + response = client.get(url, cookies=cookies) + + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} + + +def test_set_cookie_with_cookiejar() -> None: + """ + Send a request including a cookie, using a `CookieJar` instance. + """ + + url = "http://example.org/echo_cookies" + cookies = CookieJar() + cookie = Cookie( + version=0, + name="example-name", + value="example-value", + port=None, + port_specified=False, + domain="", + domain_specified=False, + domain_initial_dot=False, + path="/", + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={"HttpOnly": ""}, + rfc2109=False, + ) + cookies.set_cookie(cookie) + + client = httpx.Client( + cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies) + ) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} + + +def test_setting_client_cookies_to_cookiejar() -> None: + """ + Send a request including a cookie, using a `CookieJar` instance. + """ + + url = "http://example.org/echo_cookies" + cookies = CookieJar() + cookie = Cookie( + version=0, + name="example-name", + value="example-value", + port=None, + port_specified=False, + domain="", + domain_specified=False, + domain_initial_dot=False, + path="/", + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={"HttpOnly": ""}, + rfc2109=False, + ) + cookies.set_cookie(cookie) + + client = httpx.Client( + cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies) + ) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} + + +def test_set_cookie_with_cookies_model() -> None: + """ + Send a request including a cookie, using a `Cookies` instance. + """ + + url = "http://example.org/echo_cookies" + cookies = httpx.Cookies() + cookies["example-name"] = "example-value" + + client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies)) + client.cookies = cookies + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} + + +def test_get_cookie() -> None: + url = "http://example.org/set_cookie" + + client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies)) + response = client.get(url) + + assert response.status_code == 200 + assert response.cookies["example-name"] == "example-value" + assert client.cookies["example-name"] == "example-value" + + +def test_cookie_persistence() -> None: + """ + Ensure that Client instances persist cookies between requests. + """ + client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies)) + + response = client.get("http://example.org/echo_cookies") + assert response.status_code == 200 + assert response.json() == {"cookies": None} + + response = client.get("http://example.org/set_cookie") + assert response.status_code == 200 + assert response.cookies["example-name"] == "example-value" + assert client.cookies["example-name"] == "example-value" + + response = client.get("http://example.org/echo_cookies") + assert response.status_code == 200 + assert response.json() == {"cookies": "example-name=example-value"} diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_event_hooks.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_event_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..78fb0484e67783fd3844c059d01203a8e579eefd --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_event_hooks.py @@ -0,0 +1,228 @@ +import pytest + +import httpx + + +def app(request: httpx.Request) -> httpx.Response: + if request.url.path == "/redirect": + return httpx.Response(303, headers={"server": "testserver", "location": "/"}) + elif request.url.path.startswith("/status/"): + status_code = int(request.url.path[-3:]) + return httpx.Response(status_code, headers={"server": "testserver"}) + + return httpx.Response(200, headers={"server": "testserver"}) + + +def test_event_hooks(): + events = [] + + def on_request(request): + events.append({"event": "request", "headers": dict(request.headers)}) + + def on_response(response): + events.append({"event": "response", "headers": dict(response.headers)}) + + event_hooks = {"request": [on_request], "response": [on_response]} + + with httpx.Client( + event_hooks=event_hooks, transport=httpx.MockTransport(app) + ) as http: + http.get("http://127.0.0.1:8000/", auth=("username", "password")) + + assert events == [ + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"server": "testserver"}, + }, + ] + + +def test_event_hooks_raising_exception(server): + def raise_on_4xx_5xx(response): + response.raise_for_status() + + event_hooks = {"response": [raise_on_4xx_5xx]} + + with httpx.Client( + event_hooks=event_hooks, transport=httpx.MockTransport(app) + ) as http: + try: + http.get("http://127.0.0.1:8000/status/400") + except httpx.HTTPStatusError as exc: + assert exc.response.is_closed + + +@pytest.mark.anyio +async def test_async_event_hooks(): + events = [] + + async def on_request(request): + events.append({"event": "request", "headers": dict(request.headers)}) + + async def on_response(response): + events.append({"event": "response", "headers": dict(response.headers)}) + + event_hooks = {"request": [on_request], "response": [on_response]} + + async with httpx.AsyncClient( + event_hooks=event_hooks, transport=httpx.MockTransport(app) + ) as http: + await http.get("http://127.0.0.1:8000/", auth=("username", "password")) + + assert events == [ + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"server": "testserver"}, + }, + ] + + +@pytest.mark.anyio +async def test_async_event_hooks_raising_exception(): + async def raise_on_4xx_5xx(response): + response.raise_for_status() + + event_hooks = {"response": [raise_on_4xx_5xx]} + + async with httpx.AsyncClient( + event_hooks=event_hooks, transport=httpx.MockTransport(app) + ) as http: + try: + await http.get("http://127.0.0.1:8000/status/400") + except httpx.HTTPStatusError as exc: + assert exc.response.is_closed + + +def test_event_hooks_with_redirect(): + """ + A redirect request should trigger additional 'request' and 'response' event hooks. + """ + + events = [] + + def on_request(request): + events.append({"event": "request", "headers": dict(request.headers)}) + + def on_response(response): + events.append({"event": "response", "headers": dict(response.headers)}) + + event_hooks = {"request": [on_request], "response": [on_response]} + + with httpx.Client( + event_hooks=event_hooks, + transport=httpx.MockTransport(app), + follow_redirects=True, + ) as http: + http.get("http://127.0.0.1:8000/redirect", auth=("username", "password")) + + assert events == [ + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"location": "/", "server": "testserver"}, + }, + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"server": "testserver"}, + }, + ] + + +@pytest.mark.anyio +async def test_async_event_hooks_with_redirect(): + """ + A redirect request should trigger additional 'request' and 'response' event hooks. + """ + + events = [] + + async def on_request(request): + events.append({"event": "request", "headers": dict(request.headers)}) + + async def on_response(response): + events.append({"event": "response", "headers": dict(response.headers)}) + + event_hooks = {"request": [on_request], "response": [on_response]} + + async with httpx.AsyncClient( + event_hooks=event_hooks, + transport=httpx.MockTransport(app), + follow_redirects=True, + ) as http: + await http.get("http://127.0.0.1:8000/redirect", auth=("username", "password")) + + assert events == [ + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"location": "/", "server": "testserver"}, + }, + { + "event": "request", + "headers": { + "host": "127.0.0.1:8000", + "user-agent": f"python-httpx/{httpx.__version__}", + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + }, + { + "event": "response", + "headers": {"server": "testserver"}, + }, + ] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_headers.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..47f5a4d7317b08891214b2d64194a37b0a950e16 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_headers.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 + +import pytest + +import httpx + + +def echo_headers(request: httpx.Request) -> httpx.Response: + data = {"headers": dict(request.headers)} + return httpx.Response(200, json=data) + + +def echo_repeated_headers_multi_items(request: httpx.Request) -> httpx.Response: + data = {"headers": list(request.headers.multi_items())} + return httpx.Response(200, json=data) + + +def echo_repeated_headers_items(request: httpx.Request) -> httpx.Response: + data = {"headers": list(request.headers.items())} + return httpx.Response(200, json=data) + + +def test_client_header(): + """ + Set a header in the Client. + """ + url = "http://example.org/echo_headers" + headers = {"Example-Header": "example-value"} + + client = httpx.Client(transport=httpx.MockTransport(echo_headers), headers=headers) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "example-header": "example-value", + "host": "example.org", + "user-agent": f"python-httpx/{httpx.__version__}", + } + } + + +def test_header_merge(): + url = "http://example.org/echo_headers" + client_headers = {"User-Agent": "python-myclient/0.2.1"} + request_headers = {"X-Auth-Token": "FooBarBazToken"} + client = httpx.Client( + transport=httpx.MockTransport(echo_headers), headers=client_headers + ) + response = client.get(url, headers=request_headers) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org", + "user-agent": "python-myclient/0.2.1", + "x-auth-token": "FooBarBazToken", + } + } + + +def test_header_merge_conflicting_headers(): + url = "http://example.org/echo_headers" + client_headers = {"X-Auth-Token": "FooBar"} + request_headers = {"X-Auth-Token": "BazToken"} + client = httpx.Client( + transport=httpx.MockTransport(echo_headers), headers=client_headers + ) + response = client.get(url, headers=request_headers) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org", + "user-agent": f"python-httpx/{httpx.__version__}", + "x-auth-token": "BazToken", + } + } + + +def test_header_update(): + url = "http://example.org/echo_headers" + client = httpx.Client(transport=httpx.MockTransport(echo_headers)) + first_response = client.get(url) + client.headers.update( + {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"} + ) + second_response = client.get(url) + + assert first_response.status_code == 200 + assert first_response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org", + "user-agent": f"python-httpx/{httpx.__version__}", + } + } + + assert second_response.status_code == 200 + assert second_response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "another-header": "AThing", + "connection": "keep-alive", + "host": "example.org", + "user-agent": "python-myclient/0.2.1", + } + } + + +def test_header_repeated_items(): + url = "http://example.org/echo_headers" + client = httpx.Client(transport=httpx.MockTransport(echo_repeated_headers_items)) + response = client.get(url, headers=[("x-header", "1"), ("x-header", "2,3")]) + + assert response.status_code == 200 + + echoed_headers = response.json()["headers"] + # as per RFC 7230, the whitespace after a comma is insignificant + # so we split and strip here so that we can do a safe comparison + assert ["x-header", ["1", "2", "3"]] in [ + [k, [subv.lstrip() for subv in v.split(",")]] for k, v in echoed_headers + ] + + +def test_header_repeated_multi_items(): + url = "http://example.org/echo_headers" + client = httpx.Client( + transport=httpx.MockTransport(echo_repeated_headers_multi_items) + ) + response = client.get(url, headers=[("x-header", "1"), ("x-header", "2,3")]) + + assert response.status_code == 200 + + echoed_headers = response.json()["headers"] + assert ["x-header", "1"] in echoed_headers + assert ["x-header", "2,3"] in echoed_headers + + +def test_remove_default_header(): + """ + Remove a default header from the Client. + """ + url = "http://example.org/echo_headers" + + client = httpx.Client(transport=httpx.MockTransport(echo_headers)) + del client.headers["User-Agent"] + + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org", + } + } + + +def test_header_does_not_exist(): + headers = httpx.Headers({"foo": "bar"}) + with pytest.raises(KeyError): + del headers["baz"] + + +def test_header_with_incorrect_value(): + with pytest.raises( + TypeError, + match=f"Header value must be str or bytes, not {type(None)}", + ): + httpx.Headers({"foo": None}) # type: ignore + + +def test_host_with_auth_and_port_in_url(): + """ + The Host header should only include the hostname, or hostname:port + (for non-default ports only). Any userinfo or default port should not + be present. + """ + url = "http://username:password@example.org:80/echo_headers" + + client = httpx.Client(transport=httpx.MockTransport(echo_headers)) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org", + "user-agent": f"python-httpx/{httpx.__version__}", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + } + } + + +def test_host_with_non_default_port_in_url(): + """ + If the URL includes a non-default port, then it should be included in + the Host header. + """ + url = "http://username:password@example.org:123/echo_headers" + + client = httpx.Client(transport=httpx.MockTransport(echo_headers)) + response = client.get(url) + + assert response.status_code == 200 + assert response.json() == { + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br, zstd", + "connection": "keep-alive", + "host": "example.org:123", + "user-agent": f"python-httpx/{httpx.__version__}", + "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + } + } + + +def test_request_auto_headers(): + request = httpx.Request("GET", "https://www.example.org/") + assert "host" in request.headers + + +def test_same_origin(): + origin = httpx.URL("https://example.com") + request = httpx.Request("GET", "HTTPS://EXAMPLE.COM:443") + + client = httpx.Client() + headers = client._redirect_headers(request, origin, "GET") + + assert headers["Host"] == request.url.netloc.decode("ascii") + + +def test_not_same_origin(): + origin = httpx.URL("https://example.com") + request = httpx.Request("GET", "HTTP://EXAMPLE.COM:80") + + client = httpx.Client() + headers = client._redirect_headers(request, origin, "GET") + + assert headers["Host"] == origin.netloc.decode("ascii") + + +def test_is_https_redirect(): + url = httpx.URL("https://example.com") + request = httpx.Request( + "GET", "http://example.com", headers={"Authorization": "empty"} + ) + + client = httpx.Client() + headers = client._redirect_headers(request, url, "GET") + + assert "Authorization" in headers + + +def test_is_not_https_redirect(): + url = httpx.URL("https://www.example.com") + request = httpx.Request( + "GET", "http://example.com", headers={"Authorization": "empty"} + ) + + client = httpx.Client() + headers = client._redirect_headers(request, url, "GET") + + assert "Authorization" not in headers + + +def test_is_not_https_redirect_if_not_default_ports(): + url = httpx.URL("https://example.com:1337") + request = httpx.Request( + "GET", "http://example.com:9999", headers={"Authorization": "empty"} + ) + + client = httpx.Client() + headers = client._redirect_headers(request, url, "GET") + + assert "Authorization" not in headers diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_properties.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8709813b706a005eff0fef19e0f1539af0d0cc --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_properties.py @@ -0,0 +1,68 @@ +import httpx + + +def test_client_base_url(): + client = httpx.Client() + client.base_url = "https://www.example.org/" # type: ignore + assert isinstance(client.base_url, httpx.URL) + assert client.base_url == "https://www.example.org/" + + +def test_client_base_url_without_trailing_slash(): + client = httpx.Client() + client.base_url = "https://www.example.org/path" # type: ignore + assert isinstance(client.base_url, httpx.URL) + assert client.base_url == "https://www.example.org/path/" + + +def test_client_base_url_with_trailing_slash(): + client = httpx.Client() + client.base_url = "https://www.example.org/path/" # type: ignore + assert isinstance(client.base_url, httpx.URL) + assert client.base_url == "https://www.example.org/path/" + + +def test_client_headers(): + client = httpx.Client() + client.headers = {"a": "b"} # type: ignore + assert isinstance(client.headers, httpx.Headers) + assert client.headers["A"] == "b" + + +def test_client_cookies(): + client = httpx.Client() + client.cookies = {"a": "b"} # type: ignore + assert isinstance(client.cookies, httpx.Cookies) + mycookies = list(client.cookies.jar) + assert len(mycookies) == 1 + assert mycookies[0].name == "a" and mycookies[0].value == "b" + + +def test_client_timeout(): + expected_timeout = 12.0 + client = httpx.Client() + + client.timeout = expected_timeout # type: ignore + + assert isinstance(client.timeout, httpx.Timeout) + assert client.timeout.connect == expected_timeout + assert client.timeout.read == expected_timeout + assert client.timeout.write == expected_timeout + assert client.timeout.pool == expected_timeout + + +def test_client_event_hooks(): + def on_request(request): + pass # pragma: no cover + + client = httpx.Client() + client.event_hooks = {"request": [on_request]} + assert client.event_hooks == {"request": [on_request], "response": []} + + +def test_client_trust_env(): + client = httpx.Client() + assert client.trust_env + + client = httpx.Client(trust_env=False) + assert not client.trust_env diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_proxies.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_proxies.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4090dcecb3e805041ec23738d441e2c23e8c23 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_proxies.py @@ -0,0 +1,265 @@ +import httpcore +import pytest + +import httpx + + +def url_to_origin(url: str) -> httpcore.URL: + """ + Given a URL string, return the origin in the raw tuple format that + `httpcore` uses for it's representation. + """ + u = httpx.URL(url) + return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/") + + +def test_socks_proxy(): + url = httpx.URL("http://www.example.com") + + for proxy in ("socks5://localhost/", "socks5h://localhost/"): + client = httpx.Client(proxy=proxy) + transport = client._transport_for_url(url) + assert isinstance(transport, httpx.HTTPTransport) + assert isinstance(transport._pool, httpcore.SOCKSProxy) + + async_client = httpx.AsyncClient(proxy=proxy) + async_transport = async_client._transport_for_url(url) + assert isinstance(async_transport, httpx.AsyncHTTPTransport) + assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy) + + +PROXY_URL = "http://[::1]" + + +@pytest.mark.parametrize( + ["url", "proxies", "expected"], + [ + ("http://example.com", {}, None), + ("http://example.com", {"https://": PROXY_URL}, None), + ("http://example.com", {"http://example.net": PROXY_URL}, None), + # Using "*" should match any domain name. + ("http://example.com", {"http://*": PROXY_URL}, PROXY_URL), + ("https://example.com", {"http://*": PROXY_URL}, None), + # Using "example.com" should match example.com, but not www.example.com + ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL), + ("http://www.example.com", {"http://example.com": PROXY_URL}, None), + # Using "*.example.com" should match www.example.com, but not example.com + ("http://example.com", {"http://*.example.com": PROXY_URL}, None), + ("http://www.example.com", {"http://*.example.com": PROXY_URL}, PROXY_URL), + # Using "*example.com" should match example.com and www.example.com + ("http://example.com", {"http://*example.com": PROXY_URL}, PROXY_URL), + ("http://www.example.com", {"http://*example.com": PROXY_URL}, PROXY_URL), + ("http://wwwexample.com", {"http://*example.com": PROXY_URL}, None), + # ... + ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL), + ("http://example.com", {"all://": PROXY_URL}, PROXY_URL), + ("http://example.com", {"http://": PROXY_URL}, PROXY_URL), + ("http://example.com", {"all://example.com": PROXY_URL}, PROXY_URL), + ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL), + ("http://example.com", {"http://example.com:80": PROXY_URL}, PROXY_URL), + ("http://example.com:8080", {"http://example.com:8080": PROXY_URL}, PROXY_URL), + ("http://example.com:8080", {"http://example.com": PROXY_URL}, PROXY_URL), + ( + "http://example.com", + { + "all://": PROXY_URL + ":1", + "http://": PROXY_URL + ":2", + "all://example.com": PROXY_URL + ":3", + "http://example.com": PROXY_URL + ":4", + }, + PROXY_URL + ":4", + ), + ( + "http://example.com", + { + "all://": PROXY_URL + ":1", + "http://": PROXY_URL + ":2", + "all://example.com": PROXY_URL + ":3", + }, + PROXY_URL + ":3", + ), + ( + "http://example.com", + {"all://": PROXY_URL + ":1", "http://": PROXY_URL + ":2"}, + PROXY_URL + ":2", + ), + ], +) +def test_transport_for_request(url, proxies, expected): + mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()} + client = httpx.Client(mounts=mounts) + + transport = client._transport_for_url(httpx.URL(url)) + + if expected is None: + assert transport is client._transport + else: + assert isinstance(transport, httpx.HTTPTransport) + assert isinstance(transport._pool, httpcore.HTTPProxy) + assert transport._pool._proxy_url == url_to_origin(expected) + + +@pytest.mark.anyio +@pytest.mark.network +async def test_async_proxy_close(): + try: + transport = httpx.AsyncHTTPTransport(proxy=PROXY_URL) + client = httpx.AsyncClient(mounts={"https://": transport}) + await client.get("http://example.com") + finally: + await client.aclose() + + +@pytest.mark.network +def test_sync_proxy_close(): + try: + transport = httpx.HTTPTransport(proxy=PROXY_URL) + client = httpx.Client(mounts={"https://": transport}) + client.get("http://example.com") + finally: + client.close() + + +def test_unsupported_proxy_scheme(): + with pytest.raises(ValueError): + httpx.Client(proxy="ftp://127.0.0.1") + + +@pytest.mark.parametrize( + ["url", "env", "expected"], + [ + ("http://google.com", {}, None), + ( + "http://google.com", + {"HTTP_PROXY": "http://example.com"}, + "http://example.com", + ), + # Auto prepend http scheme + ("http://google.com", {"HTTP_PROXY": "example.com"}, "http://example.com"), + ( + "http://google.com", + {"HTTP_PROXY": "http://example.com", "NO_PROXY": "google.com"}, + None, + ), + # Everything proxied when NO_PROXY is empty/unset + ( + "http://127.0.0.1", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ""}, + "http://localhost:123", + ), + # Not proxied if NO_PROXY matches URL. + ( + "http://127.0.0.1", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "127.0.0.1"}, + None, + ), + # Proxied if NO_PROXY scheme does not match URL. + ( + "http://127.0.0.1", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "https://127.0.0.1"}, + "http://localhost:123", + ), + # Proxied if NO_PROXY scheme does not match host. + ( + "http://127.0.0.1", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "1.1.1.1"}, + "http://localhost:123", + ), + # Not proxied if NO_PROXY matches host domain suffix. + ( + "http://courses.mit.edu", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"}, + None, + ), + # Proxied even though NO_PROXY matches host domain *prefix*. + ( + "https://mit.edu.info", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"}, + "http://localhost:123", + ), + # Not proxied if one item in NO_PROXY case matches host domain suffix. + ( + "https://mit.edu.info", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,edu.info"}, + None, + ), + # Not proxied if one item in NO_PROXY case matches host domain suffix. + # May include whitespace. + ( + "https://mit.edu.info", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu, edu.info"}, + None, + ), + # Proxied if no items in NO_PROXY match. + ( + "https://mit.edu.info", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,mit.info"}, + "http://localhost:123", + ), + # Proxied if NO_PROXY domain doesn't match. + ( + "https://foo.example.com", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "www.example.com"}, + "http://localhost:123", + ), + # Not proxied for subdomains matching NO_PROXY, with a leading ".". + ( + "https://www.example1.com", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ".example1.com"}, + None, + ), + # Proxied, because NO_PROXY subdomains only match if "." separated. + ( + "https://www.example2.com", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "ample2.com"}, + "http://localhost:123", + ), + # No requests are proxied if NO_PROXY="*" is set. + ( + "https://www.example3.com", + {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"}, + None, + ), + ], +) +@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient]) +def test_proxies_environ(monkeypatch, client_class, url, env, expected): + for name, value in env.items(): + monkeypatch.setenv(name, value) + + client = client_class() + transport = client._transport_for_url(httpx.URL(url)) + + if expected is None: + assert transport == client._transport + else: + assert transport._pool._proxy_url == url_to_origin(expected) + + +@pytest.mark.parametrize( + ["proxies", "is_valid"], + [ + ({"http": "http://127.0.0.1"}, False), + ({"https": "http://127.0.0.1"}, False), + ({"all": "http://127.0.0.1"}, False), + ({"http://": "http://127.0.0.1"}, True), + ({"https://": "http://127.0.0.1"}, True), + ({"all://": "http://127.0.0.1"}, True), + ], +) +def test_for_deprecated_proxy_params(proxies, is_valid): + mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()} + + if not is_valid: + with pytest.raises(ValueError): + httpx.Client(mounts=mounts) + else: + httpx.Client(mounts=mounts) + + +def test_proxy_with_mounts(): + proxy_transport = httpx.HTTPTransport(proxy="http://127.0.0.1") + client = httpx.Client(mounts={"http://": proxy_transport}) + + transport = client._transport_for_url(httpx.URL("http://example.com")) + assert transport == proxy_transport diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_queryparams.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_queryparams.py new file mode 100644 index 0000000000000000000000000000000000000000..e5acb0ba20b39182b841f9549467d7b2012ac064 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_queryparams.py @@ -0,0 +1,35 @@ +import httpx + + +def hello_world(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, text="Hello, world") + + +def test_client_queryparams(): + client = httpx.Client(params={"a": "b"}) + assert isinstance(client.params, httpx.QueryParams) + assert client.params["a"] == "b" + + +def test_client_queryparams_string(): + client = httpx.Client(params="a=b") + assert isinstance(client.params, httpx.QueryParams) + assert client.params["a"] == "b" + + client = httpx.Client() + client.params = "a=b" # type: ignore + assert isinstance(client.params, httpx.QueryParams) + assert client.params["a"] == "b" + + +def test_client_queryparams_echo(): + url = "http://example.org/echo_queryparams" + client_queryparams = "first=str" + request_queryparams = {"second": "dict"} + client = httpx.Client( + transport=httpx.MockTransport(hello_world), params=client_queryparams + ) + response = client.get(url, params=request_queryparams) + + assert response.status_code == 200 + assert response.url == "http://example.org/echo_queryparams?first=str&second=dict" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_redirects.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_redirects.py new file mode 100644 index 0000000000000000000000000000000000000000..f65827134c6e0c5426f678bba8cc546fcab14652 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/client/test_redirects.py @@ -0,0 +1,447 @@ +import typing + +import pytest + +import httpx + + +def redirects(request: httpx.Request) -> httpx.Response: + if request.url.scheme not in ("http", "https"): + raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.") + + if request.url.path == "/redirect_301": + status_code = httpx.codes.MOVED_PERMANENTLY + content = b"here" + headers = {"location": "https://example.org/"} + return httpx.Response(status_code, headers=headers, content=content) + + elif request.url.path == "/redirect_302": + status_code = httpx.codes.FOUND + headers = {"location": "https://example.org/"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/redirect_303": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "https://example.org/"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/relative_redirect": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "/"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/malformed_redirect": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "https://:443/"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/invalid_redirect": + status_code = httpx.codes.SEE_OTHER + raw_headers = [(b"location", "https://😇/".encode("utf-8"))] + return httpx.Response(status_code, headers=raw_headers) + + elif request.url.path == "/no_scheme_redirect": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "//example.org/"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/multiple_redirects": + params = httpx.QueryParams(request.url.query) + count = int(params.get("count", "0")) + redirect_count = count - 1 + status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK + if count: + location = "/multiple_redirects" + if redirect_count: + location += f"?count={redirect_count}" + headers = {"location": location} + else: + headers = {} + return httpx.Response(status_code, headers=headers) + + if request.url.path == "/redirect_loop": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "/redirect_loop"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/cross_domain": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "https://example.org/cross_domain_target"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/cross_domain_target": + status_code = httpx.codes.OK + data = { + "body": request.content.decode("ascii"), + "headers": dict(request.headers), + } + return httpx.Response(status_code, json=data) + + elif request.url.path == "/redirect_body": + status_code = httpx.codes.PERMANENT_REDIRECT + headers = {"location": "/redirect_body_target"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/redirect_no_body": + status_code = httpx.codes.SEE_OTHER + headers = {"location": "/redirect_body_target"} + return httpx.Response(status_code, headers=headers) + + elif request.url.path == "/redirect_body_target": + data = { + "body": request.content.decode("ascii"), + "headers": dict(request.headers), + } + return httpx.Response(200, json=data) + + elif request.url.path == "/cross_subdomain": + if request.headers["Host"] != "www.example.org": + status_code = httpx.codes.PERMANENT_REDIRECT + headers = {"location": "https://www.example.org/cross_subdomain"} + return httpx.Response(status_code, headers=headers) + else: + return httpx.Response(200, text="Hello, world!") + + elif request.url.path == "/redirect_custom_scheme": + status_code = httpx.codes.MOVED_PERMANENTLY + headers = {"location": "market://details?id=42"} + return httpx.Response(status_code, headers=headers) + + if request.method == "HEAD": + return httpx.Response(200) + + return httpx.Response(200, html="Hello, world!") + + +def test_redirect_301(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.post("https://example.org/redirect_301", follow_redirects=True) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert len(response.history) == 1 + + +def test_redirect_302(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.post("https://example.org/redirect_302", follow_redirects=True) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert len(response.history) == 1 + + +def test_redirect_303(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get("https://example.org/redirect_303", follow_redirects=True) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert len(response.history) == 1 + + +def test_next_request(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + request = client.build_request("POST", "https://example.org/redirect_303") + response = client.send(request, follow_redirects=False) + assert response.status_code == httpx.codes.SEE_OTHER + assert response.url == "https://example.org/redirect_303" + assert response.next_request is not None + + response = client.send(response.next_request, follow_redirects=False) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert response.next_request is None + + +@pytest.mark.anyio +async def test_async_next_request(): + async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client: + request = client.build_request("POST", "https://example.org/redirect_303") + response = await client.send(request, follow_redirects=False) + assert response.status_code == httpx.codes.SEE_OTHER + assert response.url == "https://example.org/redirect_303" + assert response.next_request is not None + + response = await client.send(response.next_request, follow_redirects=False) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert response.next_request is None + + +def test_head_redirect(): + """ + Contrary to Requests, redirects remain enabled by default for HEAD requests. + """ + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.head("https://example.org/redirect_302", follow_redirects=True) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert response.request.method == "HEAD" + assert len(response.history) == 1 + assert response.text == "" + + +def test_relative_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get( + "https://example.org/relative_redirect", follow_redirects=True + ) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert len(response.history) == 1 + + +def test_malformed_redirect(): + # https://github.com/encode/httpx/issues/771 + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get( + "http://example.org/malformed_redirect", follow_redirects=True + ) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org:443/" + assert len(response.history) == 1 + + +def test_invalid_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + with pytest.raises(httpx.RemoteProtocolError): + client.get("http://example.org/invalid_redirect", follow_redirects=True) + + +def test_no_scheme_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get( + "https://example.org/no_scheme_redirect", follow_redirects=True + ) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/" + assert len(response.history) == 1 + + +def test_fragment_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get( + "https://example.org/relative_redirect#fragment", follow_redirects=True + ) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/#fragment" + assert len(response.history) == 1 + + +def test_multiple_redirects(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + response = client.get( + "https://example.org/multiple_redirects?count=20", follow_redirects=True + ) + assert response.status_code == httpx.codes.OK + assert response.url == "https://example.org/multiple_redirects" + assert len(response.history) == 20 + assert response.history[0].url == "https://example.org/multiple_redirects?count=20" + assert response.history[1].url == "https://example.org/multiple_redirects?count=19" + assert len(response.history[0].history) == 0 + assert len(response.history[1].history) == 1 + + +@pytest.mark.anyio +async def test_async_too_many_redirects(): + async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client: + with pytest.raises(httpx.TooManyRedirects): + await client.get( + "https://example.org/multiple_redirects?count=21", follow_redirects=True + ) + + +def test_sync_too_many_redirects(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + with pytest.raises(httpx.TooManyRedirects): + client.get( + "https://example.org/multiple_redirects?count=21", follow_redirects=True + ) + + +def test_redirect_loop(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + with pytest.raises(httpx.TooManyRedirects): + client.get("https://example.org/redirect_loop", follow_redirects=True) + + +def test_cross_domain_redirect_with_auth_header(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.com/cross_domain" + headers = {"Authorization": "abc"} + response = client.get(url, headers=headers, follow_redirects=True) + assert response.url == "https://example.org/cross_domain_target" + assert "authorization" not in response.json()["headers"] + + +def test_cross_domain_https_redirect_with_auth_header(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "http://example.com/cross_domain" + headers = {"Authorization": "abc"} + response = client.get(url, headers=headers, follow_redirects=True) + assert response.url == "https://example.org/cross_domain_target" + assert "authorization" not in response.json()["headers"] + + +def test_cross_domain_redirect_with_auth(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.com/cross_domain" + response = client.get(url, auth=("user", "pass"), follow_redirects=True) + assert response.url == "https://example.org/cross_domain_target" + assert "authorization" not in response.json()["headers"] + + +def test_same_domain_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.org/cross_domain" + headers = {"Authorization": "abc"} + response = client.get(url, headers=headers, follow_redirects=True) + assert response.url == "https://example.org/cross_domain_target" + assert response.json()["headers"]["authorization"] == "abc" + + +def test_same_domain_https_redirect_with_auth_header(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "http://example.org/cross_domain" + headers = {"Authorization": "abc"} + response = client.get(url, headers=headers, follow_redirects=True) + assert response.url == "https://example.org/cross_domain_target" + assert response.json()["headers"]["authorization"] == "abc" + + +def test_body_redirect(): + """ + A 308 redirect should preserve the request body. + """ + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.org/redirect_body" + content = b"Example request body" + response = client.post(url, content=content, follow_redirects=True) + assert response.url == "https://example.org/redirect_body_target" + assert response.json()["body"] == "Example request body" + assert "content-length" in response.json()["headers"] + + +def test_no_body_redirect(): + """ + A 303 redirect should remove the request body. + """ + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.org/redirect_no_body" + content = b"Example request body" + response = client.post(url, content=content, follow_redirects=True) + assert response.url == "https://example.org/redirect_body_target" + assert response.json()["body"] == "" + assert "content-length" not in response.json()["headers"] + + +def test_can_stream_if_no_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.org/redirect_301" + with client.stream("GET", url, follow_redirects=False) as response: + pass + assert response.status_code == httpx.codes.MOVED_PERMANENTLY + assert response.headers["location"] == "https://example.org/" + + +class ConsumeBodyTransport(httpx.MockTransport): + def handle_request(self, request: httpx.Request) -> httpx.Response: + assert isinstance(request.stream, httpx.SyncByteStream) + list(request.stream) + return self.handler(request) # type: ignore[return-value] + + +def test_cannot_redirect_streaming_body(): + client = httpx.Client(transport=ConsumeBodyTransport(redirects)) + url = "https://example.org/redirect_body" + + def streaming_body() -> typing.Iterator[bytes]: + yield b"Example request body" # pragma: no cover + + with pytest.raises(httpx.StreamConsumed): + client.post(url, content=streaming_body(), follow_redirects=True) + + +def test_cross_subdomain_redirect(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + url = "https://example.com/cross_subdomain" + response = client.get(url, follow_redirects=True) + assert response.url == "https://www.example.org/cross_subdomain" + + +def cookie_sessions(request: httpx.Request) -> httpx.Response: + if request.url.path == "/": + cookie = request.headers.get("Cookie") + if cookie is not None: + content = b"Logged in" + else: + content = b"Not logged in" + return httpx.Response(200, content=content) + + elif request.url.path == "/login": + status_code = httpx.codes.SEE_OTHER + headers = { + "location": "/", + "set-cookie": ( + "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; " + "httponly; samesite=lax" + ), + } + return httpx.Response(status_code, headers=headers) + + else: + assert request.url.path == "/logout" + status_code = httpx.codes.SEE_OTHER + headers = { + "location": "/", + "set-cookie": ( + "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; " + "httponly; samesite=lax" + ), + } + return httpx.Response(status_code, headers=headers) + + +def test_redirect_cookie_behavior(): + client = httpx.Client( + transport=httpx.MockTransport(cookie_sessions), follow_redirects=True + ) + + # The client is not logged in. + response = client.get("https://example.com/") + assert response.url == "https://example.com/" + assert response.text == "Not logged in" + + # Login redirects to the homepage, setting a session cookie. + response = client.post("https://example.com/login") + assert response.url == "https://example.com/" + assert response.text == "Logged in" + + # The client is logged in. + response = client.get("https://example.com/") + assert response.url == "https://example.com/" + assert response.text == "Logged in" + + # Logout redirects to the homepage, expiring the session cookie. + response = client.post("https://example.com/logout") + assert response.url == "https://example.com/" + assert response.text == "Not logged in" + + # The client is not logged in. + response = client.get("https://example.com/") + assert response.url == "https://example.com/" + assert response.text == "Not logged in" + + +def test_redirect_custom_scheme(): + client = httpx.Client(transport=httpx.MockTransport(redirects)) + with pytest.raises(httpx.UnsupportedProtocol) as e: + client.post("https://example.org/redirect_custom_scheme", follow_redirects=True) + assert str(e.value) == "Scheme 'market' not supported." + + +@pytest.mark.anyio +async def test_async_invalid_redirect(): + async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client: + with pytest.raises(httpx.RemoteProtocolError): + await client.get( + "http://example.org/invalid_redirect", follow_redirects=True + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/common.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..064c25a64559e688ade1467cd70446bd1923f237 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/common.py @@ -0,0 +1,4 @@ +import pathlib + +TESTS_DIR = pathlib.Path(__file__).parent +FIXTURES_DIR = TESTS_DIR / "fixtures" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/concurrency.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ed55829af9f5e1af05a3d72158ef6549e3ceb5 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/concurrency.py @@ -0,0 +1,15 @@ +""" +Async environment-agnostic concurrency utilities that are only used in tests. +""" + +import asyncio + +import sniffio +import trio + + +async def sleep(seconds: float) -> None: + if sniffio.current_async_library() == "trio": + await trio.sleep(seconds) # pragma: no cover + else: + await asyncio.sleep(seconds) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/conftest.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..858bca13978b88aaf14b80e4f948e7c701ec73fe --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/conftest.py @@ -0,0 +1,287 @@ +import asyncio +import json +import os +import threading +import time +import typing + +import pytest +import trustme +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.serialization import ( + BestAvailableEncryption, + Encoding, + PrivateFormat, + load_pem_private_key, +) +from uvicorn.config import Config +from uvicorn.server import Server + +import httpx +from tests.concurrency import sleep + +ENVIRONMENT_VARIABLES = { + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "NO_PROXY", + "SSLKEYLOGFILE", +} + + +@pytest.fixture(scope="function", autouse=True) +def clean_environ(): + """Keeps os.environ clean for every test without having to mock os.environ""" + original_environ = os.environ.copy() + os.environ.clear() + os.environ.update( + { + k: v + for k, v in original_environ.items() + if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES + } + ) + yield + os.environ.clear() + os.environ.update(original_environ) + + +Message = typing.Dict[str, typing.Any] +Receive = typing.Callable[[], typing.Awaitable[Message]] +Send = typing.Callable[ + [typing.Dict[str, typing.Any]], typing.Coroutine[None, None, None] +] +Scope = typing.Dict[str, typing.Any] + + +async def app(scope: Scope, receive: Receive, send: Send) -> None: + assert scope["type"] == "http" + if scope["path"].startswith("/slow_response"): + await slow_response(scope, receive, send) + elif scope["path"].startswith("/status"): + await status_code(scope, receive, send) + elif scope["path"].startswith("/echo_body"): + await echo_body(scope, receive, send) + elif scope["path"].startswith("/echo_binary"): + await echo_binary(scope, receive, send) + elif scope["path"].startswith("/echo_headers"): + await echo_headers(scope, receive, send) + elif scope["path"].startswith("/redirect_301"): + await redirect_301(scope, receive, send) + elif scope["path"].startswith("/json"): + await hello_world_json(scope, receive, send) + else: + await hello_world(scope, receive, send) + + +async def hello_world(scope: Scope, receive: Receive, send: Send) -> None: + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + +async def hello_world_json(scope: Scope, receive: Receive, send: Send) -> None: + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"application/json"]], + } + ) + await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'}) + + +async def slow_response(scope: Scope, receive: Receive, send: Send) -> None: + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await sleep(1.0) # Allow triggering a read timeout. + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + +async def status_code(scope: Scope, receive: Receive, send: Send) -> None: + status_code = int(scope["path"].replace("/status/", "")) + await send( + { + "type": "http.response.start", + "status": status_code, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + +async def echo_body(scope: Scope, receive: Receive, send: Send) -> None: + body = b"" + more_body = True + + while more_body: + message = await receive() + body += message.get("body", b"") + more_body = message.get("more_body", False) + + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": body}) + + +async def echo_binary(scope: Scope, receive: Receive, send: Send) -> None: + body = b"" + more_body = True + + while more_body: + message = await receive() + body += message.get("body", b"") + more_body = message.get("more_body", False) + + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"application/octet-stream"]], + } + ) + await send({"type": "http.response.body", "body": body}) + + +async def echo_headers(scope: Scope, receive: Receive, send: Send) -> None: + body = { + name.capitalize().decode(): value.decode() + for name, value in scope.get("headers", []) + } + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"application/json"]], + } + ) + await send({"type": "http.response.body", "body": json.dumps(body).encode()}) + + +async def redirect_301(scope: Scope, receive: Receive, send: Send) -> None: + await send( + {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]} + ) + await send({"type": "http.response.body"}) + + +@pytest.fixture(scope="session") +def cert_authority(): + return trustme.CA() + + +@pytest.fixture(scope="session") +def localhost_cert(cert_authority): + return cert_authority.issue_cert("localhost") + + +@pytest.fixture(scope="session") +def cert_pem_file(localhost_cert): + with localhost_cert.cert_chain_pems[0].tempfile() as tmp: + yield tmp + + +@pytest.fixture(scope="session") +def cert_private_key_file(localhost_cert): + with localhost_cert.private_key_pem.tempfile() as tmp: + yield tmp + + +@pytest.fixture(scope="session") +def cert_encrypted_private_key_file(localhost_cert): + # Deserialize the private key and then reserialize with a password + private_key = load_pem_private_key( + localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend() + ) + encrypted_private_key_pem = trustme.Blob( + private_key.private_bytes( + Encoding.PEM, + PrivateFormat.TraditionalOpenSSL, + BestAvailableEncryption(password=b"password"), + ) + ) + with encrypted_private_key_pem.tempfile() as tmp: + yield tmp + + +class TestServer(Server): + @property + def url(self) -> httpx.URL: + protocol = "https" if self.config.is_ssl else "http" + return httpx.URL(f"{protocol}://{self.config.host}:{self.config.port}/") + + def install_signal_handlers(self) -> None: + # Disable the default installation of handlers for signals such as SIGTERM, + # because it can only be done in the main thread. + pass # pragma: nocover + + async def serve(self, sockets=None): + self.restart_requested = asyncio.Event() + + loop = asyncio.get_event_loop() + tasks = { + loop.create_task(super().serve(sockets=sockets)), + loop.create_task(self.watch_restarts()), + } + await asyncio.wait(tasks) + + async def restart(self) -> None: # pragma: no cover + # This coroutine may be called from a different thread than the one the + # server is running on, and from an async environment that's not asyncio. + # For this reason, we use an event to coordinate with the server + # instead of calling shutdown()/startup() directly, and should not make + # any asyncio-specific operations. + self.started = False + self.restart_requested.set() + while not self.started: + await sleep(0.2) + + async def watch_restarts(self) -> None: # pragma: no cover + while True: + if self.should_exit: + return + + try: + await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1) + except asyncio.TimeoutError: + continue + + self.restart_requested.clear() + await self.shutdown() + await self.startup() + + +def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]: + thread = threading.Thread(target=server.run) + thread.start() + try: + while not server.started: + time.sleep(1e-3) + yield server + finally: + server.should_exit = True + thread.join() + + +@pytest.fixture(scope="session") +def server() -> typing.Iterator[TestServer]: + config = Config(app=app, lifespan="off", loop="asyncio") + server = TestServer(config=config) + yield from serve_in_thread(server) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc new file mode 100644 index 0000000000000000000000000000000000000000..ed65ee7d3d57b02580beae0dc121b795402a0fa7 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc @@ -0,0 +1,3 @@ +machine netrcexample.org +login example-username +password example-password \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc-nopassword b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc-nopassword new file mode 100644 index 0000000000000000000000000000000000000000..5575bee704567189e6d68b1c8a708505aaa6e3e2 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/fixtures/.netrc-nopassword @@ -0,0 +1,2 @@ +machine netrcexample.org +login example-username diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/__init__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_cookies.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..f7abe11ad4433eda02905f695cabfca28b8b90ae --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_cookies.py @@ -0,0 +1,98 @@ +import http + +import pytest + +import httpx + + +def test_cookies(): + cookies = httpx.Cookies({"name": "value"}) + assert cookies["name"] == "value" + assert "name" in cookies + assert len(cookies) == 1 + assert dict(cookies) == {"name": "value"} + assert bool(cookies) is True + + del cookies["name"] + assert "name" not in cookies + assert len(cookies) == 0 + assert dict(cookies) == {} + assert bool(cookies) is False + + +def test_cookies_update(): + cookies = httpx.Cookies() + more_cookies = httpx.Cookies() + more_cookies.set("name", "value", domain="example.com") + + cookies.update(more_cookies) + assert dict(cookies) == {"name": "value"} + assert cookies.get("name", domain="example.com") == "value" + + +def test_cookies_with_domain(): + cookies = httpx.Cookies() + cookies.set("name", "value", domain="example.com") + cookies.set("name", "value", domain="example.org") + + with pytest.raises(httpx.CookieConflict): + cookies["name"] + + cookies.clear(domain="example.com") + assert len(cookies) == 1 + + +def test_cookies_with_domain_and_path(): + cookies = httpx.Cookies() + cookies.set("name", "value", domain="example.com", path="/subpath/1") + cookies.set("name", "value", domain="example.com", path="/subpath/2") + cookies.clear(domain="example.com", path="/subpath/1") + assert len(cookies) == 1 + cookies.delete("name", domain="example.com", path="/subpath/2") + assert len(cookies) == 0 + + +def test_multiple_set_cookie(): + jar = http.cookiejar.CookieJar() + headers = [ + ( + b"Set-Cookie", + b"1P_JAR=2020-08-09-18; expires=Tue, 08-Sep-2099 18:33:35 GMT; " + b"path=/; domain=.example.org; Secure", + ), + ( + b"Set-Cookie", + b"NID=204=KWdXOuypc86YvRfBSiWoW1dEXfSl_5qI7sxZY4umlk4J35yNTeNEkw15" + b"MRaujK6uYCwkrtjihTTXZPp285z_xDOUzrdHt4dj0Z5C0VOpbvdLwRdHatHAzQs7" + b"7TsaiWY78a3qU9r7KP_RbSLvLl2hlhnWFR2Hp5nWKPsAcOhQgSg; expires=Mon, " + b"08-Feb-2099 18:33:35 GMT; path=/; domain=.example.org; HttpOnly", + ), + ] + request = httpx.Request("GET", "https://www.example.org") + response = httpx.Response(200, request=request, headers=headers) + + cookies = httpx.Cookies(jar) + cookies.extract_cookies(response) + + assert len(cookies) == 2 + + +def test_cookies_can_be_a_list_of_tuples(): + cookies_val = [("name1", "val1"), ("name2", "val2")] + + cookies = httpx.Cookies(cookies_val) + + assert len(cookies.items()) == 2 + for k, v in cookies_val: + assert cookies[k] == v + + +def test_cookies_repr(): + cookies = httpx.Cookies() + cookies.set(name="foo", value="bar", domain="http://blah.com") + cookies.set(name="fizz", value="buzz", domain="http://hello.com") + + assert repr(cookies) == ( + "," + " ]>" + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_headers.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..a87a446784b003b0e62b87408b9d057773c1b2fe --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_headers.py @@ -0,0 +1,219 @@ +import pytest + +import httpx + + +def test_headers(): + h = httpx.Headers([("a", "123"), ("a", "456"), ("b", "789")]) + assert "a" in h + assert "A" in h + assert "b" in h + assert "B" in h + assert "c" not in h + assert h["a"] == "123, 456" + assert h.get("a") == "123, 456" + assert h.get("nope", default=None) is None + assert h.get_list("a") == ["123", "456"] + + assert list(h.keys()) == ["a", "b"] + assert list(h.values()) == ["123, 456", "789"] + assert list(h.items()) == [("a", "123, 456"), ("b", "789")] + assert h.multi_items() == [("a", "123"), ("a", "456"), ("b", "789")] + assert list(h) == ["a", "b"] + assert dict(h) == {"a": "123, 456", "b": "789"} + assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])" + assert h == [("a", "123"), ("b", "789"), ("a", "456")] + assert h == [("a", "123"), ("A", "456"), ("b", "789")] + assert h == {"a": "123", "A": "456", "b": "789"} + assert h != "a: 123\nA: 456\nb: 789" + + h = httpx.Headers({"a": "123", "b": "789"}) + assert h["A"] == "123" + assert h["B"] == "789" + assert h.raw == [(b"a", b"123"), (b"b", b"789")] + assert repr(h) == "Headers({'a': '123', 'b': '789'})" + + +def test_header_mutations(): + h = httpx.Headers() + assert dict(h) == {} + h["a"] = "1" + assert dict(h) == {"a": "1"} + h["a"] = "2" + assert dict(h) == {"a": "2"} + h.setdefault("a", "3") + assert dict(h) == {"a": "2"} + h.setdefault("b", "4") + assert dict(h) == {"a": "2", "b": "4"} + del h["a"] + assert dict(h) == {"b": "4"} + assert h.raw == [(b"b", b"4")] + + +def test_copy_headers_method(): + headers = httpx.Headers({"custom": "example"}) + headers_copy = headers.copy() + assert headers == headers_copy + assert headers is not headers_copy + + +def test_copy_headers_init(): + headers = httpx.Headers({"custom": "example"}) + headers_copy = httpx.Headers(headers) + assert headers == headers_copy + + +def test_headers_insert_retains_ordering(): + headers = httpx.Headers({"a": "a", "b": "b", "c": "c"}) + headers["b"] = "123" + assert list(headers.values()) == ["a", "123", "c"] + + +def test_headers_insert_appends_if_new(): + headers = httpx.Headers({"a": "a", "b": "b", "c": "c"}) + headers["d"] = "123" + assert list(headers.values()) == ["a", "b", "c", "123"] + + +def test_headers_insert_removes_all_existing(): + headers = httpx.Headers([("a", "123"), ("a", "456")]) + headers["a"] = "789" + assert dict(headers) == {"a": "789"} + + +def test_headers_delete_removes_all_existing(): + headers = httpx.Headers([("a", "123"), ("a", "456")]) + del headers["a"] + assert dict(headers) == {} + + +def test_headers_dict_repr(): + """ + Headers should display with a dict repr by default. + """ + headers = httpx.Headers({"custom": "example"}) + assert repr(headers) == "Headers({'custom': 'example'})" + + +def test_headers_encoding_in_repr(): + """ + Headers should display an encoding in the repr if required. + """ + headers = httpx.Headers({b"custom": "example ☃".encode("utf-8")}) + assert repr(headers) == "Headers({'custom': 'example ☃'}, encoding='utf-8')" + + +def test_headers_list_repr(): + """ + Headers should display with a list repr if they include multiple identical keys. + """ + headers = httpx.Headers([("custom", "example 1"), ("custom", "example 2")]) + assert ( + repr(headers) == "Headers([('custom', 'example 1'), ('custom', 'example 2')])" + ) + + +def test_headers_decode_ascii(): + """ + Headers should decode as ascii by default. + """ + raw_headers = [(b"Custom", b"Example")] + headers = httpx.Headers(raw_headers) + assert dict(headers) == {"custom": "Example"} + assert headers.encoding == "ascii" + + +def test_headers_decode_utf_8(): + """ + Headers containing non-ascii codepoints should default to decoding as utf-8. + """ + raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))] + headers = httpx.Headers(raw_headers) + assert dict(headers) == {"custom": "Code point: ☃"} + assert headers.encoding == "utf-8" + + +def test_headers_decode_iso_8859_1(): + """ + Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1. + """ + raw_headers = [(b"Custom", "Code point: ÿ".encode("iso-8859-1"))] + headers = httpx.Headers(raw_headers) + assert dict(headers) == {"custom": "Code point: ÿ"} + assert headers.encoding == "iso-8859-1" + + +def test_headers_decode_explicit_encoding(): + """ + An explicit encoding may be set on headers in order to force a + particular decoding. + """ + raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))] + headers = httpx.Headers(raw_headers) + headers.encoding = "iso-8859-1" + assert dict(headers) == {"custom": "Code point: â\x98\x83"} + assert headers.encoding == "iso-8859-1" + + +def test_multiple_headers(): + """ + `Headers.get_list` should support both split_commas=False and split_commas=True. + """ + h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")]) + assert h.get_list("Set-Cookie") == ["a, b", "c"] + + h = httpx.Headers([("vary", "a, b"), ("vary", "c")]) + assert h.get_list("Vary", split_commas=True) == ["a", "b", "c"] + + +@pytest.mark.parametrize("header", ["authorization", "proxy-authorization"]) +def test_sensitive_headers(header): + """ + Some headers should be obfuscated because they contain sensitive data. + """ + value = "s3kr3t" + h = httpx.Headers({header: value}) + assert repr(h) == "Headers({'%s': '[secure]'})" % header + + +@pytest.mark.parametrize( + "headers, output", + [ + ([("content-type", "text/html")], [("content-type", "text/html")]), + ([("authorization", "s3kr3t")], [("authorization", "[secure]")]), + ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]), + ], +) +def test_obfuscate_sensitive_headers(headers, output): + as_dict = {k: v for k, v in output} + headers_class = httpx.Headers({k: v for k, v in headers}) + assert repr(headers_class) == f"Headers({as_dict!r})" + + +@pytest.mark.parametrize( + "value, expected", + ( + ( + '; rel=front; type="image/jpeg"', + [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}], + ), + ("", [{"url": "http:/.../front.jpeg"}]), + (";", [{"url": "http:/.../front.jpeg"}]), + ( + '; type="image/jpeg",;', + [ + {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, + {"url": "http://.../back.jpeg"}, + ], + ), + ("", []), + ), +) +def test_parse_header_links(value, expected): + all_links = httpx.Response(200, headers={"link": value}).links.values() + assert all(link in all_links for link in expected) + + +def test_parse_header_links_no_link(): + all_links = httpx.Response(200).links + assert all_links == {} diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_queryparams.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_queryparams.py new file mode 100644 index 0000000000000000000000000000000000000000..29b2ca634d73036db3b10e55e965a915e70de6e6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_queryparams.py @@ -0,0 +1,136 @@ +import pytest + +import httpx + + +@pytest.mark.parametrize( + "source", + [ + "a=123&a=456&b=789", + {"a": ["123", "456"], "b": 789}, + {"a": ("123", "456"), "b": 789}, + [("a", "123"), ("a", "456"), ("b", "789")], + (("a", "123"), ("a", "456"), ("b", "789")), + ], +) +def test_queryparams(source): + q = httpx.QueryParams(source) + assert "a" in q + assert "A" not in q + assert "c" not in q + assert q["a"] == "123" + assert q.get("a") == "123" + assert q.get("nope", default=None) is None + assert q.get_list("a") == ["123", "456"] + + assert list(q.keys()) == ["a", "b"] + assert list(q.values()) == ["123", "789"] + assert list(q.items()) == [("a", "123"), ("b", "789")] + assert len(q) == 2 + assert list(q) == ["a", "b"] + assert dict(q) == {"a": "123", "b": "789"} + assert str(q) == "a=123&a=456&b=789" + assert repr(q) == "QueryParams('a=123&a=456&b=789')" + assert httpx.QueryParams({"a": "123", "b": "456"}) == httpx.QueryParams( + [("a", "123"), ("b", "456")] + ) + assert httpx.QueryParams({"a": "123", "b": "456"}) == httpx.QueryParams( + "a=123&b=456" + ) + assert httpx.QueryParams({"a": "123", "b": "456"}) == httpx.QueryParams( + {"b": "456", "a": "123"} + ) + assert httpx.QueryParams() == httpx.QueryParams({}) + assert httpx.QueryParams([("a", "123"), ("a", "456")]) == httpx.QueryParams( + "a=123&a=456" + ) + assert httpx.QueryParams({"a": "123", "b": "456"}) != "invalid" + + q = httpx.QueryParams([("a", "123"), ("a", "456")]) + assert httpx.QueryParams(q) == q + + +def test_queryparam_types(): + q = httpx.QueryParams(None) + assert str(q) == "" + + q = httpx.QueryParams({"a": True}) + assert str(q) == "a=true" + + q = httpx.QueryParams({"a": False}) + assert str(q) == "a=false" + + q = httpx.QueryParams({"a": ""}) + assert str(q) == "a=" + + q = httpx.QueryParams({"a": None}) + assert str(q) == "a=" + + q = httpx.QueryParams({"a": 1.23}) + assert str(q) == "a=1.23" + + q = httpx.QueryParams({"a": 123}) + assert str(q) == "a=123" + + q = httpx.QueryParams({"a": [1, 2]}) + assert str(q) == "a=1&a=2" + + +def test_empty_query_params(): + q = httpx.QueryParams({"a": ""}) + assert str(q) == "a=" + + q = httpx.QueryParams("a=") + assert str(q) == "a=" + + q = httpx.QueryParams("a") + assert str(q) == "a=" + + +def test_queryparam_update_is_hard_deprecated(): + q = httpx.QueryParams("a=123") + with pytest.raises(RuntimeError): + q.update({"a": "456"}) + + +def test_queryparam_setter_is_hard_deprecated(): + q = httpx.QueryParams("a=123") + with pytest.raises(RuntimeError): + q["a"] = "456" + + +def test_queryparam_set(): + q = httpx.QueryParams("a=123") + q = q.set("a", "456") + assert q == httpx.QueryParams("a=456") + + +def test_queryparam_add(): + q = httpx.QueryParams("a=123") + q = q.add("a", "456") + assert q == httpx.QueryParams("a=123&a=456") + + +def test_queryparam_remove(): + q = httpx.QueryParams("a=123") + q = q.remove("a") + assert q == httpx.QueryParams("") + + +def test_queryparam_merge(): + q = httpx.QueryParams("a=123") + q = q.merge({"b": "456"}) + assert q == httpx.QueryParams("a=123&b=456") + q = q.merge({"a": "000", "c": "789"}) + assert q == httpx.QueryParams("a=000&b=456&c=789") + + +def test_queryparams_are_hashable(): + params = ( + httpx.QueryParams("a=123"), + httpx.QueryParams({"a": 123}), + httpx.QueryParams("b=456"), + httpx.QueryParams({"b": 456}), + ) + + assert len(set(params)) == 2 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_requests.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_requests.py new file mode 100644 index 0000000000000000000000000000000000000000..b31fe007be25bab60f90491af07e83c819cac5a6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_requests.py @@ -0,0 +1,241 @@ +import pickle +import typing + +import pytest + +import httpx + + +def test_request_repr(): + request = httpx.Request("GET", "http://example.org") + assert repr(request) == "" + + +def test_no_content(): + request = httpx.Request("GET", "http://example.org") + assert "Content-Length" not in request.headers + + +def test_content_length_header(): + request = httpx.Request("POST", "http://example.org", content=b"test 123") + assert request.headers["Content-Length"] == "8" + + +def test_iterable_content(): + class Content: + def __iter__(self): + yield b"test 123" # pragma: no cover + + request = httpx.Request("POST", "http://example.org", content=Content()) + assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"} + + +def test_generator_with_transfer_encoding_header(): + def content() -> typing.Iterator[bytes]: + yield b"test 123" # pragma: no cover + + request = httpx.Request("POST", "http://example.org", content=content()) + assert request.headers == {"Host": "example.org", "Transfer-Encoding": "chunked"} + + +def test_generator_with_content_length_header(): + def content() -> typing.Iterator[bytes]: + yield b"test 123" # pragma: no cover + + headers = {"Content-Length": "8"} + request = httpx.Request( + "POST", "http://example.org", content=content(), headers=headers + ) + assert request.headers == {"Host": "example.org", "Content-Length": "8"} + + +def test_url_encoded_data(): + request = httpx.Request("POST", "http://example.org", data={"test": "123"}) + request.read() + + assert request.headers["Content-Type"] == "application/x-www-form-urlencoded" + assert request.content == b"test=123" + + +def test_json_encoded_data(): + request = httpx.Request("POST", "http://example.org", json={"test": 123}) + request.read() + + assert request.headers["Content-Type"] == "application/json" + assert request.content == b'{"test":123}' + + +def test_headers(): + request = httpx.Request("POST", "http://example.org", json={"test": 123}) + + assert request.headers == { + "Host": "example.org", + "Content-Type": "application/json", + "Content-Length": "12", + } + + +def test_read_and_stream_data(): + # Ensure a request may still be streamed if it has been read. + # Needed for cases such as authentication classes that read the request body. + request = httpx.Request("POST", "http://example.org", json={"test": 123}) + request.read() + assert request.stream is not None + assert isinstance(request.stream, typing.Iterable) + content = b"".join(list(request.stream)) + assert content == request.content + + +@pytest.mark.anyio +async def test_aread_and_stream_data(): + # Ensure a request may still be streamed if it has been read. + # Needed for cases such as authentication classes that read the request body. + request = httpx.Request("POST", "http://example.org", json={"test": 123}) + await request.aread() + assert request.stream is not None + assert isinstance(request.stream, typing.AsyncIterable) + content = b"".join([part async for part in request.stream]) + assert content == request.content + + +def test_cannot_access_streaming_content_without_read(): + # Ensure that streaming requests + def streaming_body() -> typing.Iterator[bytes]: # pragma: no cover + yield b"" + + request = httpx.Request("POST", "http://example.org", content=streaming_body()) + with pytest.raises(httpx.RequestNotRead): + request.content # noqa: B018 + + +def test_transfer_encoding_header(): + async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]: + yield data # pragma: no cover + + data = streaming_body(b"test 123") + + request = httpx.Request("POST", "http://example.org", content=data) + assert "Content-Length" not in request.headers + assert request.headers["Transfer-Encoding"] == "chunked" + + +def test_ignore_transfer_encoding_header_if_content_length_exists(): + """ + `Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly. + See https://github.com/encode/httpx/issues/1168 + """ + + def streaming_body(data: bytes) -> typing.Iterator[bytes]: + yield data # pragma: no cover + + data = streaming_body(b"abcd") + + headers = {"Content-Length": "4"} + request = httpx.Request("POST", "http://example.org", content=data, headers=headers) + assert "Transfer-Encoding" not in request.headers + assert request.headers["Content-Length"] == "4" + + +def test_override_host_header(): + headers = {"host": "1.2.3.4:80"} + + request = httpx.Request("GET", "http://example.org", headers=headers) + assert request.headers["Host"] == "1.2.3.4:80" + + +def test_override_accept_encoding_header(): + headers = {"Accept-Encoding": "identity"} + + request = httpx.Request("GET", "http://example.org", headers=headers) + assert request.headers["Accept-Encoding"] == "identity" + + +def test_override_content_length_header(): + async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]: + yield data # pragma: no cover + + data = streaming_body(b"test 123") + headers = {"Content-Length": "8"} + + request = httpx.Request("POST", "http://example.org", content=data, headers=headers) + assert request.headers["Content-Length"] == "8" + + +def test_url(): + url = "http://example.org" + request = httpx.Request("GET", url) + assert request.url.scheme == "http" + assert request.url.port is None + assert request.url.path == "/" + assert request.url.raw_path == b"/" + + url = "https://example.org/abc?foo=bar" + request = httpx.Request("GET", url) + assert request.url.scheme == "https" + assert request.url.port is None + assert request.url.path == "/abc" + assert request.url.raw_path == b"/abc?foo=bar" + + +def test_request_picklable(): + request = httpx.Request("POST", "http://example.org", json={"test": 123}) + pickle_request = pickle.loads(pickle.dumps(request)) + assert pickle_request.method == "POST" + assert pickle_request.url.path == "/" + assert pickle_request.headers["Content-Type"] == "application/json" + assert pickle_request.content == b'{"test":123}' + assert pickle_request.stream is not None + assert request.headers == { + "Host": "example.org", + "Content-Type": "application/json", + "content-length": "12", + } + + +@pytest.mark.anyio +async def test_request_async_streaming_content_picklable(): + async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]: + yield data + + data = streaming_body(b"test 123") + request = httpx.Request("POST", "http://example.org", content=data) + pickle_request = pickle.loads(pickle.dumps(request)) + with pytest.raises(httpx.RequestNotRead): + pickle_request.content # noqa: B018 + with pytest.raises(httpx.StreamClosed): + await pickle_request.aread() + + request = httpx.Request("POST", "http://example.org", content=data) + await request.aread() + pickle_request = pickle.loads(pickle.dumps(request)) + assert pickle_request.content == b"test 123" + + +def test_request_generator_content_picklable(): + def content() -> typing.Iterator[bytes]: + yield b"test 123" # pragma: no cover + + request = httpx.Request("POST", "http://example.org", content=content()) + pickle_request = pickle.loads(pickle.dumps(request)) + with pytest.raises(httpx.RequestNotRead): + pickle_request.content # noqa: B018 + with pytest.raises(httpx.StreamClosed): + pickle_request.read() + + request = httpx.Request("POST", "http://example.org", content=content()) + request.read() + pickle_request = pickle.loads(pickle.dumps(request)) + assert pickle_request.content == b"test 123" + + +def test_request_params(): + request = httpx.Request("GET", "http://example.com", params={}) + assert str(request.url) == "http://example.com" + + request = httpx.Request( + "GET", "http://example.com?c=3", params={"a": "1", "b": "2"} + ) + assert str(request.url) == "http://example.com?a=1&b=2" + + request = httpx.Request("GET", "http://example.com?a=1", params={}) + assert str(request.url) == "http://example.com" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_responses.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..06c28e1e30b3bb77325327e82b368687f6bbe65c --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_responses.py @@ -0,0 +1,1037 @@ +import json +import pickle +import typing + +import chardet +import pytest + +import httpx + + +class StreamingBody: + def __iter__(self): + yield b"Hello, " + yield b"world!" + + +def streaming_body() -> typing.Iterator[bytes]: + yield b"Hello, " + yield b"world!" + + +async def async_streaming_body() -> typing.AsyncIterator[bytes]: + yield b"Hello, " + yield b"world!" + + +def autodetect(content): + return chardet.detect(content).get("encoding") + + +def test_response(): + response = httpx.Response( + 200, + content=b"Hello, world!", + request=httpx.Request("GET", "https://example.org"), + ) + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.request.method == "GET" + assert response.request.url == "https://example.org" + assert not response.is_error + + +def test_response_content(): + response = httpx.Response(200, content="Hello, world!") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.headers == {"Content-Length": "13"} + + +def test_response_text(): + response = httpx.Response(200, text="Hello, world!") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.headers == { + "Content-Length": "13", + "Content-Type": "text/plain; charset=utf-8", + } + + +def test_response_html(): + response = httpx.Response(200, html="Hello, world!") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.headers == { + "Content-Length": "39", + "Content-Type": "text/html; charset=utf-8", + } + + +def test_response_json(): + response = httpx.Response(200, json={"hello": "world"}) + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert str(response.json()) == "{'hello': 'world'}" + assert response.headers == { + "Content-Length": "17", + "Content-Type": "application/json", + } + + +def test_raise_for_status(): + request = httpx.Request("GET", "https://example.org") + + # 2xx status codes are not an error. + response = httpx.Response(200, request=request) + response.raise_for_status() + + # 1xx status codes are informational responses. + response = httpx.Response(101, request=request) + assert response.is_informational + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert str(exc_info.value) == ( + "Informational response '101 Switching Protocols' for url 'https://example.org'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101" + ) + + # 3xx status codes are redirections. + headers = {"location": "https://other.org"} + response = httpx.Response(303, headers=headers, request=request) + assert response.is_redirect + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert str(exc_info.value) == ( + "Redirect response '303 See Other' for url 'https://example.org'\n" + "Redirect location: 'https://other.org'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303" + ) + + # 4xx status codes are a client error. + response = httpx.Response(403, request=request) + assert response.is_client_error + assert response.is_error + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert str(exc_info.value) == ( + "Client error '403 Forbidden' for url 'https://example.org'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403" + ) + + # 5xx status codes are a server error. + response = httpx.Response(500, request=request) + assert response.is_server_error + assert response.is_error + with pytest.raises(httpx.HTTPStatusError) as exc_info: + response.raise_for_status() + assert str(exc_info.value) == ( + "Server error '500 Internal Server Error' for url 'https://example.org'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500" + ) + + # Calling .raise_for_status without setting a request instance is + # not valid. Should raise a runtime error. + response = httpx.Response(200) + with pytest.raises(RuntimeError): + response.raise_for_status() + + +def test_response_repr(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + assert repr(response) == "" + + +def test_response_content_type_encoding(): + """ + Use the charset encoding in the Content-Type header if possible. + """ + headers = {"Content-Type": "text-plain; charset=latin-1"} + content = "Latin 1: ÿ".encode("latin-1") + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.text == "Latin 1: ÿ" + assert response.encoding == "latin-1" + + +def test_response_default_to_utf8_encoding(): + """ + Default to utf-8 encoding if there is no Content-Type header. + """ + content = "おはようございます。".encode("utf-8") + response = httpx.Response( + 200, + content=content, + ) + assert response.text == "おはようございます。" + assert response.encoding == "utf-8" + + +def test_response_fallback_to_utf8_encoding(): + """ + Fallback to utf-8 if we get an invalid charset in the Content-Type header. + """ + headers = {"Content-Type": "text-plain; charset=invalid-codec-name"} + content = "おはようございます。".encode("utf-8") + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.text == "おはようございます。" + assert response.encoding == "utf-8" + + +def test_response_no_charset_with_ascii_content(): + """ + A response with ascii encoded content should decode correctly, + even with no charset specified. + """ + content = b"Hello, world!" + headers = {"Content-Type": "text/plain"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.status_code == 200 + assert response.encoding == "utf-8" + assert response.text == "Hello, world!" + + +def test_response_no_charset_with_utf8_content(): + """ + A response with UTF-8 encoded content should decode correctly, + even with no charset specified. + """ + content = "Unicode Snowman: ☃".encode("utf-8") + headers = {"Content-Type": "text/plain"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.text == "Unicode Snowman: ☃" + assert response.encoding == "utf-8" + + +def test_response_no_charset_with_iso_8859_1_content(): + """ + A response with ISO 8859-1 encoded content should decode correctly, + even with no charset specified, if autodetect is enabled. + """ + content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1") + headers = {"Content-Type": "text/plain"} + response = httpx.Response( + 200, content=content, headers=headers, default_encoding=autodetect + ) + assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz" + assert response.charset_encoding is None + + +def test_response_no_charset_with_cp_1252_content(): + """ + A response with Windows 1252 encoded content should decode correctly, + even with no charset specified, if autodetect is enabled. + """ + content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252") + headers = {"Content-Type": "text/plain"} + response = httpx.Response( + 200, content=content, headers=headers, default_encoding=autodetect + ) + assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz" + assert response.charset_encoding is None + + +def test_response_non_text_encoding(): + """ + Default to attempting utf-8 encoding for non-text content-type headers. + """ + headers = {"Content-Type": "image/png"} + response = httpx.Response( + 200, + content=b"xyz", + headers=headers, + ) + assert response.text == "xyz" + assert response.encoding == "utf-8" + + +def test_response_set_explicit_encoding(): + headers = { + "Content-Type": "text-plain; charset=utf-8" + } # Deliberately incorrect charset + response = httpx.Response( + 200, + content="Latin 1: ÿ".encode("latin-1"), + headers=headers, + ) + response.encoding = "latin-1" + assert response.text == "Latin 1: ÿ" + assert response.encoding == "latin-1" + + +def test_response_force_encoding(): + response = httpx.Response( + 200, + content="Snowman: ☃".encode("utf-8"), + ) + response.encoding = "iso-8859-1" + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Snowman: â\x98\x83" + assert response.encoding == "iso-8859-1" + + +def test_response_force_encoding_after_text_accessed(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.encoding == "utf-8" + + with pytest.raises(ValueError): + response.encoding = "UTF8" + + with pytest.raises(ValueError): + response.encoding = "iso-8859-1" + + +def test_read(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + + assert response.status_code == 200 + assert response.text == "Hello, world!" + assert response.encoding == "utf-8" + assert response.is_closed + + content = response.read() + + assert content == b"Hello, world!" + assert response.content == b"Hello, world!" + assert response.is_closed + + +def test_empty_read(): + response = httpx.Response(200) + + assert response.status_code == 200 + assert response.text == "" + assert response.encoding == "utf-8" + assert response.is_closed + + content = response.read() + + assert content == b"" + assert response.content == b"" + assert response.is_closed + + +@pytest.mark.anyio +async def test_aread(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + + assert response.status_code == 200 + assert response.text == "Hello, world!" + assert response.encoding == "utf-8" + assert response.is_closed + + content = await response.aread() + + assert content == b"Hello, world!" + assert response.content == b"Hello, world!" + assert response.is_closed + + +@pytest.mark.anyio +async def test_empty_aread(): + response = httpx.Response(200) + + assert response.status_code == 200 + assert response.text == "" + assert response.encoding == "utf-8" + assert response.is_closed + + content = await response.aread() + + assert content == b"" + assert response.content == b"" + assert response.is_closed + + +def test_iter_raw(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + raw = b"" + for part in response.iter_raw(): + raw += part + assert raw == b"Hello, world!" + + +def test_iter_raw_with_chunksize(): + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_raw(chunk_size=5)) + assert parts == [b"Hello", b", wor", b"ld!"] + + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_raw(chunk_size=7)) + assert parts == [b"Hello, ", b"world!"] + + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_raw(chunk_size=13)) + assert parts == [b"Hello, world!"] + + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_raw(chunk_size=20)) + assert parts == [b"Hello, world!"] + + +def test_iter_raw_doesnt_return_empty_chunks(): + def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]: + yield b"Hello, " + yield b"" + yield b"world!" + yield b"" + + response = httpx.Response(200, content=streaming_body_with_empty_chunks()) + + parts = list(response.iter_raw()) + assert parts == [b"Hello, ", b"world!"] + + +def test_iter_raw_on_iterable(): + response = httpx.Response( + 200, + content=StreamingBody(), + ) + + raw = b"" + for part in response.iter_raw(): + raw += part + assert raw == b"Hello, world!" + + +def test_iter_raw_on_async(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + with pytest.raises(RuntimeError): + list(response.iter_raw()) + + +def test_close_on_async(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + with pytest.raises(RuntimeError): + response.close() + + +def test_iter_raw_increments_updates_counter(): + response = httpx.Response(200, content=streaming_body()) + + num_downloaded = response.num_bytes_downloaded + for part in response.iter_raw(): + assert len(part) == (response.num_bytes_downloaded - num_downloaded) + num_downloaded = response.num_bytes_downloaded + + +@pytest.mark.anyio +async def test_aiter_raw(): + response = httpx.Response(200, content=async_streaming_body()) + + raw = b"" + async for part in response.aiter_raw(): + raw += part + assert raw == b"Hello, world!" + + +@pytest.mark.anyio +async def test_aiter_raw_with_chunksize(): + response = httpx.Response(200, content=async_streaming_body()) + + parts = [part async for part in response.aiter_raw(chunk_size=5)] + assert parts == [b"Hello", b", wor", b"ld!"] + + response = httpx.Response(200, content=async_streaming_body()) + + parts = [part async for part in response.aiter_raw(chunk_size=13)] + assert parts == [b"Hello, world!"] + + response = httpx.Response(200, content=async_streaming_body()) + + parts = [part async for part in response.aiter_raw(chunk_size=20)] + assert parts == [b"Hello, world!"] + + +@pytest.mark.anyio +async def test_aiter_raw_on_sync(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + with pytest.raises(RuntimeError): + [part async for part in response.aiter_raw()] + + +@pytest.mark.anyio +async def test_aclose_on_sync(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + with pytest.raises(RuntimeError): + await response.aclose() + + +@pytest.mark.anyio +async def test_aiter_raw_increments_updates_counter(): + response = httpx.Response(200, content=async_streaming_body()) + + num_downloaded = response.num_bytes_downloaded + async for part in response.aiter_raw(): + assert len(part) == (response.num_bytes_downloaded - num_downloaded) + num_downloaded = response.num_bytes_downloaded + + +def test_iter_bytes(): + response = httpx.Response(200, content=b"Hello, world!") + + content = b"" + for part in response.iter_bytes(): + content += part + assert content == b"Hello, world!" + + +def test_iter_bytes_with_chunk_size(): + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_bytes(chunk_size=5)) + assert parts == [b"Hello", b", wor", b"ld!"] + + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_bytes(chunk_size=13)) + assert parts == [b"Hello, world!"] + + response = httpx.Response(200, content=streaming_body()) + parts = list(response.iter_bytes(chunk_size=20)) + assert parts == [b"Hello, world!"] + + +def test_iter_bytes_with_empty_response(): + response = httpx.Response(200, content=b"") + parts = list(response.iter_bytes()) + assert parts == [] + + +def test_iter_bytes_doesnt_return_empty_chunks(): + def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]: + yield b"Hello, " + yield b"" + yield b"world!" + yield b"" + + response = httpx.Response(200, content=streaming_body_with_empty_chunks()) + + parts = list(response.iter_bytes()) + assert parts == [b"Hello, ", b"world!"] + + +@pytest.mark.anyio +async def test_aiter_bytes(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + + content = b"" + async for part in response.aiter_bytes(): + content += part + assert content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_aiter_bytes_with_chunk_size(): + response = httpx.Response(200, content=async_streaming_body()) + parts = [part async for part in response.aiter_bytes(chunk_size=5)] + assert parts == [b"Hello", b", wor", b"ld!"] + + response = httpx.Response(200, content=async_streaming_body()) + parts = [part async for part in response.aiter_bytes(chunk_size=13)] + assert parts == [b"Hello, world!"] + + response = httpx.Response(200, content=async_streaming_body()) + parts = [part async for part in response.aiter_bytes(chunk_size=20)] + assert parts == [b"Hello, world!"] + + +def test_iter_text(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + + content = "" + for part in response.iter_text(): + content += part + assert content == "Hello, world!" + + +def test_iter_text_with_chunk_size(): + response = httpx.Response(200, content=b"Hello, world!") + parts = list(response.iter_text(chunk_size=5)) + assert parts == ["Hello", ", wor", "ld!"] + + response = httpx.Response(200, content=b"Hello, world!!") + parts = list(response.iter_text(chunk_size=7)) + assert parts == ["Hello, ", "world!!"] + + response = httpx.Response(200, content=b"Hello, world!") + parts = list(response.iter_text(chunk_size=7)) + assert parts == ["Hello, ", "world!"] + + response = httpx.Response(200, content=b"Hello, world!") + parts = list(response.iter_text(chunk_size=13)) + assert parts == ["Hello, world!"] + + response = httpx.Response(200, content=b"Hello, world!") + parts = list(response.iter_text(chunk_size=20)) + assert parts == ["Hello, world!"] + + +@pytest.mark.anyio +async def test_aiter_text(): + response = httpx.Response( + 200, + content=b"Hello, world!", + ) + + content = "" + async for part in response.aiter_text(): + content += part + assert content == "Hello, world!" + + +@pytest.mark.anyio +async def test_aiter_text_with_chunk_size(): + response = httpx.Response(200, content=b"Hello, world!") + parts = [part async for part in response.aiter_text(chunk_size=5)] + assert parts == ["Hello", ", wor", "ld!"] + + response = httpx.Response(200, content=b"Hello, world!") + parts = [part async for part in response.aiter_text(chunk_size=13)] + assert parts == ["Hello, world!"] + + response = httpx.Response(200, content=b"Hello, world!") + parts = [part async for part in response.aiter_text(chunk_size=20)] + assert parts == ["Hello, world!"] + + +def test_iter_lines(): + response = httpx.Response( + 200, + content=b"Hello,\nworld!", + ) + content = list(response.iter_lines()) + assert content == ["Hello,", "world!"] + + +@pytest.mark.anyio +async def test_aiter_lines(): + response = httpx.Response( + 200, + content=b"Hello,\nworld!", + ) + + content = [] + async for line in response.aiter_lines(): + content.append(line) + assert content == ["Hello,", "world!"] + + +def test_sync_streaming_response(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + assert response.status_code == 200 + assert not response.is_closed + + content = response.read() + + assert content == b"Hello, world!" + assert response.content == b"Hello, world!" + assert response.is_closed + + +@pytest.mark.anyio +async def test_async_streaming_response(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + assert response.status_code == 200 + assert not response.is_closed + + content = await response.aread() + + assert content == b"Hello, world!" + assert response.content == b"Hello, world!" + assert response.is_closed + + +def test_cannot_read_after_stream_consumed(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + content = b"" + for part in response.iter_bytes(): + content += part + + with pytest.raises(httpx.StreamConsumed): + response.read() + + +@pytest.mark.anyio +async def test_cannot_aread_after_stream_consumed(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + content = b"" + async for part in response.aiter_bytes(): + content += part + + with pytest.raises(httpx.StreamConsumed): + await response.aread() + + +def test_cannot_read_after_response_closed(): + response = httpx.Response( + 200, + content=streaming_body(), + ) + + response.close() + with pytest.raises(httpx.StreamClosed): + response.read() + + +@pytest.mark.anyio +async def test_cannot_aread_after_response_closed(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + await response.aclose() + with pytest.raises(httpx.StreamClosed): + await response.aread() + + +@pytest.mark.anyio +async def test_elapsed_not_available_until_closed(): + response = httpx.Response( + 200, + content=async_streaming_body(), + ) + + with pytest.raises(RuntimeError): + response.elapsed # noqa: B018 + + +def test_unknown_status_code(): + response = httpx.Response( + 600, + ) + assert response.status_code == 600 + assert response.reason_phrase == "" + assert response.text == "" + + +def test_json_with_specified_encoding(): + data = {"greeting": "hello", "recipient": "world"} + content = json.dumps(data).encode("utf-16") + headers = {"Content-Type": "application/json, charset=utf-16"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.json() == data + + +def test_json_with_options(): + data = {"greeting": "hello", "recipient": "world", "amount": 1} + content = json.dumps(data).encode("utf-16") + headers = {"Content-Type": "application/json, charset=utf-16"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.json(parse_int=str)["amount"] == "1" + + +@pytest.mark.parametrize( + "encoding", + [ + "utf-8", + "utf-8-sig", + "utf-16", + "utf-16-be", + "utf-16-le", + "utf-32", + "utf-32-be", + "utf-32-le", + ], +) +def test_json_without_specified_charset(encoding): + data = {"greeting": "hello", "recipient": "world"} + content = json.dumps(data).encode(encoding) + headers = {"Content-Type": "application/json"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.json() == data + + +@pytest.mark.parametrize( + "encoding", + [ + "utf-8", + "utf-8-sig", + "utf-16", + "utf-16-be", + "utf-16-le", + "utf-32", + "utf-32-be", + "utf-32-le", + ], +) +def test_json_with_specified_charset(encoding): + data = {"greeting": "hello", "recipient": "world"} + content = json.dumps(data).encode(encoding) + headers = {"Content-Type": f"application/json; charset={encoding}"} + response = httpx.Response( + 200, + content=content, + headers=headers, + ) + assert response.json() == data + + +@pytest.mark.parametrize( + "headers, expected", + [ + ( + {"Link": "; rel='preload'"}, + {"preload": {"rel": "preload", "url": "https://example.com"}}, + ), + ( + {"Link": '; rel="hub", ; rel="self"'}, + { + "hub": {"url": "/hub", "rel": "hub"}, + "self": {"url": "/resource", "rel": "self"}, + }, + ), + ], +) +def test_link_headers(headers, expected): + response = httpx.Response( + 200, + content=None, + headers=headers, + ) + assert response.links == expected + + +@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br")) +def test_decode_error_with_request(header_value): + headers = [(b"Content-Encoding", header_value)] + broken_compressed_body = b"xxxxxxxxxxxxxx" + with pytest.raises(httpx.DecodingError): + httpx.Response( + 200, + headers=headers, + content=broken_compressed_body, + ) + + with pytest.raises(httpx.DecodingError): + httpx.Response( + 200, + headers=headers, + content=broken_compressed_body, + request=httpx.Request("GET", "https://www.example.org/"), + ) + + +@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br")) +def test_value_error_without_request(header_value): + headers = [(b"Content-Encoding", header_value)] + broken_compressed_body = b"xxxxxxxxxxxxxx" + with pytest.raises(httpx.DecodingError): + httpx.Response(200, headers=headers, content=broken_compressed_body) + + +def test_response_with_unset_request(): + response = httpx.Response(200, content=b"Hello, world!") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert not response.is_error + + +def test_set_request_after_init(): + response = httpx.Response(200, content=b"Hello, world!") + + response.request = httpx.Request("GET", "https://www.example.org") + + assert response.request.method == "GET" + assert response.request.url == "https://www.example.org" + + +def test_cannot_access_unset_request(): + response = httpx.Response(200, content=b"Hello, world!") + + with pytest.raises(RuntimeError): + response.request # noqa: B018 + + +def test_generator_with_transfer_encoding_header(): + def content() -> typing.Iterator[bytes]: + yield b"test 123" # pragma: no cover + + response = httpx.Response(200, content=content()) + assert response.headers == {"Transfer-Encoding": "chunked"} + + +def test_generator_with_content_length_header(): + def content() -> typing.Iterator[bytes]: + yield b"test 123" # pragma: no cover + + headers = {"Content-Length": "8"} + response = httpx.Response(200, content=content(), headers=headers) + assert response.headers == {"Content-Length": "8"} + + +def test_response_picklable(): + response = httpx.Response( + 200, + content=b"Hello, world!", + request=httpx.Request("GET", "https://example.org"), + ) + pickle_response = pickle.loads(pickle.dumps(response)) + assert pickle_response.is_closed is True + assert pickle_response.is_stream_consumed is True + assert pickle_response.next_request is None + assert pickle_response.stream is not None + assert pickle_response.content == b"Hello, world!" + assert pickle_response.status_code == 200 + assert pickle_response.request.url == response.request.url + assert pickle_response.extensions == {} + assert pickle_response.history == [] + + +@pytest.mark.anyio +async def test_response_async_streaming_picklable(): + response = httpx.Response(200, content=async_streaming_body()) + pickle_response = pickle.loads(pickle.dumps(response)) + with pytest.raises(httpx.ResponseNotRead): + pickle_response.content # noqa: B018 + with pytest.raises(httpx.StreamClosed): + await pickle_response.aread() + assert pickle_response.is_stream_consumed is False + assert pickle_response.num_bytes_downloaded == 0 + assert pickle_response.headers == {"Transfer-Encoding": "chunked"} + + response = httpx.Response(200, content=async_streaming_body()) + await response.aread() + pickle_response = pickle.loads(pickle.dumps(response)) + assert pickle_response.is_stream_consumed is True + assert pickle_response.content == b"Hello, world!" + assert pickle_response.num_bytes_downloaded == 13 + + +def test_response_decode_text_using_autodetect(): + # Ensure that a 'default_encoding="autodetect"' on the response allows for + # encoding autodetection to be used when no "Content-Type: text/plain; charset=..." + # info is present. + # + # Here we have some french text encoded with ISO-8859-1, rather than UTF-8. + text = ( + "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains " + "que la France a produits, sans excepter Voltaire lui-même, imprégné de " + "l'esprit anglais par son séjour à Londres, c'est incontestablement " + "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la " + "plus complète le fond du génie français." + ) + content = text.encode("ISO-8859-1") + response = httpx.Response(200, content=content, default_encoding=autodetect) + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.encoding == "ISO-8859-1" + assert response.text == text + + +def test_response_decode_text_using_explicit_encoding(): + # Ensure that a 'default_encoding="..."' on the response is used for text decoding + # when no "Content-Type: text/plain; charset=..."" info is present. + # + # Here we have some french text encoded with Windows-1252, rather than UTF-8. + # https://en.wikipedia.org/wiki/Windows-1252 + text = ( + "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains " + "que la France a produits, sans excepter Voltaire lui-même, imprégné de " + "l'esprit anglais par son séjour à Londres, c'est incontestablement " + "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la " + "plus complète le fond du génie français." + ) + content = text.encode("cp1252") + response = httpx.Response(200, content=content, default_encoding="cp1252") + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.encoding == "cp1252" + assert response.text == text diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_url.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_url.py new file mode 100644 index 0000000000000000000000000000000000000000..03072e8f5cdb5314ceab580c664d0c890949a365 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_url.py @@ -0,0 +1,863 @@ +import pytest + +import httpx + +# Tests for `httpx.URL` instantiation and property accessors. + + +def test_basic_url(): + url = httpx.URL("https://www.example.com/") + + assert url.scheme == "https" + assert url.userinfo == b"" + assert url.netloc == b"www.example.com" + assert url.host == "www.example.com" + assert url.port is None + assert url.path == "/" + assert url.query == b"" + assert url.fragment == "" + + assert str(url) == "https://www.example.com/" + assert repr(url) == "URL('https://www.example.com/')" + + +def test_complete_url(): + url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor") + assert url.scheme == "https" + assert url.host == "example.org" + assert url.port == 123 + assert url.path == "/path/to/somewhere" + assert url.query == b"abc=123" + assert url.raw_path == b"/path/to/somewhere?abc=123" + assert url.fragment == "anchor" + + assert str(url) == "https://example.org:123/path/to/somewhere?abc=123#anchor" + assert ( + repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')" + ) + + +def test_url_with_empty_query(): + """ + URLs with and without a trailing `?` but an empty query component + should preserve the information on the raw path. + """ + url = httpx.URL("https://www.example.com/path") + assert url.path == "/path" + assert url.query == b"" + assert url.raw_path == b"/path" + + url = httpx.URL("https://www.example.com/path?") + assert url.path == "/path" + assert url.query == b"" + assert url.raw_path == b"/path?" + + +def test_url_no_scheme(): + url = httpx.URL("://example.com") + assert url.scheme == "" + assert url.host == "example.com" + assert url.path == "/" + + +def test_url_no_authority(): + url = httpx.URL("http://") + assert url.scheme == "http" + assert url.host == "" + assert url.path == "/" + + +# Tests for percent encoding across path, query, and fragment... + + +@pytest.mark.parametrize( + "url,raw_path,path,query,fragment", + [ + # URL with unescaped chars in path. + ( + "https://example.com/!$&'()*+,;= abc ABC 123 :/[]@", + b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@", + "/!$&'()*+,;= abc ABC 123 :/[]@", + b"", + "", + ), + # URL with escaped chars in path. + ( + "https://example.com/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@", + b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@", + "/!$&'()*+,;= abc ABC 123 :/[]@", + b"", + "", + ), + # URL with mix of unescaped and escaped chars in path. + # WARNING: This has the incorrect behaviour, adding the test as an interim step. + ( + "https://example.com/ %61%62%63", + b"/%20%61%62%63", + "/ abc", + b"", + "", + ), + # URL with unescaped chars in query. + ( + "https://example.com/?!$&'()*+,;= abc ABC 123 :/[]@?", + b"/?!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?", + "/", + b"!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?", + "", + ), + # URL with escaped chars in query. + ( + "https://example.com/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?", + b"/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?", + "/", + b"!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?", + "", + ), + # URL with mix of unescaped and escaped chars in query. + ( + "https://example.com/?%20%97%98%99", + b"/?%20%97%98%99", + "/", + b"%20%97%98%99", + "", + ), + # URL encoding characters in fragment. + ( + "https://example.com/#!$&'()*+,;= abc ABC 123 :/[]@?#", + b"/", + "/", + b"", + "!$&'()*+,;= abc ABC 123 :/[]@?#", + ), + ], +) +def test_path_query_fragment(url, raw_path, path, query, fragment): + url = httpx.URL(url) + assert url.raw_path == raw_path + assert url.path == path + assert url.query == query + assert url.fragment == fragment + + +def test_url_query_encoding(): + url = httpx.URL("https://www.example.com/?a=b c&d=e/f") + assert url.raw_path == b"/?a=b%20c&d=e/f" + + url = httpx.URL("https://www.example.com/?a=b+c&d=e/f") + assert url.raw_path == b"/?a=b+c&d=e/f" + + url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"}) + assert url.raw_path == b"/?a=b+c&d=e%2Ff" + + +def test_url_params(): + url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"}) + assert str(url) == "https://example.org:123/path/to/somewhere?a=123" + assert url.params == httpx.QueryParams({"a": "123"}) + + url = httpx.URL( + "https://example.org:123/path/to/somewhere?b=456", params={"a": "123"} + ) + assert str(url) == "https://example.org:123/path/to/somewhere?a=123" + assert url.params == httpx.QueryParams({"a": "123"}) + + +# Tests for username and password + + +@pytest.mark.parametrize( + "url,userinfo,username,password", + [ + # username and password in URL. + ( + "https://username:password@example.com", + b"username:password", + "username", + "password", + ), + # username and password in URL with percent escape sequences. + ( + "https://username%40gmail.com:pa%20ssword@example.com", + b"username%40gmail.com:pa%20ssword", + "username@gmail.com", + "pa ssword", + ), + ( + "https://user%20name:p%40ssword@example.com", + b"user%20name:p%40ssword", + "user name", + "p@ssword", + ), + # username and password in URL without percent escape sequences. + ( + "https://username@gmail.com:pa ssword@example.com", + b"username%40gmail.com:pa%20ssword", + "username@gmail.com", + "pa ssword", + ), + ( + "https://user name:p@ssword@example.com", + b"user%20name:p%40ssword", + "user name", + "p@ssword", + ), + ], +) +def test_url_username_and_password(url, userinfo, username, password): + url = httpx.URL(url) + assert url.userinfo == userinfo + assert url.username == username + assert url.password == password + + +# Tests for different host types + + +def test_url_valid_host(): + url = httpx.URL("https://example.com/") + assert url.host == "example.com" + + +def test_url_normalized_host(): + url = httpx.URL("https://EXAMPLE.com/") + assert url.host == "example.com" + + +def test_url_percent_escape_host(): + url = httpx.URL("https://exam le.com/") + assert url.host == "exam%20le.com" + + +def test_url_ipv4_like_host(): + """rare host names used to quality as IPv4""" + url = httpx.URL("https://023b76x43144/") + assert url.host == "023b76x43144" + + +# Tests for different port types + + +def test_url_valid_port(): + url = httpx.URL("https://example.com:123/") + assert url.port == 123 + + +def test_url_normalized_port(): + # If the port matches the scheme default it is normalized to None. + url = httpx.URL("https://example.com:443/") + assert url.port is None + + +def test_url_invalid_port(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://example.com:abc/") + assert str(exc.value) == "Invalid port: 'abc'" + + +# Tests for path handling + + +def test_url_normalized_path(): + url = httpx.URL("https://example.com/abc/def/../ghi/./jkl") + assert url.path == "/abc/ghi/jkl" + + +def test_url_escaped_path(): + url = httpx.URL("https://example.com/ /🌟/") + assert url.raw_path == b"/%20/%F0%9F%8C%9F/" + + +def test_url_leading_dot_prefix_on_absolute_url(): + url = httpx.URL("https://example.com/../abc") + assert url.path == "/abc" + + +def test_url_leading_dot_prefix_on_relative_url(): + url = httpx.URL("../abc") + assert url.path == "../abc" + + +# Tests for query parameter percent encoding. +# +# Percent-encoding in `params={}` should match browser form behavior. + + +def test_param_with_space(): + # Params passed as form key-value pairs should be form escaped, + # Including the special case of "+" for space seperators. + url = httpx.URL("http://webservice", params={"u": "with spaces"}) + assert str(url) == "http://webservice?u=with+spaces" + + +def test_param_requires_encoding(): + # Params passed as form key-value pairs should be escaped. + url = httpx.URL("http://webservice", params={"u": "%"}) + assert str(url) == "http://webservice?u=%25" + + +def test_param_with_percent_encoded(): + # Params passed as form key-value pairs should always be escaped, + # even if they include a valid escape sequence. + # We want to match browser form behaviour here. + url = httpx.URL("http://webservice", params={"u": "with%20spaces"}) + assert str(url) == "http://webservice?u=with%2520spaces" + + +def test_param_with_existing_escape_requires_encoding(): + # Params passed as form key-value pairs should always be escaped, + # even if they include a valid escape sequence. + # We want to match browser form behaviour here. + url = httpx.URL("http://webservice", params={"u": "http://example.com?q=foo%2Fa"}) + assert str(url) == "http://webservice?u=http%3A%2F%2Fexample.com%3Fq%3Dfoo%252Fa" + + +# Tests for query parameter percent encoding. +# +# Percent-encoding in `url={}` should match browser URL bar behavior. + + +def test_query_with_existing_percent_encoding(): + # Valid percent encoded sequences should not be double encoded. + url = httpx.URL("http://webservice?u=phrase%20with%20spaces") + assert str(url) == "http://webservice?u=phrase%20with%20spaces" + + +def test_query_requiring_percent_encoding(): + # Characters that require percent encoding should be encoded. + url = httpx.URL("http://webservice?u=phrase with spaces") + assert str(url) == "http://webservice?u=phrase%20with%20spaces" + + +def test_query_with_mixed_percent_encoding(): + # When a mix of encoded and unencoded characters are present, + # characters that require percent encoding should be encoded, + # while existing sequences should not be double encoded. + url = httpx.URL("http://webservice?u=phrase%20with spaces") + assert str(url) == "http://webservice?u=phrase%20with%20spaces" + + +# Tests for invalid URLs + + +def test_url_invalid_hostname(): + """ + Ensure that invalid URLs raise an `httpx.InvalidURL` exception. + """ + with pytest.raises(httpx.InvalidURL): + httpx.URL("https://😇/") + + +def test_url_excessively_long_url(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://www.example.com/" + "x" * 100_000) + assert str(exc.value) == "URL too long" + + +def test_url_excessively_long_component(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://www.example.com", path="/" + "x" * 100_000) + assert str(exc.value) == "URL component 'path' too long" + + +def test_url_non_printing_character_in_url(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://www.example.com/\n") + assert str(exc.value) == ( + "Invalid non-printable ASCII character in URL, '\\n' at position 24." + ) + + +def test_url_non_printing_character_in_component(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://www.example.com", path="/\n") + assert str(exc.value) == ( + "Invalid non-printable ASCII character in URL path component, " + "'\\n' at position 1." + ) + + +# Test for url components + + +def test_url_with_components(): + url = httpx.URL(scheme="https", host="www.example.com", path="/") + + assert url.scheme == "https" + assert url.userinfo == b"" + assert url.host == "www.example.com" + assert url.port is None + assert url.path == "/" + assert url.query == b"" + assert url.fragment == "" + + assert str(url) == "https://www.example.com/" + + +def test_urlparse_with_invalid_component(): + with pytest.raises(TypeError) as exc: + httpx.URL(scheme="https", host="www.example.com", incorrect="/") + assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()" + + +def test_urlparse_with_invalid_scheme(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL(scheme="~", host="www.example.com", path="/") + assert str(exc.value) == "Invalid URL component 'scheme'" + + +def test_urlparse_with_invalid_path(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL(scheme="https", host="www.example.com", path="abc") + assert str(exc.value) == "For absolute URLs, path must be empty or begin with '/'" + + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL(path="//abc") + assert str(exc.value) == "Relative URLs cannot have a path starting with '//'" + + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL(path=":abc") + assert str(exc.value) == "Relative URLs cannot have a path starting with ':'" + + +def test_url_with_relative_path(): + # This path would be invalid for an absolute URL, but is valid as a relative URL. + url = httpx.URL(path="abc") + assert url.path == "abc" + + +# Tests for `httpx.URL` python built-in operators. + + +def test_url_eq_str(): + """ + Ensure that `httpx.URL` supports the equality operator. + """ + url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor") + assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor" + assert str(url) == url + + +def test_url_set(): + """ + Ensure that `httpx.URL` instances can be used in sets. + """ + urls = ( + httpx.URL("http://example.org:123/path/to/somewhere"), + httpx.URL("http://example.org:123/path/to/somewhere/else"), + ) + + url_set = set(urls) + + assert all(url in urls for url in url_set) + + +# Tests for TypeErrors when instantiating `httpx.URL`. + + +def test_url_invalid_type(): + """ + Ensure that invalid types on `httpx.URL()` raise a `TypeError`. + """ + + class ExternalURLClass: # representing external URL class + pass + + with pytest.raises(TypeError): + httpx.URL(ExternalURLClass()) # type: ignore + + +def test_url_with_invalid_component(): + with pytest.raises(TypeError) as exc: + httpx.URL(scheme="https", host="www.example.com", incorrect="/") + assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()" + + +# Tests for `URL.join()`. + + +def test_url_join(): + """ + Some basic URL joining tests. + """ + url = httpx.URL("https://example.org:123/path/to/somewhere") + assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else" + assert ( + url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else" + ) + assert ( + url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else" + ) + assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else" + + +def test_relative_url_join(): + url = httpx.URL("/path/to/somewhere") + assert url.join("/somewhere-else") == "/somewhere-else" + assert url.join("somewhere-else") == "/path/to/somewhere-else" + assert url.join("../somewhere-else") == "/path/somewhere-else" + assert url.join("../../somewhere-else") == "/somewhere-else" + + +def test_url_join_rfc3986(): + """ + URL joining tests, as-per reference examples in RFC 3986. + + https://tools.ietf.org/html/rfc3986#section-5.4 + """ + + url = httpx.URL("http://example.com/b/c/d;p?q") + + assert url.join("g") == "http://example.com/b/c/g" + assert url.join("./g") == "http://example.com/b/c/g" + assert url.join("g/") == "http://example.com/b/c/g/" + assert url.join("/g") == "http://example.com/g" + assert url.join("//g") == "http://g" + assert url.join("?y") == "http://example.com/b/c/d;p?y" + assert url.join("g?y") == "http://example.com/b/c/g?y" + assert url.join("#s") == "http://example.com/b/c/d;p?q#s" + assert url.join("g#s") == "http://example.com/b/c/g#s" + assert url.join("g?y#s") == "http://example.com/b/c/g?y#s" + assert url.join(";x") == "http://example.com/b/c/;x" + assert url.join("g;x") == "http://example.com/b/c/g;x" + assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s" + assert url.join("") == "http://example.com/b/c/d;p?q" + assert url.join(".") == "http://example.com/b/c/" + assert url.join("./") == "http://example.com/b/c/" + assert url.join("..") == "http://example.com/b/" + assert url.join("../") == "http://example.com/b/" + assert url.join("../g") == "http://example.com/b/g" + assert url.join("../..") == "http://example.com/" + assert url.join("../../") == "http://example.com/" + assert url.join("../../g") == "http://example.com/g" + + assert url.join("../../../g") == "http://example.com/g" + assert url.join("../../../../g") == "http://example.com/g" + + assert url.join("/./g") == "http://example.com/g" + assert url.join("/../g") == "http://example.com/g" + assert url.join("g.") == "http://example.com/b/c/g." + assert url.join(".g") == "http://example.com/b/c/.g" + assert url.join("g..") == "http://example.com/b/c/g.." + assert url.join("..g") == "http://example.com/b/c/..g" + + assert url.join("./../g") == "http://example.com/b/g" + assert url.join("./g/.") == "http://example.com/b/c/g/" + assert url.join("g/./h") == "http://example.com/b/c/g/h" + assert url.join("g/../h") == "http://example.com/b/c/h" + assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y" + assert url.join("g;x=1/../y") == "http://example.com/b/c/y" + + assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x" + assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x" + assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x" + assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x" + + +def test_resolution_error_1833(): + """ + See https://github.com/encode/httpx/issues/1833 + """ + url = httpx.URL("https://example.com/?[]") + assert url.join("/") == "https://example.com/" + + +# Tests for `URL.copy_with()`. + + +def test_copy_with(): + url = httpx.URL("https://www.example.com/") + assert str(url) == "https://www.example.com/" + + url = url.copy_with() + assert str(url) == "https://www.example.com/" + + url = url.copy_with(scheme="http") + assert str(url) == "http://www.example.com/" + + url = url.copy_with(netloc=b"example.com") + assert str(url) == "http://example.com/" + + url = url.copy_with(path="/abc") + assert str(url) == "http://example.com/abc" + + +def test_url_copywith_authority_subcomponents(): + copy_with_kwargs = { + "username": "username", + "password": "password", + "port": 444, + "host": "example.net", + } + url = httpx.URL("https://example.org") + new = url.copy_with(**copy_with_kwargs) + assert str(new) == "https://username:password@example.net:444" + + +def test_url_copywith_netloc(): + copy_with_kwargs = { + "netloc": b"example.net:444", + } + url = httpx.URL("https://example.org") + new = url.copy_with(**copy_with_kwargs) + assert str(new) == "https://example.net:444" + + +def test_url_copywith_userinfo_subcomponents(): + copy_with_kwargs = { + "username": "tom@example.org", + "password": "abc123@ %", + } + url = httpx.URL("https://example.org") + new = url.copy_with(**copy_with_kwargs) + assert str(new) == "https://tom%40example.org:abc123%40%20%@example.org" + assert new.username == "tom@example.org" + assert new.password == "abc123@ %" + assert new.userinfo == b"tom%40example.org:abc123%40%20%" + + +def test_url_copywith_invalid_component(): + url = httpx.URL("https://example.org") + with pytest.raises(TypeError): + url.copy_with(pathh="/incorrect-spelling") + with pytest.raises(TypeError): + url.copy_with(userinfo="should be bytes") + + +def test_url_copywith_urlencoded_path(): + url = httpx.URL("https://example.org") + url = url.copy_with(path="/path to somewhere") + assert url.path == "/path to somewhere" + assert url.query == b"" + assert url.raw_path == b"/path%20to%20somewhere" + + +def test_url_copywith_query(): + url = httpx.URL("https://example.org") + url = url.copy_with(query=b"a=123") + assert url.path == "/" + assert url.query == b"a=123" + assert url.raw_path == b"/?a=123" + + +def test_url_copywith_raw_path(): + url = httpx.URL("https://example.org") + url = url.copy_with(raw_path=b"/some/path") + assert url.path == "/some/path" + assert url.query == b"" + assert url.raw_path == b"/some/path" + + url = httpx.URL("https://example.org") + url = url.copy_with(raw_path=b"/some/path?") + assert url.path == "/some/path" + assert url.query == b"" + assert url.raw_path == b"/some/path?" + + url = httpx.URL("https://example.org") + url = url.copy_with(raw_path=b"/some/path?a=123") + assert url.path == "/some/path" + assert url.query == b"a=123" + assert url.raw_path == b"/some/path?a=123" + + +def test_url_copywith_security(): + """ + Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945) + """ + with pytest.raises(httpx.InvalidURL): + httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw") + + url = httpx.URL("https://example.com/path?t=w#tw") + bad = "https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx" + with pytest.raises(httpx.InvalidURL): + url.copy_with(scheme=bad) + + +# Tests for copy-modifying-parameters methods. +# +# `URL.copy_set_param()` +# `URL.copy_add_param()` +# `URL.copy_remove_param()` +# `URL.copy_merge_params()` + + +def test_url_set_param_manipulation(): + """ + Some basic URL query parameter manipulation. + """ + url = httpx.URL("https://example.org:123/?a=123") + assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456" + + +def test_url_add_param_manipulation(): + """ + Some basic URL query parameter manipulation. + """ + url = httpx.URL("https://example.org:123/?a=123") + assert url.copy_add_param("a", "456") == "https://example.org:123/?a=123&a=456" + + +def test_url_remove_param_manipulation(): + """ + Some basic URL query parameter manipulation. + """ + url = httpx.URL("https://example.org:123/?a=123") + assert url.copy_remove_param("a") == "https://example.org:123/" + + +def test_url_merge_params_manipulation(): + """ + Some basic URL query parameter manipulation. + """ + url = httpx.URL("https://example.org:123/?a=123") + assert url.copy_merge_params({"b": "456"}) == "https://example.org:123/?a=123&b=456" + + +# Tests for IDNA hostname support. + + +@pytest.mark.parametrize( + "given,idna,host,raw_host,scheme,port", + [ + ( + "http://中国.icom.museum:80/", + "http://xn--fiqs8s.icom.museum:80/", + "中国.icom.museum", + b"xn--fiqs8s.icom.museum", + "http", + None, + ), + ( + "http://Königsgäßchen.de", + "http://xn--knigsgchen-b4a3dun.de", + "königsgäßchen.de", + b"xn--knigsgchen-b4a3dun.de", + "http", + None, + ), + ( + "https://faß.de", + "https://xn--fa-hia.de", + "faß.de", + b"xn--fa-hia.de", + "https", + None, + ), + ( + "https://βόλος.com:443", + "https://xn--nxasmm1c.com:443", + "βόλος.com", + b"xn--nxasmm1c.com", + "https", + None, + ), + ( + "http://ශ්‍රී.com:444", + "http://xn--10cl1a0b660p.com:444", + "ශ්‍රී.com", + b"xn--10cl1a0b660p.com", + "http", + 444, + ), + ( + "https://نامه‌ای.com:4433", + "https://xn--mgba3gch31f060k.com:4433", + "نامه‌ای.com", + b"xn--mgba3gch31f060k.com", + "https", + 4433, + ), + ], + ids=[ + "http_with_port", + "unicode_tr46_compat", + "https_without_port", + "https_with_port", + "http_with_custom_port", + "https_with_custom_port", + ], +) +def test_idna_url(given, idna, host, raw_host, scheme, port): + url = httpx.URL(given) + assert url == httpx.URL(idna) + assert url.host == host + assert url.raw_host == raw_host + assert url.scheme == scheme + assert url.port == port + + +def test_url_unescaped_idna_host(): + url = httpx.URL("https://中国.icom.museum/") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + +def test_url_escaped_idna_host(): + url = httpx.URL("https://xn--fiqs8s.icom.museum/") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + +def test_url_invalid_idna_host(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://☃.com/") + assert str(exc.value) == "Invalid IDNA hostname: '☃.com'" + + +# Tests for IPv4 hostname support. + + +def test_url_valid_ipv4(): + url = httpx.URL("https://1.2.3.4/") + assert url.host == "1.2.3.4" + + +def test_url_invalid_ipv4(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://999.999.999.999/") + assert str(exc.value) == "Invalid IPv4 address: '999.999.999.999'" + + +# Tests for IPv6 hostname support. + + +def test_ipv6_url(): + url = httpx.URL("http://[::ffff:192.168.0.1]:5678/") + + assert url.host == "::ffff:192.168.0.1" + assert url.netloc == b"[::ffff:192.168.0.1]:5678" + + +def test_url_valid_ipv6(): + url = httpx.URL("https://[2001:db8::ff00:42:8329]/") + assert url.host == "2001:db8::ff00:42:8329" + + +def test_url_invalid_ipv6(): + with pytest.raises(httpx.InvalidURL) as exc: + httpx.URL("https://[2001]/") + assert str(exc.value) == "Invalid IPv6 address: '[2001]'" + + +@pytest.mark.parametrize("host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"]) +def test_ipv6_url_from_raw_url(host): + url = httpx.URL(scheme="https", host=host, port=443, path="/") + + assert url.host == "::ffff:192.168.0.1" + assert url.netloc == b"[::ffff:192.168.0.1]" + assert str(url) == "https://[::ffff:192.168.0.1]/" + + +@pytest.mark.parametrize( + "url_str", + [ + "http://127.0.0.1:1234", + "http://example.com:1234", + "http://[::ffff:127.0.0.1]:1234", + ], +) +@pytest.mark.parametrize("new_host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"]) +def test_ipv6_url_copy_with_host(url_str, new_host): + url = httpx.URL(url_str).copy_with(host=new_host) + + assert url.host == "::ffff:192.168.0.1" + assert url.netloc == b"[::ffff:192.168.0.1]:1234" + assert str(url) == "http://[::ffff:192.168.0.1]:1234" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_whatwg.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_whatwg.py new file mode 100644 index 0000000000000000000000000000000000000000..14af6825868fb55ae2c4cc4c290fcab6b7f3b74d --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/test_whatwg.py @@ -0,0 +1,52 @@ +# The WHATWG have various tests that can be used to validate the URL parsing. +# +# https://url.spec.whatwg.org/ + +import json + +import pytest + +from httpx._urlparse import urlparse + +# URL test cases from... +# https://github.com/web-platform-tests/wpt/blob/master/url/resources/urltestdata.json +with open("tests/models/whatwg.json", "r", encoding="utf-8") as input: + test_cases = json.load(input) + test_cases = [ + item + for item in test_cases + if not isinstance(item, str) and not item.get("failure") + ] + + +@pytest.mark.parametrize("test_case", test_cases) +def test_urlparse(test_case): + if test_case["href"] in ("a: foo.com", "lolscheme:x x#x%20x"): + # Skip these two test cases. + # WHATWG cases where are not using percent-encoding for the space character. + # Anyone know what's going on here? + return + + p = urlparse(test_case["href"]) + + # Test cases include the protocol with the trailing ":" + protocol = p.scheme + ":" + # Include the square brackets for IPv6 addresses. + hostname = f"[{p.host}]" if ":" in p.host else p.host + # The test cases use a string representation of the port. + port = "" if p.port is None else str(p.port) + # I have nothing to say about this one. + path = p.path + # The 'search' and 'hash' components in the whatwg tests are semantic, not literal. + # Our parsing differentiates between no query/hash and empty-string query/hash. + search = "" if p.query in (None, "") else "?" + str(p.query) + hash = "" if p.fragment in (None, "") else "#" + str(p.fragment) + + # URL hostnames are case-insensitive. + # We normalize these, unlike the WHATWG test cases. + assert protocol == test_case["protocol"] + assert hostname.lower() == test_case["hostname"].lower() + assert port == test_case["port"] + assert path == test_case["pathname"] + assert search == test_case["search"] + assert hash == test_case["hash"] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/whatwg.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/whatwg.json new file mode 100644 index 0000000000000000000000000000000000000000..85a5140f8a8109dda5ca34a82871162bc8f70f0b --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/models/whatwg.json @@ -0,0 +1,9746 @@ +[ + "See ../README.md for a description of the format.", + { + "input": "http://example\t.\norg", + "base": "http://example.org/foo/bar", + "href": "http://example.org/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://user:pass@foo:21/bar;par?b#c", + "base": "http://example.org/foo/bar", + "href": "http://user:pass@foo:21/bar;par?b#c", + "origin": "http://foo:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "foo:21", + "hostname": "foo", + "port": "21", + "pathname": "/bar;par", + "search": "?b", + "hash": "#c" + }, + { + "input": "https://test:@test", + "base": null, + "href": "https://test@test/", + "origin": "https://test", + "protocol": "https:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://:@test", + "base": null, + "href": "https://test/", + "origin": "https://test", + "protocol": "https:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://test:@test/x", + "base": null, + "href": "non-special://test@test/x", + "origin": "null", + "protocol": "non-special:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "non-special://:@test/x", + "base": null, + "href": "non-special://test/x", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "http:foo.com", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/foo.com", + "search": "", + "hash": "" + }, + { + "input": "\t :foo.com \n", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com", + "search": "", + "hash": "" + }, + { + "input": " foo.com ", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/foo.com", + "search": "", + "hash": "" + }, + { + "input": "a:\t foo.com", + "base": "http://example.org/foo/bar", + "href": "a: foo.com", + "origin": "null", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": " foo.com", + "search": "", + "hash": "" + }, + { + "input": "http://f:21/ b ? d # e ", + "base": "http://example.org/foo/bar", + "href": "http://f:21/%20b%20?%20d%20#%20e", + "origin": "http://f:21", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:21", + "hostname": "f", + "port": "21", + "pathname": "/%20b%20", + "search": "?%20d%20", + "hash": "#%20e" + }, + { + "input": "lolscheme:x x#x x", + "base": null, + "href": "lolscheme:x x#x%20x", + "protocol": "lolscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "x x", + "search": "", + "hash": "#x%20x" + }, + { + "input": "http://f:/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:0/c", + "base": "http://example.org/foo/bar", + "href": "http://f:0/c", + "origin": "http://f:0", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:0", + "hostname": "f", + "port": "0", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:00000000000000/c", + "base": "http://example.org/foo/bar", + "href": "http://f:0/c", + "origin": "http://f:0", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:0", + "hostname": "f", + "port": "0", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:00000000000000000000080/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:b/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f: /c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f:\n/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:fifty-two/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f:999999/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "non-special://f:999999/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f: 21 / b ? d # e ", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": " \t", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": ":foo.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com/", + "search": "", + "hash": "" + }, + { + "input": ":foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com/", + "search": "", + "hash": "" + }, + { + "input": ":", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:", + "search": "", + "hash": "" + }, + { + "input": ":a", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:a", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:a", + "search": "", + "hash": "" + }, + { + "input": ":/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:/", + "search": "", + "hash": "" + }, + { + "input": ":\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:/", + "search": "", + "hash": "" + }, + { + "input": ":#", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:#", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:", + "search": "", + "hash": "" + }, + { + "input": "#", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "#/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#/" + }, + { + "input": "#\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#\\", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#\\" + }, + { + "input": "#;?", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#;?", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#;?" + }, + { + "input": "?", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar?", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": ":23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:23", + "search": "", + "hash": "" + }, + { + "input": "/:23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/:23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/:23", + "search": "", + "hash": "" + }, + { + "input": "\\x", + "base": "http://example.org/foo/bar", + "href": "http://example.org/x", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "\\\\x\\hello", + "base": "http://example.org/foo/bar", + "href": "http://x/hello", + "origin": "http://x", + "protocol": "http:", + "username": "", + "password": "", + "host": "x", + "hostname": "x", + "port": "", + "pathname": "/hello", + "search": "", + "hash": "" + }, + { + "input": "::", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/::", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/::", + "search": "", + "hash": "" + }, + { + "input": "::23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/::23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/::23", + "search": "", + "hash": "" + }, + { + "input": "foo://", + "base": "http://example.org/foo/bar", + "href": "foo://", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@c:29/d", + "base": "http://example.org/foo/bar", + "href": "http://a:b@c:29/d", + "origin": "http://c:29", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "c:29", + "hostname": "c", + "port": "29", + "pathname": "/d", + "search": "", + "hash": "" + }, + { + "input": "http::@c:29", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:@c:29", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:@c:29", + "search": "", + "hash": "" + }, + { + "input": "http://&a:foo(b]c@d:2/", + "base": "http://example.org/foo/bar", + "href": "http://&a:foo(b%5Dc@d:2/", + "origin": "http://d:2", + "protocol": "http:", + "username": "&a", + "password": "foo(b%5Dc", + "host": "d:2", + "hostname": "d", + "port": "2", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://::@c@d:2", + "base": "http://example.org/foo/bar", + "href": "http://:%3A%40c@d:2/", + "origin": "http://d:2", + "protocol": "http:", + "username": "", + "password": "%3A%40c", + "host": "d:2", + "hostname": "d", + "port": "2", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo.com:b@d/", + "base": "http://example.org/foo/bar", + "href": "http://foo.com:b@d/", + "origin": "http://d", + "protocol": "http:", + "username": "foo.com", + "password": "b", + "host": "d", + "hostname": "d", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo.com/\\@", + "base": "http://example.org/foo/bar", + "href": "http://foo.com//@", + "origin": "http://foo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.com", + "hostname": "foo.com", + "port": "", + "pathname": "//@", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://foo.com/", + "origin": "http://foo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.com", + "hostname": "foo.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\a\\b:c\\d@foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://a/b:c/d@foo.com/", + "origin": "http://a", + "protocol": "http:", + "username": "", + "password": "", + "host": "a", + "hostname": "a", + "port": "", + "pathname": "/b:c/d@foo.com/", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@c\\", + "base": null, + "href": "http://a:b@c/", + "origin": "http://c", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "c", + "hostname": "c", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://a@b\\c", + "base": null, + "href": "ws://a@b/c", + "origin": "ws://b", + "protocol": "ws:", + "username": "a", + "password": "", + "host": "b", + "hostname": "b", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "foo:/", + "base": "http://example.org/foo/bar", + "href": "foo:/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "foo:/bar.com/", + "base": "http://example.org/foo/bar", + "href": "foo:/bar.com/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/bar.com/", + "search": "", + "hash": "" + }, + { + "input": "foo://///////", + "base": "http://example.org/foo/bar", + "href": "foo://///////", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///////", + "search": "", + "hash": "" + }, + { + "input": "foo://///////bar.com/", + "base": "http://example.org/foo/bar", + "href": "foo://///////bar.com/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///////bar.com/", + "search": "", + "hash": "" + }, + { + "input": "foo:////://///", + "base": "http://example.org/foo/bar", + "href": "foo:////://///", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//://///", + "search": "", + "hash": "" + }, + { + "input": "c:/foo", + "base": "http://example.org/foo/bar", + "href": "c:/foo", + "origin": "null", + "protocol": "c:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "//foo/bar", + "base": "http://example.org/foo/bar", + "href": "http://foo/bar", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/bar", + "search": "", + "hash": "" + }, + { + "input": "http://foo/path;a??e#f#g", + "base": "http://example.org/foo/bar", + "href": "http://foo/path;a??e#f#g", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/path;a", + "search": "??e", + "hash": "#f#g" + }, + { + "input": "http://foo/abcd?efgh?ijkl", + "base": "http://example.org/foo/bar", + "href": "http://foo/abcd?efgh?ijkl", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/abcd", + "search": "?efgh?ijkl", + "hash": "" + }, + { + "input": "http://foo/abcd#foo?bar", + "base": "http://example.org/foo/bar", + "href": "http://foo/abcd#foo?bar", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/abcd", + "search": "", + "hash": "#foo?bar" + }, + { + "input": "[61:24:74]:98", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/[61:24:74]:98", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/[61:24:74]:98", + "search": "", + "hash": "" + }, + { + "input": "http:[61:27]/:foo", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/[61:27]/:foo", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/[61:27]/:foo", + "search": "", + "hash": "" + }, + { + "input": "http://[1::2]:3:4", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1]", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1]:80", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://[2001::1]", + "base": "http://example.org/foo/bar", + "href": "http://[2001::1]/", + "origin": "http://[2001::1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[2001::1]", + "hostname": "[2001::1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[::127.0.0.1]", + "base": "http://example.org/foo/bar", + "href": "http://[::7f00:1]/", + "origin": "http://[::7f00:1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[::7f00:1]", + "hostname": "[::7f00:1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[::127.0.0.1.]", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://[0:0:0:0:0:0:13.1.68.3]", + "base": "http://example.org/foo/bar", + "href": "http://[::d01:4403]/", + "origin": "http://[::d01:4403]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[::d01:4403]", + "hostname": "[::d01:4403]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[2001::1]:80", + "base": "http://example.org/foo/bar", + "href": "http://[2001::1]/", + "origin": "http://[2001::1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[2001::1]", + "hostname": "[2001::1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/example.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/example.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftp:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:/example.com/", + "base": "http://example.org/foo/bar", + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:/example.com/", + "base": "http://example.org/foo/bar", + "href": "madeupscheme:/example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file:/example.com/", + "base": "http://example.org/foo/bar", + "href": "file:///example.com/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file://example:1/", + "base": null, + "failure": true + }, + { + "input": "file://example:test/", + "base": null, + "failure": true + }, + { + "input": "file://example%/", + "base": null, + "failure": true + }, + { + "input": "file://[example]/", + "base": null, + "failure": true + }, + { + "input": "ftps:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ftps:/example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:/example.com/", + "base": "http://example.org/foo/bar", + "href": "gopher:/example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:/example.com/", + "base": "http://example.org/foo/bar", + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/example.com/", + "base": "http://example.org/foo/bar", + "href": "data:/example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/example.com/", + "base": "http://example.org/foo/bar", + "href": "javascript:/example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/example.com/", + "base": "http://example.org/foo/bar", + "href": "mailto:/example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "http:example.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/example.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftp:example.com/", + "base": "http://example.org/foo/bar", + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:example.com/", + "base": "http://example.org/foo/bar", + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:example.com/", + "base": "http://example.org/foo/bar", + "href": "madeupscheme:example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:example.com/", + "base": "http://example.org/foo/bar", + "href": "ftps:example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:example.com/", + "base": "http://example.org/foo/bar", + "href": "gopher:example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:example.com/", + "base": "http://example.org/foo/bar", + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:example.com/", + "base": "http://example.org/foo/bar", + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:example.com/", + "base": "http://example.org/foo/bar", + "href": "data:example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:example.com/", + "base": "http://example.org/foo/bar", + "href": "javascript:example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:example.com/", + "base": "http://example.org/foo/bar", + "href": "mailto:example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "/a/b/c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/b/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/b/c", + "search": "", + "hash": "" + }, + { + "input": "/a/ /c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/%20/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/%20/c", + "search": "", + "hash": "" + }, + { + "input": "/a%2fc", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a%2fc", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a%2fc", + "search": "", + "hash": "" + }, + { + "input": "/a/%2f/c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/%2f/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/%2f/c", + "search": "", + "hash": "" + }, + { + "input": "#β", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#%CE%B2", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#%CE%B2" + }, + { + "input": "data:text/html,test#test", + "base": "http://example.org/foo/bar", + "href": "data:text/html,test#test", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "text/html,test", + "search": "", + "hash": "#test" + }, + { + "input": "tel:1234567890", + "base": "http://example.org/foo/bar", + "href": "tel:1234567890", + "origin": "null", + "protocol": "tel:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "1234567890", + "search": "", + "hash": "" + }, + "# Based on https://felixfbecker.github.io/whatwg-url-custom-host-repro/", + { + "input": "ssh://example.com/foo/bar.git", + "base": "http://example.org/", + "href": "ssh://example.com/foo/bar.git", + "origin": "null", + "protocol": "ssh:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/bar.git", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/file.html", + { + "input": "file:c:\\foo\\bar.html", + "base": "file:///tmp/mock/path", + "href": "file:///c:/foo/bar.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar.html", + "search": "", + "hash": "" + }, + { + "input": " File:c|////foo\\bar.html", + "base": "file:///tmp/mock/path", + "href": "file:///c:////foo/bar.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:////foo/bar.html", + "search": "", + "hash": "" + }, + { + "input": "C|/foo/bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/C|\\foo\\bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "//C|/foo/bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "//server/file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "\\\\server\\file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "/\\server/file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "file:///foo/bar.txt", + "base": "file:///tmp/mock/path", + "href": "file:///foo/bar.txt", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/foo/bar.txt", + "search": "", + "hash": "" + }, + { + "input": "file:///home/me", + "base": "file:///tmp/mock/path", + "href": "file:///home/me", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/home/me", + "search": "", + "hash": "" + }, + { + "input": "//", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///test", + "base": "file:///tmp/mock/path", + "href": "file:///test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "file://test", + "base": "file:///tmp/mock/path", + "href": "file://test/", + "protocol": "file:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost/", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost/test", + "base": "file:///tmp/mock/path", + "href": "file:///test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "test", + "base": "file:///tmp/mock/path", + "href": "file:///tmp/mock/test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/tmp/mock/test", + "search": "", + "hash": "" + }, + { + "input": "file:test", + "base": "file:///tmp/mock/path", + "href": "file:///tmp/mock/test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/tmp/mock/test", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/path.js", + { + "input": "http://example.com/././foo", + "base": null, + "href": "http://example.com/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/./.foo", + "base": null, + "href": "http://example.com/.foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/.foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/.", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/./", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/..", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/..bar", + "base": null, + "href": "http://example.com/foo/..bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/..bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../ton", + "base": null, + "href": "http://example.com/foo/ton", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/ton", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../ton/../../a", + "base": null, + "href": "http://example.com/a", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/../../..", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/../../../ton", + "base": null, + "href": "http://example.com/ton", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/ton", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e%2", + "base": null, + "href": "http://example.com/foo/%2e%2", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/%2e%2", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e./%2e%2e/.%2e/%2e.bar", + "base": null, + "href": "http://example.com/%2e.bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%2e.bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com////../..", + "base": null, + "href": "http://example.com//", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar//../..", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar//..", + "base": null, + "href": "http://example.com/foo/bar/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/bar/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo", + "base": null, + "href": "http://example.com/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%20foo", + "base": null, + "href": "http://example.com/%20foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%20foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%", + "base": null, + "href": "http://example.com/foo%", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2", + "base": null, + "href": "http://example.com/foo%2", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2zbar", + "base": null, + "href": "http://example.com/foo%2zbar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2zbar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2©zbar", + "base": null, + "href": "http://example.com/foo%2%C3%82%C2%A9zbar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2%C3%82%C2%A9zbar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%41%7a", + "base": null, + "href": "http://example.com/foo%41%7a", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%41%7a", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo\t\u0091%91", + "base": null, + "href": "http://example.com/foo%C2%91%91", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%C2%91%91", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%00%51", + "base": null, + "href": "http://example.com/foo%00%51", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%00%51", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/(%28:%3A%29)", + "base": null, + "href": "http://example.com/(%28:%3A%29)", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/(%28:%3A%29)", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%3A%3a%3C%3c", + "base": null, + "href": "http://example.com/%3A%3a%3C%3c", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%3A%3a%3C%3c", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo\tbar", + "base": null, + "href": "http://example.com/foobar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foobar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com\\\\foo\\\\bar", + "base": null, + "href": "http://example.com//foo//bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "//foo//bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd", + "base": null, + "href": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%7Ffp3%3Eju%3Dduvgw%3Dd", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/@asdf%40", + "base": null, + "href": "http://example.com/@asdf%40", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/@asdf%40", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/你好你好", + "base": null, + "href": "http://example.com/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/‥/foo", + "base": null, + "href": "http://example.com/%E2%80%A5/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E2%80%A5/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com//foo", + "base": null, + "href": "http://example.com/%EF%BB%BF/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%EF%BB%BF/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/‮/foo/‭/bar", + "base": null, + "href": "http://example.com/%E2%80%AE/foo/%E2%80%AD/bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E2%80%AE/foo/%E2%80%AD/bar", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/relative.js", + { + "input": "http://www.google.com/foo?bar=baz#", + "base": null, + "href": "http://www.google.com/foo?bar=baz#", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "?bar=baz", + "hash": "" + }, + { + "input": "http://www.google.com/foo?bar=baz# »", + "base": null, + "href": "http://www.google.com/foo?bar=baz#%20%C2%BB", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "?bar=baz", + "hash": "#%20%C2%BB" + }, + { + "input": "data:test# »", + "base": null, + "href": "data:test#%20%C2%BB", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "", + "hash": "#%20%C2%BB" + }, + { + "input": "http://www.google.com", + "base": null, + "href": "http://www.google.com/", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.0x00A80001", + "base": null, + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://www/foo%2Ehtml", + "base": null, + "href": "http://www/foo%2Ehtml", + "origin": "http://www", + "protocol": "http:", + "username": "", + "password": "", + "host": "www", + "hostname": "www", + "port": "", + "pathname": "/foo%2Ehtml", + "search": "", + "hash": "" + }, + { + "input": "http://www/foo/%2E/html", + "base": null, + "href": "http://www/foo/html", + "origin": "http://www", + "protocol": "http:", + "username": "", + "password": "", + "host": "www", + "hostname": "www", + "port": "", + "pathname": "/foo/html", + "search": "", + "hash": "" + }, + { + "input": "http://user:pass@/", + "base": null, + "failure": true + }, + { + "input": "http://%25DOMAIN:foobar@foodomain.com/", + "base": null, + "href": "http://%25DOMAIN:foobar@foodomain.com/", + "origin": "http://foodomain.com", + "protocol": "http:", + "username": "%25DOMAIN", + "password": "foobar", + "host": "foodomain.com", + "hostname": "foodomain.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\www.google.com\\foo", + "base": null, + "href": "http://www.google.com/foo", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://foo:80/", + "base": null, + "href": "http://foo/", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo:81/", + "base": null, + "href": "http://foo:81/", + "origin": "http://foo:81", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "httpa://foo:80/", + "base": null, + "href": "httpa://foo:80/", + "origin": "null", + "protocol": "httpa:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo:-80/", + "base": null, + "failure": true + }, + { + "input": "https://foo:443/", + "base": null, + "href": "https://foo/", + "origin": "https://foo", + "protocol": "https:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://foo:80/", + "base": null, + "href": "https://foo:80/", + "origin": "https://foo:80", + "protocol": "https:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp://foo:21/", + "base": null, + "href": "ftp://foo/", + "origin": "ftp://foo", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp://foo:80/", + "base": null, + "href": "ftp://foo:80/", + "origin": "ftp://foo:80", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "gopher://foo:70/", + "base": null, + "href": "gopher://foo:70/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "foo:70", + "hostname": "foo", + "port": "70", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "gopher://foo:443/", + "base": null, + "href": "gopher://foo:443/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "foo:443", + "hostname": "foo", + "port": "443", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:80/", + "base": null, + "href": "ws://foo/", + "origin": "ws://foo", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:81/", + "base": null, + "href": "ws://foo:81/", + "origin": "ws://foo:81", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:443/", + "base": null, + "href": "ws://foo:443/", + "origin": "ws://foo:443", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:443", + "hostname": "foo", + "port": "443", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:815/", + "base": null, + "href": "ws://foo:815/", + "origin": "ws://foo:815", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:815", + "hostname": "foo", + "port": "815", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:80/", + "base": null, + "href": "wss://foo:80/", + "origin": "wss://foo:80", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:81/", + "base": null, + "href": "wss://foo:81/", + "origin": "wss://foo:81", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:443/", + "base": null, + "href": "wss://foo/", + "origin": "wss://foo", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:815/", + "base": null, + "href": "wss://foo:815/", + "origin": "wss://foo:815", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:815", + "hostname": "foo", + "port": "815", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/example.com/", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp:/example.com/", + "base": null, + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:/example.com/", + "base": null, + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:/example.com/", + "base": null, + "href": "madeupscheme:/example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file:/example.com/", + "base": null, + "href": "file:///example.com/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:/example.com/", + "base": null, + "href": "ftps:/example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:/example.com/", + "base": null, + "href": "gopher:/example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:/example.com/", + "base": null, + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:/example.com/", + "base": null, + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/example.com/", + "base": null, + "href": "data:/example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/example.com/", + "base": null, + "href": "javascript:/example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/example.com/", + "base": null, + "href": "mailto:/example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "http:example.com/", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp:example.com/", + "base": null, + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:example.com/", + "base": null, + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:example.com/", + "base": null, + "href": "madeupscheme:example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:example.com/", + "base": null, + "href": "ftps:example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:example.com/", + "base": null, + "href": "gopher:example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:example.com/", + "base": null, + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:example.com/", + "base": null, + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:example.com/", + "base": null, + "href": "data:example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:example.com/", + "base": null, + "href": "javascript:example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:example.com/", + "base": null, + "href": "mailto:example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/segments-userinfo-vs-host.html", + { + "input": "http:@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://@pple.com", + "base": null, + "href": "http://pple.com/", + "origin": "http://pple.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "pple.com", + "hostname": "pple.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http::b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/:b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://:b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://user@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "http:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "https:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:a:b@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/a:b@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://a:b@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "http::@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://www.@pple.com", + "base": null, + "href": "http://www.@pple.com/", + "origin": "http://pple.com", + "protocol": "http:", + "username": "www.", + "password": "", + "host": "pple.com", + "hostname": "pple.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:@:www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/@:www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://@:www.example.com", + "base": null, + "failure": true + }, + { + "input": "http://:@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Others", + { + "input": "/", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": ".", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "./test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../aaa/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/aaa/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/aaa/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../../test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "中/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/%E4%B8%AD/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/%E4%B8%AD/test.txt", + "search": "", + "hash": "" + }, + { + "input": "http://www.example2.com", + "base": "http://www.example.com/test", + "href": "http://www.example2.com/", + "origin": "http://www.example2.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example2.com", + "hostname": "www.example2.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "//www.example2.com", + "base": "http://www.example.com/test", + "href": "http://www.example2.com/", + "origin": "http://www.example2.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example2.com", + "hostname": "www.example2.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:...", + "base": "http://www.example.com/test", + "href": "file:///...", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/...", + "search": "", + "hash": "" + }, + { + "input": "file:..", + "base": "http://www.example.com/test", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:a", + "base": "http://www.example.com/test", + "href": "file:///a", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "file:.", + "base": null, + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:.", + "base": "http://www.example.com/test", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/host.html", + "Basic canonicalization, uppercase should be converted to lowercase", + { + "input": "http://ExAmPlE.CoM", + "base": "http://other.com/", + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://example example.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://Goo%20 goo%7C|.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[:]", + "base": "http://other.com/", + "failure": true + }, + "U+3000 is mapped to U+0020 (space) which is disallowed", + { + "input": "http://GOO\u00a0\u3000goo.com", + "base": "http://other.com/", + "failure": true + }, + "Other types of space (no-break, zero-width, zero-width-no-break) are name-prepped away to nothing. U+200B, U+2060, and U+FEFF, are ignored", + { + "input": "http://GOO\u200b\u2060\ufeffgoo.com", + "base": "http://other.com/", + "href": "http://googoo.com/", + "origin": "http://googoo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "googoo.com", + "hostname": "googoo.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Leading and trailing C0 control or space", + { + "input": "\u0000\u001b\u0004\u0012 http://example.com/\u001f \u000d ", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Ideographic full stop (full-width period for Chinese, etc.) should be treated as a dot. U+3002 is mapped to U+002E (dot)", + { + "input": "http://www.foo。bar.com", + "base": "http://other.com/", + "href": "http://www.foo.bar.com/", + "origin": "http://www.foo.bar.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.foo.bar.com", + "hostname": "www.foo.bar.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid unicode characters should fail... U+FDD0 is disallowed; %ef%b7%90 is U+FDD0", + { + "input": "http://\ufdd0zyx.com", + "base": "http://other.com/", + "failure": true + }, + "This is the same as previous but escaped", + { + "input": "http://%ef%b7%90zyx.com", + "base": "http://other.com/", + "failure": true + }, + "U+FFFD", + { + "input": "https://\ufffd", + "base": null, + "failure": true + }, + { + "input": "https://%EF%BF%BD", + "base": null, + "failure": true + }, + { + "input": "https://x/\ufffd?\ufffd#\ufffd", + "base": null, + "href": "https://x/%EF%BF%BD?%EF%BF%BD#%EF%BF%BD", + "origin": "https://x", + "protocol": "https:", + "username": "", + "password": "", + "host": "x", + "hostname": "x", + "port": "", + "pathname": "/%EF%BF%BD", + "search": "?%EF%BF%BD", + "hash": "#%EF%BF%BD" + }, + "Domain is ASCII, but a label is invalid IDNA", + { + "input": "http://a.b.c.xn--pokxncvks", + "base": null, + "failure": true + }, + { + "input": "http://10.0.0.xn--pokxncvks", + "base": null, + "failure": true + }, + "IDNA labels should be matched case-insensitively", + { + "input": "http://a.b.c.XN--pokxncvks", + "base": null, + "failure": true + }, + { + "input": "http://a.b.c.Xn--pokxncvks", + "base": null, + "failure": true + }, + { + "input": "http://10.0.0.XN--pokxncvks", + "base": null, + "failure": true + }, + { + "input": "http://10.0.0.xN--pokxncvks", + "base": null, + "failure": true + }, + "Test name prepping, fullwidth input should be converted to ASCII and NOT IDN-ized. This is 'Go' in fullwidth UTF-8/UTF-16.", + { + "input": "http://Go.com", + "base": "http://other.com/", + "href": "http://go.com/", + "origin": "http://go.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "go.com", + "hostname": "go.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "URL spec forbids the following. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24257", + { + "input": "http://%41.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%ef%bc%85%ef%bc%94%ef%bc%91.com", + "base": "http://other.com/", + "failure": true + }, + "...%00 in fullwidth should fail (also as escaped UTF-8 input)", + { + "input": "http://%00.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%ef%bc%85%ef%bc%90%ef%bc%90.com", + "base": "http://other.com/", + "failure": true + }, + "Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN", + { + "input": "http://你好你好", + "base": "http://other.com/", + "href": "http://xn--6qqa088eba/", + "origin": "http://xn--6qqa088eba", + "protocol": "http:", + "username": "", + "password": "", + "host": "xn--6qqa088eba", + "hostname": "xn--6qqa088eba", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://faß.ExAmPlE/", + "base": null, + "href": "https://xn--fa-hia.example/", + "origin": "https://xn--fa-hia.example", + "protocol": "https:", + "username": "", + "password": "", + "host": "xn--fa-hia.example", + "hostname": "xn--fa-hia.example", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://faß.ExAmPlE/", + "base": null, + "href": "sc://fa%C3%9F.ExAmPlE/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "fa%C3%9F.ExAmPlE", + "hostname": "fa%C3%9F.ExAmPlE", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid escaped characters should fail and the percents should be escaped. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24191", + { + "input": "http://%zz%66%a.com", + "base": "http://other.com/", + "failure": true + }, + "If we get an invalid character that has been escaped.", + { + "input": "http://%25", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://hello%00", + "base": "http://other.com/", + "failure": true + }, + "Escaped numbers should be treated like IP addresses if they are.", + { + "input": "http://%30%78%63%30%2e%30%32%35%30.01", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://%30%78%63%30%2e%30%32%35%30.01%2e", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.0.257", + "base": "http://other.com/", + "failure": true + }, + "Invalid escaping in hosts causes failure", + { + "input": "http://%3g%78%63%30%2e%30%32%35%30%2E.01", + "base": "http://other.com/", + "failure": true + }, + "A space in a host causes failure", + { + "input": "http://192.168.0.1 hello", + "base": "http://other.com/", + "failure": true + }, + { + "input": "https://x x:12", + "base": null, + "failure": true + }, + "Fullwidth and escaped UTF-8 fullwidth should still be treated as IP", + { + "input": "http://0Xc0.0250.01", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Domains with empty labels", + { + "input": "http://./", + "base": null, + "href": "http://./", + "origin": "http://.", + "protocol": "http:", + "username": "", + "password": "", + "host": ".", + "hostname": ".", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://../", + "base": null, + "href": "http://../", + "origin": "http://..", + "protocol": "http:", + "username": "", + "password": "", + "host": "..", + "hostname": "..", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Non-special domains with empty labels", + { + "input": "h://.", + "base": null, + "href": "h://.", + "origin": "null", + "protocol": "h:", + "username": "", + "password": "", + "host": ".", + "hostname": ".", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + "Broken IPv6", + { + "input": "http://[www.google.com]/", + "base": null, + "failure": true + }, + { + "input": "http://[google.com]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.3.4x]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.3.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::.1.2]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::.1]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::%31]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%5B::1]", + "base": "http://other.com/", + "failure": true + }, + "Misc Unicode", + { + "input": "http://foo:💩@example.com/bar", + "base": "http://other.com/", + "href": "http://foo:%F0%9F%92%A9@example.com/bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "foo", + "password": "%F0%9F%92%A9", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/bar", + "search": "", + "hash": "" + }, + "# resolving a fragment against any scheme succeeds", + { + "input": "#", + "base": "test:test", + "href": "test:test#", + "origin": "null", + "protocol": "test:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "", + "hash": "" + }, + { + "input": "#x", + "base": "mailto:x@x.com", + "href": "mailto:x@x.com#x", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "x@x.com", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "data:,", + "href": "data:,#x", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": ",", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "about:blank", + "href": "about:blank#x", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#x" + }, + { + "input": "#x:y", + "base": "about:blank", + "href": "about:blank#x:y", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#x:y" + }, + { + "input": "#", + "base": "test:test?test", + "href": "test:test?test#", + "origin": "null", + "protocol": "test:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "?test", + "hash": "" + }, + "# multiple @ in authority state", + { + "input": "https://@test@test@example:800/", + "base": "http://doesnotmatter/", + "href": "https://%40test%40test@example:800/", + "origin": "https://example:800", + "protocol": "https:", + "username": "%40test%40test", + "password": "", + "host": "example:800", + "hostname": "example", + "port": "800", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://@@@example", + "base": "http://doesnotmatter/", + "href": "https://%40%40@example/", + "origin": "https://example", + "protocol": "https:", + "username": "%40%40", + "password": "", + "host": "example", + "hostname": "example", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "non-az-09 characters", + { + "input": "http://`{}:`{}@h/`{}?`{}", + "base": "http://doesnotmatter/", + "href": "http://%60%7B%7D:%60%7B%7D@h/%60%7B%7D?`{}", + "origin": "http://h", + "protocol": "http:", + "username": "%60%7B%7D", + "password": "%60%7B%7D", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/%60%7B%7D", + "search": "?`{}", + "hash": "" + }, + "byte is ' and url is special", + { + "input": "http://host/?'", + "base": null, + "href": "http://host/?%27", + "origin": "http://host", + "protocol": "http:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "?%27", + "hash": "" + }, + { + "input": "notspecial://host/?'", + "base": null, + "href": "notspecial://host/?'", + "origin": "null", + "protocol": "notspecial:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "?'", + "hash": "" + }, + "# Credentials in base", + { + "input": "/some/path", + "base": "http://user@example.org/smth", + "href": "http://user@example.org/some/path", + "origin": "http://example.org", + "protocol": "http:", + "username": "user", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/some/path", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "http://user:pass@example.org:21/smth", + "href": "http://user:pass@example.org:21/smth", + "origin": "http://example.org:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "example.org:21", + "hostname": "example.org", + "port": "21", + "pathname": "/smth", + "search": "", + "hash": "" + }, + { + "input": "/some/path", + "base": "http://user:pass@example.org:21/smth", + "href": "http://user:pass@example.org:21/some/path", + "origin": "http://example.org:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "example.org:21", + "hostname": "example.org", + "port": "21", + "pathname": "/some/path", + "search": "", + "hash": "" + }, + "# a set of tests designed by zcorpan for relative URLs with unknown schemes", + { + "input": "i", + "base": "sc:sd", + "failure": true + }, + { + "input": "i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "i", + "base": "sc:/pa/pa", + "href": "sc:/pa/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/i", + "search": "", + "hash": "" + }, + { + "input": "i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "i", + "base": "sc:///pa/pa", + "href": "sc:///pa/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc:sd", + "failure": true + }, + { + "input": "../i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "../i", + "base": "sc:/pa/pa", + "href": "sc:/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc:///pa/pa", + "href": "sc:///i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc:sd", + "failure": true + }, + { + "input": "/i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "/i", + "base": "sc:/pa/pa", + "href": "sc:/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc:///pa/pa", + "href": "sc:///i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "?i", + "base": "sc:sd", + "failure": true + }, + { + "input": "?i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "?i", + "base": "sc:/pa/pa", + "href": "sc:/pa/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "?i", + "hash": "" + }, + { + "input": "?i", + "base": "sc://ho/pa", + "href": "sc://ho/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/pa", + "search": "?i", + "hash": "" + }, + { + "input": "?i", + "base": "sc:///pa/pa", + "href": "sc:///pa/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "?i", + "hash": "" + }, + { + "input": "#i", + "base": "sc:sd", + "href": "sc:sd#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "sd", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:sd/sd", + "href": "sc:sd/sd#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "sd/sd", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:/pa/pa", + "href": "sc:/pa/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc://ho/pa", + "href": "sc://ho/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/pa", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:///pa/pa", + "href": "sc:///pa/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "", + "hash": "#i" + }, + "# make sure that relative URL logic works on known typically non-relative schemes too", + { + "input": "about:/../", + "base": null, + "href": "about:/", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/../", + "base": null, + "href": "data:/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/../", + "base": null, + "href": "javascript:/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/../", + "base": null, + "href": "mailto:/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# unknown schemes and their hosts", + { + "input": "sc://ñ.test/", + "base": null, + "href": "sc://%C3%B1.test/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1.test", + "hostname": "%C3%B1.test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://%/", + "base": null, + "href": "sc://%/", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%", + "hostname": "%", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://@/", + "base": null, + "failure": true + }, + { + "input": "sc://te@s:t@/", + "base": null, + "failure": true + }, + { + "input": "sc://:/", + "base": null, + "failure": true + }, + { + "input": "sc://:12/", + "base": null, + "failure": true + }, + { + "input": "x", + "base": "sc://ñ", + "href": "sc://%C3%B1/x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + "# unknown schemes and backslashes", + { + "input": "sc:\\../", + "base": null, + "href": "sc:\\../", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\../", + "search": "", + "hash": "" + }, + "# unknown scheme with path looking like a password", + { + "input": "sc::a@example.net", + "base": null, + "href": "sc::a@example.net", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": ":a@example.net", + "search": "", + "hash": "" + }, + "# unknown scheme with bogus percent-encoding", + { + "input": "wow:%NBD", + "base": null, + "href": "wow:%NBD", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%NBD", + "search": "", + "hash": "" + }, + { + "input": "wow:%1G", + "base": null, + "href": "wow:%1G", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%1G", + "search": "", + "hash": "" + }, + "# unknown scheme with non-URL characters", + { + "input": "wow:\uFFFF", + "base": null, + "href": "wow:%EF%BF%BF", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%EF%BF%BF", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/\uD800\uD801\uDFFE\uDFFF\uFDD0\uFDCF\uFDEF\uFDF0\uFFFE\uFFFF?\uD800\uD801\uDFFE\uDFFF\uFDD0\uFDCF\uFDEF\uFDF0\uFFFE\uFFFF", + "base": null, + "href": "http://example.com/%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF?%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "search": "?%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "hash": "" + }, + "Forbidden host code points", + { + "input": "sc://a\u0000b/", + "base": null, + "failure": true + }, + { + "input": "sc://a b/", + "base": null, + "failure": true + }, + { + "input": "sc://ab", + "base": null, + "failure": true + }, + { + "input": "sc://a[b/", + "base": null, + "failure": true + }, + { + "input": "sc://a\\b/", + "base": null, + "failure": true + }, + { + "input": "sc://a]b/", + "base": null, + "failure": true + }, + { + "input": "sc://a^b", + "base": null, + "failure": true + }, + { + "input": "sc://a|b/", + "base": null, + "failure": true + }, + "Forbidden host codepoints: tabs and newlines are removed during preprocessing", + { + "input": "foo://ho\u0009st/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "foo://ho\u000Ast/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "foo://ho\u000Dst/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + "Forbidden domain code-points", + { + "input": "http://a\u0000b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0001b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0002b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0003b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0004b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0005b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0006b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0007b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0008b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Bb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Cb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Eb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Fb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0010b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0011b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0012b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0013b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0014b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0015b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0016b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0017b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0018b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0019b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Ab/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Bb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Cb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Db/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Eb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Fb/", + "base": null, + "failure": true + }, + { + "input": "http://a b/", + "base": null, + "failure": true + }, + { + "input": "http://a%b/", + "base": null, + "failure": true + }, + { + "input": "http://ab", + "base": null, + "failure": true + }, + { + "input": "http://a[b/", + "base": null, + "failure": true + }, + { + "input": "http://a]b/", + "base": null, + "failure": true + }, + { + "input": "http://a^b", + "base": null, + "failure": true + }, + { + "input": "http://a|b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u007Fb/", + "base": null, + "failure": true + }, + "Forbidden domain codepoints: tabs and newlines are removed during preprocessing", + { + "input": "http://ho\u0009st/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://ho\u000Ast/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://ho\u000Dst/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + "Encoded forbidden domain codepoints in special URLs", + { + "input": "http://ho%00st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%01st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%02st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%03st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%04st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%05st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%06st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%07st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%08st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%09st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%10st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%11st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%12st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%13st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%14st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%15st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%16st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%17st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%18st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%19st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%20st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%23st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%25st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%2Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%40st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%7Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%7Fst/", + "base": null, + "failure": true + }, + "Allowed host/domain code points", + { + "input": "http://!\"$&'()*+,-.;=_`{}~/", + "base": null, + "href": "http://!\"$&'()*+,-.;=_`{}~/", + "origin": "http://!\"$&'()*+,-.;=_`{}~", + "protocol": "http:", + "username": "", + "password": "", + "host": "!\"$&'()*+,-.;=_`{}~", + "hostname": "!\"$&'()*+,-.;=_`{}~", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u000B\u000C\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\u007F!\"$%&'()*+,-.;=_`{}~/", + "base": null, + "href": "sc://%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~", + "hostname": "%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Hosts and percent-encoding", + { + "input": "ftp://example.com%80/", + "base": null, + "failure": true + }, + { + "input": "ftp://example.com%A0/", + "base": null, + "failure": true + }, + { + "input": "https://example.com%80/", + "base": null, + "failure": true + }, + { + "input": "https://example.com%A0/", + "base": null, + "failure": true + }, + { + "input": "ftp://%e2%98%83", + "base": null, + "href": "ftp://xn--n3h/", + "origin": "ftp://xn--n3h", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "xn--n3h", + "hostname": "xn--n3h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://%e2%98%83", + "base": null, + "href": "https://xn--n3h/", + "origin": "https://xn--n3h", + "protocol": "https:", + "username": "", + "password": "", + "host": "xn--n3h", + "hostname": "xn--n3h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# tests from jsdom/whatwg-url designed for code coverage", + { + "input": "http://127.0.0.1:10100/relative_import.html", + "base": null, + "href": "http://127.0.0.1:10100/relative_import.html", + "origin": "http://127.0.0.1:10100", + "protocol": "http:", + "username": "", + "password": "", + "host": "127.0.0.1:10100", + "hostname": "127.0.0.1", + "port": "10100", + "pathname": "/relative_import.html", + "search": "", + "hash": "" + }, + { + "input": "http://facebook.com/?foo=%7B%22abc%22", + "base": null, + "href": "http://facebook.com/?foo=%7B%22abc%22", + "origin": "http://facebook.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "facebook.com", + "hostname": "facebook.com", + "port": "", + "pathname": "/", + "search": "?foo=%7B%22abc%22", + "hash": "" + }, + { + "input": "https://localhost:3000/jqueryui@1.2.3", + "base": null, + "href": "https://localhost:3000/jqueryui@1.2.3", + "origin": "https://localhost:3000", + "protocol": "https:", + "username": "", + "password": "", + "host": "localhost:3000", + "hostname": "localhost", + "port": "3000", + "pathname": "/jqueryui@1.2.3", + "search": "", + "hash": "" + }, + "# tab/LF/CR", + { + "input": "h\tt\nt\rp://h\to\ns\rt:9\t0\n0\r0/p\ta\nt\rh?q\tu\ne\rry#f\tr\na\rg", + "base": null, + "href": "http://host:9000/path?query#frag", + "origin": "http://host:9000", + "protocol": "http:", + "username": "", + "password": "", + "host": "host:9000", + "hostname": "host", + "port": "9000", + "pathname": "/path", + "search": "?query", + "hash": "#frag" + }, + "# Stringification of URL.searchParams", + { + "input": "?a=b&c=d", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar?a=b&c=d", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "?a=b&c=d", + "searchParams": "a=b&c=d", + "hash": "" + }, + { + "input": "??a=b&c=d", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar??a=b&c=d", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "??a=b&c=d", + "searchParams": "%3Fa=b&c=d", + "hash": "" + }, + "# Scheme only", + { + "input": "http:", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "searchParams": "", + "hash": "" + }, + { + "input": "http:", + "base": "https://example.org/foo/bar", + "failure": true + }, + { + "input": "sc:", + "base": "https://example.org/foo/bar", + "href": "sc:", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "searchParams": "", + "hash": "" + }, + "# Percent encoding of fragments", + { + "input": "http://foo.bar/baz?qux#foo\bbar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%08bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%08bar" + }, + { + "input": "http://foo.bar/baz?qux#foo\"bar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%22bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%22bar" + }, + { + "input": "http://foo.bar/baz?qux#foobar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%3Ebar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%3Ebar" + }, + { + "input": "http://foo.bar/baz?qux#foo`bar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%60bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%60bar" + }, + "# IPv4 parsing (via https://github.com/nodejs/node/pull/10317)", + { + "input": "http://1.2.3.4/", + "base": "http://other.com/", + "href": "http://1.2.3.4/", + "origin": "http://1.2.3.4", + "protocol": "http:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://1.2.3.4./", + "base": "http://other.com/", + "href": "http://1.2.3.4/", + "origin": "http://1.2.3.4", + "protocol": "http:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257", + "base": "http://other.com/", + "href": "http://192.168.1.1/", + "origin": "http://192.168.1.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.1.1", + "hostname": "192.168.1.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257.", + "base": "http://other.com/", + "href": "http://192.168.1.1/", + "origin": "http://192.168.1.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.1.1", + "hostname": "192.168.1.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257.com", + "base": "http://other.com/", + "href": "http://192.168.257.com/", + "origin": "http://192.168.257.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.257.com", + "hostname": "192.168.257.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://256", + "base": "http://other.com/", + "href": "http://0.0.1.0/", + "origin": "http://0.0.1.0", + "protocol": "http:", + "username": "", + "password": "", + "host": "0.0.1.0", + "hostname": "0.0.1.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://256.com", + "base": "http://other.com/", + "href": "http://256.com/", + "origin": "http://256.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "256.com", + "hostname": "256.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999", + "base": "http://other.com/", + "href": "http://59.154.201.255/", + "origin": "http://59.154.201.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "59.154.201.255", + "hostname": "59.154.201.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999.", + "base": "http://other.com/", + "href": "http://59.154.201.255/", + "origin": "http://59.154.201.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "59.154.201.255", + "hostname": "59.154.201.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999.com", + "base": "http://other.com/", + "href": "http://999999999.com/", + "origin": "http://999999999.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "999999999.com", + "hostname": "999999999.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://10000000000", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://10000000000.com", + "base": "http://other.com/", + "href": "http://10000000000.com/", + "origin": "http://10000000000.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "10000000000.com", + "hostname": "10000000000.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://4294967295", + "base": "http://other.com/", + "href": "http://255.255.255.255/", + "origin": "http://255.255.255.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "255.255.255.255", + "hostname": "255.255.255.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://4294967296", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://0xffffffff", + "base": "http://other.com/", + "href": "http://255.255.255.255/", + "origin": "http://255.255.255.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "255.255.255.255", + "hostname": "255.255.255.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://0xffffffff1", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://256.256.256.256", + "base": "http://other.com/", + "failure": true + }, + { + "input": "https://0x.0x.0", + "base": null, + "href": "https://0.0.0.0/", + "origin": "https://0.0.0.0", + "protocol": "https:", + "username": "", + "password": "", + "host": "0.0.0.0", + "hostname": "0.0.0.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "More IPv4 parsing (via https://github.com/jsdom/whatwg-url/issues/92)", + { + "input": "https://0x100000000/test", + "base": null, + "failure": true + }, + { + "input": "https://256.0.0.1/test", + "base": null, + "failure": true + }, + "# file URLs containing percent-encoded Windows drive letters (shouldn't work)", + { + "input": "file:///C%3A/", + "base": null, + "href": "file:///C%3A/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C%3A/", + "search": "", + "hash": "" + }, + { + "input": "file:///C%7C/", + "base": null, + "href": "file:///C%7C/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C%7C/", + "search": "", + "hash": "" + }, + { + "input": "file://%43%3A", + "base": null, + "failure": true + }, + { + "input": "file://%43%7C", + "base": null, + "failure": true + }, + { + "input": "file://%43|", + "base": null, + "failure": true + }, + { + "input": "file://C%7C", + "base": null, + "failure": true + }, + { + "input": "file://%43%7C/", + "base": null, + "failure": true + }, + { + "input": "https://%43%7C/", + "base": null, + "failure": true + }, + { + "input": "asdf://%43|/", + "base": null, + "failure": true + }, + { + "input": "asdf://%43%7C/", + "base": null, + "href": "asdf://%43%7C/", + "origin": "null", + "protocol": "asdf:", + "username": "", + "password": "", + "host": "%43%7C", + "hostname": "%43%7C", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# file URLs relative to other file URLs (via https://github.com/jsdom/whatwg-url/pull/60)", + { + "input": "pix/submit.gif", + "base": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/anchor.html", + "href": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///C:/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# More file URL tests by zcorpan and annevk", + { + "input": "/", + "base": "file:///C:/a/b", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "file://h/C:/a/b", + "href": "file://h/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "file://h/a/b", + "href": "file://h/", + "protocol": "file:", + "username": "", + "password": "", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "//d:", + "base": "file:///C:/a/b", + "href": "file:///d:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/d:", + "search": "", + "hash": "" + }, + { + "input": "//d:/..", + "base": "file:///C:/a/b", + "href": "file:///d:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/d:/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///ab:/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///1:/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "file:///test?test#test", + "href": "file:///test?test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "" + }, + { + "input": "file:", + "base": "file:///test?test#test", + "href": "file:///test?test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "" + }, + { + "input": "?x", + "base": "file:///test?test#test", + "href": "file:///test?x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?x", + "hash": "" + }, + { + "input": "file:?x", + "base": "file:///test?test#test", + "href": "file:///test?x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?x", + "hash": "" + }, + { + "input": "#x", + "base": "file:///test?test#test", + "href": "file:///test?test#x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "#x" + }, + { + "input": "file:#x", + "base": "file:///test?test#test", + "href": "file:///test?test#x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "#x" + }, + "# File URLs and many (back)slashes", + { + "input": "file:\\\\//", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\\\\\", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\\\\\?fox", + "base": null, + "href": "file:////?fox", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "?fox", + "hash": "" + }, + { + "input": "file:\\\\\\\\#guppy", + "base": null, + "href": "file:////#guppy", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "#guppy" + }, + { + "input": "file://spider///", + "base": null, + "href": "file://spider///", + "protocol": "file:", + "username": "", + "password": "", + "host": "spider", + "hostname": "spider", + "port": "", + "pathname": "///", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\localhost//", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:///localhost//cat", + "base": null, + "href": "file:///localhost//cat", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/localhost//cat", + "search": "", + "hash": "" + }, + { + "input": "file://\\/localhost//cat", + "base": null, + "href": "file:////localhost//cat", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//localhost//cat", + "search": "", + "hash": "" + }, + { + "input": "file://localhost//a//../..//", + "base": null, + "href": "file://///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///", + "search": "", + "hash": "" + }, + { + "input": "/////mouse", + "base": "file:///elephant", + "href": "file://///mouse", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///mouse", + "search": "", + "hash": "" + }, + { + "input": "\\//pig", + "base": "file://lion/", + "href": "file:///pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pig", + "search": "", + "hash": "" + }, + { + "input": "\\/localhost//pig", + "base": "file://lion/", + "href": "file:////pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//pig", + "search": "", + "hash": "" + }, + { + "input": "//localhost//pig", + "base": "file://lion/", + "href": "file:////pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//pig", + "search": "", + "hash": "" + }, + { + "input": "/..//localhost//pig", + "base": "file://lion/", + "href": "file://lion//localhost//pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "lion", + "hostname": "lion", + "port": "", + "pathname": "//localhost//pig", + "search": "", + "hash": "" + }, + { + "input": "file://", + "base": "file://ape/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# File URLs with non-empty hosts", + { + "input": "/rooibos", + "base": "file://tea/", + "href": "file://tea/rooibos", + "protocol": "file:", + "username": "", + "password": "", + "host": "tea", + "hostname": "tea", + "port": "", + "pathname": "/rooibos", + "search": "", + "hash": "" + }, + { + "input": "/?chai", + "base": "file://tea/", + "href": "file://tea/?chai", + "protocol": "file:", + "username": "", + "password": "", + "host": "tea", + "hostname": "tea", + "port": "", + "pathname": "/", + "search": "?chai", + "hash": "" + }, + "# Windows drive letter handling with the 'file:' base URL", + { + "input": "C|", + "base": "file://host/dir/file", + "href": "file://host/C:", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|", + "base": "file://host/D:/dir1/dir2/file", + "href": "file://host/C:", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|#", + "base": "file://host/dir/file", + "href": "file://host/C:#", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|?", + "base": "file://host/dir/file", + "href": "file://host/C:?", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|/", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C|\n/", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C|\\", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C", + "base": "file://host/dir/file", + "href": "file://host/dir/C", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/dir/C", + "search": "", + "hash": "" + }, + { + "input": "C|a", + "base": "file://host/dir/file", + "href": "file://host/dir/C|a", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/dir/C|a", + "search": "", + "hash": "" + }, + "# Windows drive letter quirk in the file slash state", + { + "input": "/c:/foo/bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/c|/foo/bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "file:\\c:\\foo\\bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/c:/foo/bar", + "base": "file://host/path", + "href": "file://host/c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + "# Do not drop the host in the presence of a drive letter", + { + "input": "file://example.net/C:/", + "base": null, + "href": "file://example.net/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "example.net", + "hostname": "example.net", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://1.2.3.4/C:/", + "base": null, + "href": "file://1.2.3.4/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://[1::8]/C:/", + "base": null, + "href": "file://[1::8]/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "[1::8]", + "hostname": "[1::8]", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Copy the host from the base URL in the following cases", + { + "input": "C|/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:/C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Copy the empty host from the input in the following cases", + { + "input": "//C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "///C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:///C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Windows drive letter quirk (no host)", + { + "input": "file:/C|/", + "base": null, + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://C|/", + "base": null, + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# file URLs without base URL by Rimas Misevičius", + { + "input": "file:", + "base": null, + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:?q=v", + "base": null, + "href": "file:///?q=v", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "?q=v", + "hash": "" + }, + { + "input": "file:#frag", + "base": null, + "href": "file:///#frag", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "#frag" + }, + "# file: drive letter cases from https://crbug.com/1078698", + { + "input": "file:///Y:", + "base": null, + "href": "file:///Y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:", + "search": "", + "hash": "" + }, + { + "input": "file:///Y:/", + "base": null, + "href": "file:///Y:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:/", + "search": "", + "hash": "" + }, + { + "input": "file:///./Y", + "base": null, + "href": "file:///Y", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y", + "search": "", + "hash": "" + }, + { + "input": "file:///./Y:", + "base": null, + "href": "file:///Y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:", + "search": "", + "hash": "" + }, + { + "input": "\\\\\\.\\Y:", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "# file: drive letter cases from https://crbug.com/1078698 but lowercased", + { + "input": "file:///y:", + "base": null, + "href": "file:///y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:", + "search": "", + "hash": "" + }, + { + "input": "file:///y:/", + "base": null, + "href": "file:///y:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:/", + "search": "", + "hash": "" + }, + { + "input": "file:///./y", + "base": null, + "href": "file:///y", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y", + "search": "", + "hash": "" + }, + { + "input": "file:///./y:", + "base": null, + "href": "file:///y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:", + "search": "", + "hash": "" + }, + { + "input": "\\\\\\.\\y:", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "# Additional file URL tests for (https://github.com/whatwg/url/issues/405)", + { + "input": "file://localhost//a//../..//foo", + "base": null, + "href": "file://///foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///foo", + "search": "", + "hash": "" + }, + { + "input": "file://localhost////foo", + "base": null, + "href": "file://////foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "////foo", + "search": "", + "hash": "" + }, + { + "input": "file:////foo", + "base": null, + "href": "file:////foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//foo", + "search": "", + "hash": "" + }, + { + "input": "file:///one/two", + "base": "file:///", + "href": "file:///one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/one/two", + "search": "", + "hash": "" + }, + { + "input": "file:////one/two", + "base": "file:///", + "href": "file:////one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//one/two", + "search": "", + "hash": "" + }, + { + "input": "//one/two", + "base": "file:///", + "href": "file://one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "one", + "hostname": "one", + "port": "", + "pathname": "/two", + "search": "", + "hash": "" + }, + { + "input": "///one/two", + "base": "file:///", + "href": "file:///one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/one/two", + "search": "", + "hash": "" + }, + { + "input": "////one/two", + "base": "file:///", + "href": "file:////one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//one/two", + "search": "", + "hash": "" + }, + { + "input": "file:///.//", + "base": "file:////", + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + "File URL tests for https://github.com/whatwg/url/issues/549", + { + "input": "file:.//p", + "base": null, + "href": "file:////p", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + { + "input": "file:/.//p", + "base": null, + "href": "file:////p", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + "# IPv6 tests", + { + "input": "http://[1:0::]", + "base": "http://example.net/", + "href": "http://[1::]/", + "origin": "http://[1::]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[1::]", + "hostname": "[1::]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[0:1:2:3:4:5:6:7:8]", + "base": "http://example.net/", + "failure": true + }, + { + "input": "https://[0::0::0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:0:]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1:2:3:4:5:6:7.0.0.0.1]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.00.0.0.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.290.0.0.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.23.23]", + "base": null, + "failure": true + }, + "# Empty host", + { + "input": "http://?", + "base": null, + "failure": true + }, + { + "input": "http://#", + "base": null, + "failure": true + }, + "Port overflow (2^32 + 81)", + { + "input": "http://f:4294967377/c", + "base": "http://example.org/", + "failure": true + }, + "Port overflow (2^64 + 81)", + { + "input": "http://f:18446744073709551697/c", + "base": "http://example.org/", + "failure": true + }, + "Port overflow (2^128 + 81)", + { + "input": "http://f:340282366920938463463374607431768211537/c", + "base": "http://example.org/", + "failure": true + }, + "# Non-special-URL path tests", + { + "input": "sc://ñ", + "base": null, + "href": "sc://%C3%B1", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "sc://ñ?x", + "base": null, + "href": "sc://%C3%B1?x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "?x", + "hash": "" + }, + { + "input": "sc://ñ#x", + "base": null, + "href": "sc://%C3%B1#x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "sc://ñ", + "href": "sc://%C3%B1#x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "#x" + }, + { + "input": "?x", + "base": "sc://ñ", + "href": "sc://%C3%B1?x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "?x", + "hash": "" + }, + { + "input": "sc://?", + "base": null, + "href": "sc://?", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "sc://#", + "base": null, + "href": "sc://#", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "///", + "base": "sc://x/", + "href": "sc:///", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "////", + "base": "sc://x/", + "href": "sc:////", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "////x/", + "base": "sc://x/", + "href": "sc:////x/", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//x/", + "search": "", + "hash": "" + }, + { + "input": "tftp://foobar.com/someconfig;mode=netascii", + "base": null, + "href": "tftp://foobar.com/someconfig;mode=netascii", + "origin": "null", + "protocol": "tftp:", + "username": "", + "password": "", + "host": "foobar.com", + "hostname": "foobar.com", + "port": "", + "pathname": "/someconfig;mode=netascii", + "search": "", + "hash": "" + }, + { + "input": "telnet://user:pass@foobar.com:23/", + "base": null, + "href": "telnet://user:pass@foobar.com:23/", + "origin": "null", + "protocol": "telnet:", + "username": "user", + "password": "pass", + "host": "foobar.com:23", + "hostname": "foobar.com", + "port": "23", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ut2004://10.10.10.10:7777/Index.ut2", + "base": null, + "href": "ut2004://10.10.10.10:7777/Index.ut2", + "origin": "null", + "protocol": "ut2004:", + "username": "", + "password": "", + "host": "10.10.10.10:7777", + "hostname": "10.10.10.10", + "port": "7777", + "pathname": "/Index.ut2", + "search": "", + "hash": "" + }, + { + "input": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz", + "base": null, + "href": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz", + "origin": "null", + "protocol": "redis:", + "username": "foo", + "password": "bar", + "host": "somehost:6379", + "hostname": "somehost", + "port": "6379", + "pathname": "/0", + "search": "?baz=bam&qux=baz", + "hash": "" + }, + { + "input": "rsync://foo@host:911/sup", + "base": null, + "href": "rsync://foo@host:911/sup", + "origin": "null", + "protocol": "rsync:", + "username": "foo", + "password": "", + "host": "host:911", + "hostname": "host", + "port": "911", + "pathname": "/sup", + "search": "", + "hash": "" + }, + { + "input": "git://github.com/foo/bar.git", + "base": null, + "href": "git://github.com/foo/bar.git", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "github.com", + "hostname": "github.com", + "port": "", + "pathname": "/foo/bar.git", + "search": "", + "hash": "" + }, + { + "input": "irc://myserver.com:6999/channel?passwd", + "base": null, + "href": "irc://myserver.com:6999/channel?passwd", + "origin": "null", + "protocol": "irc:", + "username": "", + "password": "", + "host": "myserver.com:6999", + "hostname": "myserver.com", + "port": "6999", + "pathname": "/channel", + "search": "?passwd", + "hash": "" + }, + { + "input": "dns://fw.example.org:9999/foo.bar.org?type=TXT", + "base": null, + "href": "dns://fw.example.org:9999/foo.bar.org?type=TXT", + "origin": "null", + "protocol": "dns:", + "username": "", + "password": "", + "host": "fw.example.org:9999", + "hostname": "fw.example.org", + "port": "9999", + "pathname": "/foo.bar.org", + "search": "?type=TXT", + "hash": "" + }, + { + "input": "ldap://localhost:389/ou=People,o=JNDITutorial", + "base": null, + "href": "ldap://localhost:389/ou=People,o=JNDITutorial", + "origin": "null", + "protocol": "ldap:", + "username": "", + "password": "", + "host": "localhost:389", + "hostname": "localhost", + "port": "389", + "pathname": "/ou=People,o=JNDITutorial", + "search": "", + "hash": "" + }, + { + "input": "git+https://github.com/foo/bar", + "base": null, + "href": "git+https://github.com/foo/bar", + "origin": "null", + "protocol": "git+https:", + "username": "", + "password": "", + "host": "github.com", + "hostname": "github.com", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "urn:ietf:rfc:2648", + "base": null, + "href": "urn:ietf:rfc:2648", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ietf:rfc:2648", + "search": "", + "hash": "" + }, + { + "input": "tag:joe@example.org,2001:foo/bar", + "base": null, + "href": "tag:joe@example.org,2001:foo/bar", + "origin": "null", + "protocol": "tag:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "joe@example.org,2001:foo/bar", + "search": "", + "hash": "" + }, + "Serialize /. in path", + { + "input": "non-spec:/.//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/..//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/a/..//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/.//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/..//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/a/..//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "/.//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "/..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "a/..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "non-spec:/..//p", + "href": "non-spec:/.//p", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + { + "input": "path", + "base": "non-spec:/..//p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + "Do not serialize /. in path", + { + "input": "../path", + "base": "non-spec:/.//p", + "href": "non-spec:/path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + "# percent encoded hosts in non-special-URLs", + { + "input": "non-special://%E2%80%A0/", + "base": null, + "href": "non-special://%E2%80%A0/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "%E2%80%A0", + "hostname": "%E2%80%A0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://H%4fSt/path", + "base": null, + "href": "non-special://H%4fSt/path", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "H%4fSt", + "hostname": "H%4fSt", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + "# IPv6 in non-special-URLs", + { + "input": "non-special://[1:2:0:0:5:0:0:0]/", + "base": null, + "href": "non-special://[1:2:0:0:5::]/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2:0:0:5::]", + "hostname": "[1:2:0:0:5::]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[1:2:0:0:0:0:0:3]/", + "base": null, + "href": "non-special://[1:2::3]/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2::3]", + "hostname": "[1:2::3]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[1:2::3]:80/", + "base": null, + "href": "non-special://[1:2::3]:80/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2::3]:80", + "hostname": "[1:2::3]", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[:80/", + "base": null, + "failure": true + }, + { + "input": "blob:https://example.com:443/", + "base": null, + "href": "blob:https://example.com:443/", + "origin": "https://example.com", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "https://example.com:443/", + "search": "", + "hash": "" + }, + { + "input": "blob:http://example.org:88/", + "base": null, + "href": "blob:http://example.org:88/", + "origin": "http://example.org:88", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "http://example.org:88/", + "search": "", + "hash": "" + }, + { + "input": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", + "base": null, + "href": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "d3958f5c-0777-0845-9dcf-2cb28783acaf", + "search": "", + "hash": "" + }, + { + "input": "blob:", + "base": null, + "href": "blob:", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + "blob: in blob:", + { + "input": "blob:blob:", + "base": null, + "href": "blob:blob:", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blob:", + "search": "", + "hash": "" + }, + { + "input": "blob:blob:https://example.org/", + "base": null, + "href": "blob:blob:https://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blob:https://example.org/", + "search": "", + "hash": "" + }, + "Non-http(s): in blob:", + { + "input": "blob:about:blank", + "base": null, + "href": "blob:about:blank", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "about:blank", + "search": "", + "hash": "" + }, + { + "input": "blob:file://host/path", + "base": null, + "href": "blob:file://host/path", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "file://host/path", + "search": "", + "hash": "" + }, + { + "input": "blob:ftp://host/path", + "base": null, + "href": "blob:ftp://host/path", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ftp://host/path", + "search": "", + "hash": "" + }, + { + "input": "blob:ws://example.org/", + "base": null, + "href": "blob:ws://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ws://example.org/", + "search": "", + "hash": "" + }, + { + "input": "blob:wss://example.org/", + "base": null, + "href": "blob:wss://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "wss://example.org/", + "search": "", + "hash": "" + }, + "Percent-encoded http: in blob:", + { + "input": "blob:http%3a//example.org/", + "base": null, + "href": "blob:http%3a//example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "http%3a//example.org/", + "search": "", + "hash": "" + }, + "Invalid IPv4 radix digits", + { + "input": "http://0x7f.0.0.0x7g", + "base": null, + "href": "http://0x7f.0.0.0x7g/", + "protocol": "http:", + "username": "", + "password": "", + "host": "0x7f.0.0.0x7g", + "hostname": "0x7f.0.0.0x7g", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://0X7F.0.0.0X7G", + "base": null, + "href": "http://0x7f.0.0.0x7g/", + "protocol": "http:", + "username": "", + "password": "", + "host": "0x7f.0.0.0x7g", + "hostname": "0x7f.0.0.0x7g", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid IPv4 portion of IPv6 address", + { + "input": "http://[::127.0.0.0.1]", + "base": null, + "failure": true + }, + "Uncompressed IPv6 addresses with 0", + { + "input": "http://[0:1:0:1:0:1:0:1]", + "base": null, + "href": "http://[0:1:0:1:0:1:0:1]/", + "protocol": "http:", + "username": "", + "password": "", + "host": "[0:1:0:1:0:1:0:1]", + "hostname": "[0:1:0:1:0:1:0:1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[1:0:1:0:1:0:1:0]", + "base": null, + "href": "http://[1:0:1:0:1:0:1:0]/", + "protocol": "http:", + "username": "", + "password": "", + "host": "[1:0:1:0:1:0:1:0]", + "hostname": "[1:0:1:0:1:0:1:0]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Percent-encoded query and fragment", + { + "input": "http://example.org/test?\u0022", + "base": null, + "href": "http://example.org/test?%22", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%22", + "hash": "" + }, + { + "input": "http://example.org/test?\u0023", + "base": null, + "href": "http://example.org/test?#", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "http://example.org/test?\u003C", + "base": null, + "href": "http://example.org/test?%3C", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%3C", + "hash": "" + }, + { + "input": "http://example.org/test?\u003E", + "base": null, + "href": "http://example.org/test?%3E", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%3E", + "hash": "" + }, + { + "input": "http://example.org/test?\u2323", + "base": null, + "href": "http://example.org/test?%E2%8C%A3", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%E2%8C%A3", + "hash": "" + }, + { + "input": "http://example.org/test?%23%23", + "base": null, + "href": "http://example.org/test?%23%23", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%23%23", + "hash": "" + }, + { + "input": "http://example.org/test?%GH", + "base": null, + "href": "http://example.org/test?%GH", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%GH", + "hash": "" + }, + { + "input": "http://example.org/test?a#%EF", + "base": null, + "href": "http://example.org/test?a#%EF", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#%EF" + }, + { + "input": "http://example.org/test?a#%GH", + "base": null, + "href": "http://example.org/test?a#%GH", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#%GH" + }, + "URLs that require a non-about:blank base. (Also serve as invalid base tests.)", + { + "input": "a", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "a/", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "a//", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "Bases that don't fail to parse but fail to be bases", + { + "input": "test-a-colon.html", + "base": "a:", + "failure": true + }, + { + "input": "test-a-colon-b.html", + "base": "a:b", + "failure": true + }, + "Other base URL tests, that must succeed", + { + "input": "test-a-colon-slash.html", + "base": "a:/", + "href": "a:/test-a-colon-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash.html", + "base": "a://", + "href": "a:///test-a-colon-slash-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-b.html", + "base": "a:/b", + "href": "a:/test-a-colon-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-b.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash-b.html", + "base": "a://b", + "href": "a://b/test-a-colon-slash-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "b", + "hostname": "b", + "port": "", + "pathname": "/test-a-colon-slash-slash-b.html", + "search": "", + "hash": "" + }, + "Null code point in fragment", + { + "input": "http://example.org/test?a#b\u0000c", + "base": null, + "href": "http://example.org/test?a#b%00c", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + { + "input": "non-spec://example.org/test?a#b\u0000c", + "base": null, + "href": "non-spec://example.org/test?a#b%00c", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + { + "input": "non-spec:/test?a#b\u0000c", + "base": null, + "href": "non-spec:/test?a#b%00c", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + "First scheme char - not allowed: https://github.com/whatwg/url/issues/464", + { + "input": "10.0.0.7:8080/foo.html", + "base": "file:///some/dir/bar.html", + "href": "file:///some/dir/10.0.0.7:8080/foo.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/some/dir/10.0.0.7:8080/foo.html", + "search": "", + "hash": "" + }, + "Subsequent scheme chars - not allowed", + { + "input": "a!@$*=/foo.html", + "base": "file:///some/dir/bar.html", + "href": "file:///some/dir/a!@$*=/foo.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/some/dir/a!@$*=/foo.html", + "search": "", + "hash": "" + }, + "First and subsequent scheme chars - allowed", + { + "input": "a1234567890-+.:foo/bar", + "base": "http://example.com/dir/file", + "href": "a1234567890-+.:foo/bar", + "protocol": "a1234567890-+.:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "foo/bar", + "search": "", + "hash": "" + }, + "IDNA ignored code points in file URLs hosts", + { + "input": "file://a\u00ADb/p", + "base": null, + "href": "file://ab/p", + "protocol": "file:", + "username": "", + "password": "", + "host": "ab", + "hostname": "ab", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + { + "input": "file://a%C2%ADb/p", + "base": null, + "href": "file://ab/p", + "protocol": "file:", + "username": "", + "password": "", + "host": "ab", + "hostname": "ab", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + "IDNA hostnames which get mapped to 'localhost'", + { + "input": "file://loC𝐀𝐋𝐇𝐨𝐬𝐭/usr/bin", + "base": null, + "href": "file:///usr/bin", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/usr/bin", + "search": "", + "hash": "" + }, + "Empty host after the domain to ASCII", + { + "input": "file://\u00ad/p", + "base": null, + "failure": true + }, + { + "input": "file://%C2%AD/p", + "base": null, + "failure": true + }, + { + "input": "file://xn--/p", + "base": null, + "failure": true + }, + "https://bugzilla.mozilla.org/show_bug.cgi?id=1647058", + { + "input": "#link", + "base": "https://example.org/##link", + "href": "https://example.org/#link", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "#link" + }, + "UTF-8 percent-encode of C0 control percent-encode set and supersets", + { + "input": "non-special:cannot-be-a-base-url-\u0000\u0001\u001F\u001E\u007E\u007F\u0080", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:cannot-be-a-base-url-%00%01%1F%1E~%7F%C2%80", + "origin": "null", + "password": "", + "pathname": "cannot-be-a-base-url-%00%01%1F%1E~%7F%C2%80", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "https://www.example.com/path{\u007Fpath.html?query'\u007F=query#fragment<\u007Ffragment", + "base": null, + "hash": "#fragment%3C%7Ffragment", + "host": "www.example.com", + "hostname": "www.example.com", + "href": "https://www.example.com/path%7B%7Fpath.html?query%27%7F=query#fragment%3C%7Ffragment", + "origin": "https://www.example.com", + "password": "", + "pathname": "/path%7B%7Fpath.html", + "port": "", + "protocol": "https:", + "search": "?query%27%7F=query", + "username": "" + }, + { + "input": "https://user:pass[\u007F@foo/bar", + "base": "http://example.org", + "hash": "", + "host": "foo", + "hostname": "foo", + "href": "https://user:pass%5B%7F@foo/bar", + "origin": "https://foo", + "password": "pass%5B%7F", + "pathname": "/bar", + "port": "", + "protocol": "https:", + "search": "", + "username": "user" + }, + "Tests for the distinct percent-encode sets", + { + "input": "foo:// !\"$%&'()*+,-.;<=>@[\\]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~@host/", + "origin": "null", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~" + }, + { + "input": "wss:// !\"$%&'()*+,-.;<=>@[]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~@host/", + "origin": "wss://host", + "password": "", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~" + }, + { + "input": "foo://joe: !\"$%&'()*+,-.:;<=>@[\\]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://joe:%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~@host/", + "origin": "null", + "password": "%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "joe" + }, + { + "input": "wss://joe: !\"$%&'()*+,-.:;<=>@[]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://joe:%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~@host/", + "origin": "wss://host", + "password": "%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "joe" + }, + { + "input": "foo://!\"$%&'()*+,-.;=_`{}~/", + "base": null, + "hash": "", + "host": "!\"$%&'()*+,-.;=_`{}~", + "hostname": "!\"$%&'()*+,-.;=_`{}~", + "href":"foo://!\"$%&'()*+,-.;=_`{}~/", + "origin": "null", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://!\"$&'()*+,-.;=_`{}~/", + "base": null, + "hash": "", + "host": "!\"$&'()*+,-.;=_`{}~", + "hostname": "!\"$&'()*+,-.;=_`{}~", + "href":"wss://!\"$&'()*+,-.;=_`{}~/", + "origin": "wss://!\"$&'()*+,-.;=_`{}~", + "password": "", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + { + "input": "foo://host/ !\"$%&'()*+,-./:;<=>@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://host/%20!%22$%&'()*+,-./:;%3C=%3E@[\\]^_%60%7B|%7D~", + "origin": "null", + "password": "", + "pathname": "/%20!%22$%&'()*+,-./:;%3C=%3E@[\\]^_%60%7B|%7D~", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://host/ !\"$%&'()*+,-./:;<=>@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://host/%20!%22$%&'()*+,-./:;%3C=%3E@[/]^_%60%7B|%7D~", + "origin": "wss://host", + "password": "", + "pathname": "/%20!%22$%&'()*+,-./:;%3C=%3E@[/]^_%60%7B|%7D~", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + { + "input": "foo://host/dir/? !\"$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://host/dir/?%20!%22$%&'()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "origin": "null", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "foo:", + "search": "?%20!%22$%&'()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "username": "" + }, + { + "input": "wss://host/dir/? !\"$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://host/dir/?%20!%22$%&%27()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "origin": "wss://host", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "wss:", + "search": "?%20!%22$%&%27()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "username": "" + }, + { + "input": "foo://host/dir/# !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "host": "host", + "hostname": "host", + "href": "foo://host/dir/#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "origin": "null", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://host/dir/# !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "host": "host", + "hostname": "host", + "href": "wss://host/dir/#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "origin": "wss://host", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + "Ensure that input schemes are not ignored when resolving non-special URLs", + { + "input": "abc:rootless", + "base": "abc://host/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:rootless", + "base": "abc:/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:rootless", + "base": "abc:path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:/rooted", + "base": "abc://host/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:/rooted", + "password": "", + "pathname": "/rooted", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + "Empty query and fragment with blank should throw an error", + { + "input": "#", + "base": null, + "failure": true, + "relativeTo": "any-base" + }, + { + "input": "?", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "Last component looks like a number, but not valid IPv4", + { + "input": "http://1.2.3.4.5", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://1.2.3.4.5.", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://0..0x300/", + "base": null, + "failure": true + }, + { + "input": "http://0..0x300./", + "base": null, + "failure": true + }, + { + "input": "http://256.256.256.256.256", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://256.256.256.256.256.", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://1.2.3.08", + "base": null, + "failure": true + }, + { + "input": "http://1.2.3.08.", + "base": null, + "failure": true + }, + { + "input": "http://1.2.3.09", + "base": null, + "failure": true + }, + { + "input": "http://09.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://09.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://01.2.3.4.5", + "base": null, + "failure": true + }, + { + "input": "http://01.2.3.4.5.", + "base": null, + "failure": true + }, + { + "input": "http://0x100.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://0x100.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://0x1.2.3.4.5", + "base": null, + "failure": true + }, + { + "input": "http://0x1.2.3.4.5.", + "base": null, + "failure": true + }, + { + "input": "http://foo.1.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://foo.1.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://foo.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.09", + "base": null, + "failure": true + }, + { + "input": "http://foo.09.", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x4", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.09..", + "base": null, + "hash": "", + "host": "foo.09..", + "hostname": "foo.09..", + "href":"http://foo.09../", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://0999999999999999999/", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x", + "base": null, + "failure": true + }, + { + "input": "http://foo.0XFfFfFfFfFfFfFfFfFfAcE123", + "base": null, + "failure": true + }, + { + "input": "http://💩.123/", + "base": null, + "failure": true + }, + "U+0000 and U+FFFF in various places", + { + "input": "https://\u0000y", + "base": null, + "failure": true + }, + { + "input": "https://x/\u0000y", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/%00y", + "password": "", + "pathname": "/%00y", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://x/?\u0000y", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/?%00y", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "?%00y", + "username": "" + }, + { + "input": "https://x/?#\u0000y", + "base": null, + "hash": "#%00y", + "host": "x", + "hostname": "x", + "href": "https://x/?#%00y", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://\uFFFFy", + "base": null, + "failure": true + }, + { + "input": "https://x/\uFFFFy", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/%EF%BF%BFy", + "password": "", + "pathname": "/%EF%BF%BFy", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://x/?\uFFFFy", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/?%EF%BF%BFy", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "?%EF%BF%BFy", + "username": "" + }, + { + "input": "https://x/?#\uFFFFy", + "base": null, + "hash": "#%EF%BF%BFy", + "host": "x", + "hostname": "x", + "href": "https://x/?#%EF%BF%BFy", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "non-special:\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:%00y", + "password": "", + "pathname": "%00y", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/%00y", + "password": "", + "pathname": "x/%00y", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/?\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/?%00y", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "?%00y", + "username": "" + }, + { + "input": "non-special:x/?#\u0000y", + "base": null, + "hash": "#%00y", + "host": "", + "hostname": "", + "href": "non-special:x/?#%00y", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:%EF%BF%BFy", + "password": "", + "pathname": "%EF%BF%BFy", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/%EF%BF%BFy", + "password": "", + "pathname": "x/%EF%BF%BFy", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/?\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/?%EF%BF%BFy", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "?%EF%BF%BFy", + "username": "" + }, + { + "input": "non-special:x/?#\uFFFFy", + "base": null, + "hash": "#%EF%BF%BFy", + "host": "", + "hostname": "", + "href": "non-special:x/?#%EF%BF%BFy", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "https://example.com/\"quoted\"", + "base": null, + "hash": "", + "host": "example.com", + "hostname": "example.com", + "href": "https://example.com/%22quoted%22", + "origin": "https://example.com", + "password": "", + "pathname": "/%22quoted%22", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://a%C2%ADb/", + "base": null, + "hash": "", + "host": "ab", + "hostname": "ab", + "href": "https://ab/", + "origin": "https://ab", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "comment": "Empty host after domain to ASCII", + "input": "https://\u00AD/", + "base": null, + "failure": true + }, + { + "input": "https://%C2%AD/", + "base": null, + "failure": true + }, + { + "input": "https://xn--/", + "base": null, + "failure": true + }, + "Non-special schemes that some implementations might incorrectly treat as special", + { + "input": "data://example.com:8080/pathname?search#hash", + "base": null, + "href": "data://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "data:///test", + "base": null, + "href": "data:///test", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "data://test/a/../b", + "base": null, + "href": "data://test/b", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "data://:443", + "base": null, + "failure": true + }, + { + "input": "data://test:test", + "base": null, + "failure": true + }, + { + "input": "data://[:1]", + "base": null, + "failure": true + }, + { + "input": "javascript://example.com:8080/pathname?search#hash", + "base": null, + "href": "javascript://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "javascript:///test", + "base": null, + "href": "javascript:///test", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "javascript://test/a/../b", + "base": null, + "href": "javascript://test/b", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "javascript://:443", + "base": null, + "failure": true + }, + { + "input": "javascript://test:test", + "base": null, + "failure": true + }, + { + "input": "javascript://[:1]", + "base": null, + "failure": true + }, + { + "input": "mailto://example.com:8080/pathname?search#hash", + "base": null, + "href": "mailto://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "mailto:///test", + "base": null, + "href": "mailto:///test", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "mailto://test/a/../b", + "base": null, + "href": "mailto://test/b", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "mailto://:443", + "base": null, + "failure": true + }, + { + "input": "mailto://test:test", + "base": null, + "failure": true + }, + { + "input": "mailto://[:1]", + "base": null, + "failure": true + }, + { + "input": "intent://example.com:8080/pathname?search#hash", + "base": null, + "href": "intent://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "intent:///test", + "base": null, + "href": "intent:///test", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "intent://test/a/../b", + "base": null, + "href": "intent://test/b", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "intent://:443", + "base": null, + "failure": true + }, + { + "input": "intent://test:test", + "base": null, + "failure": true + }, + { + "input": "intent://[:1]", + "base": null, + "failure": true + }, + { + "input": "urn://example.com:8080/pathname?search#hash", + "base": null, + "href": "urn://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "urn:///test", + "base": null, + "href": "urn:///test", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "urn://test/a/../b", + "base": null, + "href": "urn://test/b", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "urn://:443", + "base": null, + "failure": true + }, + { + "input": "urn://test:test", + "base": null, + "failure": true + }, + { + "input": "urn://[:1]", + "base": null, + "failure": true + }, + { + "input": "turn://example.com:8080/pathname?search#hash", + "base": null, + "href": "turn://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "turn:///test", + "base": null, + "href": "turn:///test", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "turn://test/a/../b", + "base": null, + "href": "turn://test/b", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "turn://:443", + "base": null, + "failure": true + }, + { + "input": "turn://test:test", + "base": null, + "failure": true + }, + { + "input": "turn://[:1]", + "base": null, + "failure": true + }, + { + "input": "stun://example.com:8080/pathname?search#hash", + "base": null, + "href": "stun://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "stun:///test", + "base": null, + "href": "stun:///test", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "stun://test/a/../b", + "base": null, + "href": "stun://test/b", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "stun://:443", + "base": null, + "failure": true + }, + { + "input": "stun://test:test", + "base": null, + "failure": true + }, + { + "input": "stun://[:1]", + "base": null, + "failure": true + }, + { + "input": "w://x:0", + "base": null, + "href": "w://x:0", + "origin": "null", + "protocol": "w:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "west://x:0", + "base": null, + "href": "west://x:0", + "origin": "null", + "protocol": "west:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + "Scheme relative path starting with multiple slashes", + { + "input": "///test", + "base": "http://example.org/", + "href": "http://test/", + "protocol": "http:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///\\//\\//test", + "base": "http://example.org/", + "href": "http://test/", + "protocol": "http:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../../", + "base": "http://example.org/", + "href": "http://example.org/", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path/../../", + "base": "http://example.org/", + "href": "http://example.org/", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path/../../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "/\\/\\//example.org/../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///abcdef/../", + "base": "file:///", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "/\\//\\/a/../", + "base": "file:///", + "href": "file://////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "////", + "search": "", + "hash": "" + }, + { + "input": "//a/../", + "base": "file:///", + "href": "file://a/", + "protocol": "file:", + "username": "", + "password": "", + "host": "a", + "hostname": "a", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + } +] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_api.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..225f384ede71ea938979ead9fd474cf24b8eb6fc --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_api.py @@ -0,0 +1,102 @@ +import typing + +import pytest + +import httpx + + +def test_get(server): + response = httpx.get(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.http_version == "HTTP/1.1" + + +def test_post(server): + response = httpx.post(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_post_byte_iterator(server): + def data() -> typing.Iterator[bytes]: + yield b"Hello" + yield b", " + yield b"world!" + + response = httpx.post(server.url, content=data()) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_post_byte_stream(server): + class Data(httpx.SyncByteStream): + def __iter__(self): + yield b"Hello" + yield b", " + yield b"world!" + + response = httpx.post(server.url, content=Data()) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_options(server): + response = httpx.options(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_head(server): + response = httpx.head(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_put(server): + response = httpx.put(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_patch(server): + response = httpx.patch(server.url, content=b"Hello, world!") + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_delete(server): + response = httpx.delete(server.url) + assert response.status_code == 200 + assert response.reason_phrase == "OK" + + +def test_stream(server): + with httpx.stream("GET", server.url) as response: + response.read() + + assert response.status_code == 200 + assert response.reason_phrase == "OK" + assert response.text == "Hello, world!" + assert response.http_version == "HTTP/1.1" + + +def test_get_invalid_url(): + with pytest.raises(httpx.UnsupportedProtocol): + httpx.get("invalid://example.org") + + +# check that httpcore isn't imported until we do a request +def test_httpcore_lazy_loading(server): + import sys + + # unload our module if it is already loaded + if "httpx" in sys.modules: + del sys.modules["httpx"] + del sys.modules["httpcore"] + import httpx + + assert "httpcore" not in sys.modules + _response = httpx.get(server.url) + assert "httpcore" in sys.modules diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_asgi.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_asgi.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbc91bc00c7c19a1de3fc1f8de59860c29a277e --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_asgi.py @@ -0,0 +1,224 @@ +import json + +import pytest + +import httpx + + +async def hello_world(scope, receive, send): + status = 200 + output = b"Hello, World!" + headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": output}) + + +async def echo_path(scope, receive, send): + status = 200 + output = json.dumps({"path": scope["path"]}).encode("utf-8") + headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": output}) + + +async def echo_raw_path(scope, receive, send): + status = 200 + output = json.dumps({"raw_path": scope["raw_path"].decode("ascii")}).encode("utf-8") + headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": output}) + + +async def echo_body(scope, receive, send): + status = 200 + headers = [(b"content-type", "text/plain")] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + more_body = True + while more_body: + message = await receive() + body = message.get("body", b"") + more_body = message.get("more_body", False) + await send({"type": "http.response.body", "body": body, "more_body": more_body}) + + +async def echo_headers(scope, receive, send): + status = 200 + output = json.dumps( + {"headers": [[k.decode(), v.decode()] for k, v in scope["headers"]]} + ).encode("utf-8") + headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": output}) + + +async def raise_exc(scope, receive, send): + raise RuntimeError() + + +async def raise_exc_after_response(scope, receive, send): + status = 200 + output = b"Hello, World!" + headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))] + + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": output}) + raise RuntimeError() + + +@pytest.mark.anyio +async def test_asgi_transport(): + async with httpx.ASGITransport(app=hello_world) as transport: + request = httpx.Request("GET", "http://www.example.com/") + response = await transport.handle_async_request(request) + await response.aread() + assert response.status_code == 200 + assert response.content == b"Hello, World!" + + +@pytest.mark.anyio +async def test_asgi_transport_no_body(): + async with httpx.ASGITransport(app=echo_body) as transport: + request = httpx.Request("GET", "http://www.example.com/") + response = await transport.handle_async_request(request) + await response.aread() + assert response.status_code == 200 + assert response.content == b"" + + +@pytest.mark.anyio +async def test_asgi(): + transport = httpx.ASGITransport(app=hello_world) + async with httpx.AsyncClient(transport=transport) as client: + response = await client.get("http://www.example.org/") + + assert response.status_code == 200 + assert response.text == "Hello, World!" + + +@pytest.mark.anyio +async def test_asgi_urlencoded_path(): + transport = httpx.ASGITransport(app=echo_path) + async with httpx.AsyncClient(transport=transport) as client: + url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org") + response = await client.get(url) + + assert response.status_code == 200 + assert response.json() == {"path": "/user@example.org"} + + +@pytest.mark.anyio +async def test_asgi_raw_path(): + transport = httpx.ASGITransport(app=echo_raw_path) + async with httpx.AsyncClient(transport=transport) as client: + url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org") + response = await client.get(url) + + assert response.status_code == 200 + assert response.json() == {"raw_path": "/user@example.org"} + + +@pytest.mark.anyio +async def test_asgi_raw_path_should_not_include_querystring_portion(): + """ + See https://github.com/encode/httpx/issues/2810 + """ + transport = httpx.ASGITransport(app=echo_raw_path) + async with httpx.AsyncClient(transport=transport) as client: + url = httpx.URL("http://www.example.org/path?query") + response = await client.get(url) + + assert response.status_code == 200 + assert response.json() == {"raw_path": "/path"} + + +@pytest.mark.anyio +async def test_asgi_upload(): + transport = httpx.ASGITransport(app=echo_body) + async with httpx.AsyncClient(transport=transport) as client: + response = await client.post("http://www.example.org/", content=b"example") + + assert response.status_code == 200 + assert response.text == "example" + + +@pytest.mark.anyio +async def test_asgi_headers(): + transport = httpx.ASGITransport(app=echo_headers) + async with httpx.AsyncClient(transport=transport) as client: + response = await client.get("http://www.example.org/") + + assert response.status_code == 200 + assert response.json() == { + "headers": [ + ["host", "www.example.org"], + ["accept", "*/*"], + ["accept-encoding", "gzip, deflate, br, zstd"], + ["connection", "keep-alive"], + ["user-agent", f"python-httpx/{httpx.__version__}"], + ] + } + + +@pytest.mark.anyio +async def test_asgi_exc(): + transport = httpx.ASGITransport(app=raise_exc) + async with httpx.AsyncClient(transport=transport) as client: + with pytest.raises(RuntimeError): + await client.get("http://www.example.org/") + + +@pytest.mark.anyio +async def test_asgi_exc_after_response(): + transport = httpx.ASGITransport(app=raise_exc_after_response) + async with httpx.AsyncClient(transport=transport) as client: + with pytest.raises(RuntimeError): + await client.get("http://www.example.org/") + + +@pytest.mark.anyio +async def test_asgi_disconnect_after_response_complete(): + disconnect = False + + async def read_body(scope, receive, send): + nonlocal disconnect + + status = 200 + headers = [(b"content-type", "text/plain")] + + await send( + {"type": "http.response.start", "status": status, "headers": headers} + ) + more_body = True + while more_body: + message = await receive() + more_body = message.get("more_body", False) + + await send({"type": "http.response.body", "body": b"", "more_body": False}) + + # The ASGI spec says of the Disconnect message: + # "Sent to the application when a HTTP connection is closed or if receive is + # called after a response has been sent." + # So if receive() is called again, the disconnect message should be received + message = await receive() + disconnect = message.get("type") == "http.disconnect" + + transport = httpx.ASGITransport(app=read_body) + async with httpx.AsyncClient(transport=transport) as client: + response = await client.post("http://www.example.org/", content=b"example") + + assert response.status_code == 200 + assert disconnect + + +@pytest.mark.anyio +async def test_asgi_exc_no_raise(): + transport = httpx.ASGITransport(app=raise_exc, raise_app_exceptions=False) + async with httpx.AsyncClient(transport=transport) as client: + response = await client.get("http://www.example.org/") + + assert response.status_code == 500 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_auth.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6df922ead467fb5ca147140941297f52360860 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_auth.py @@ -0,0 +1,308 @@ +""" +Unit tests for auth classes. + +Integration tests also exist in tests/client/test_auth.py +""" + +from urllib.request import parse_keqv_list + +import pytest + +import httpx + + +def test_basic_auth(): + auth = httpx.BasicAuth(username="user", password="pass") + request = httpx.Request("GET", "https://www.example.com") + + # The initial request should include a basic auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert request.headers["Authorization"].startswith("Basic") + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_with_200(): + auth = httpx.DigestAuth(username="user", password="pass") + request = httpx.Request("GET", "https://www.example.com") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 200 response is returned, then no other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_with_401(): + auth = httpx.DigestAuth(username="user", password="pass") + request = httpx.Request("GET", "https://www.example.com") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 401 response is returned, then a digest auth request is made. + headers = { + "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."' + } + response = httpx.Response( + content=b"Auth required", status_code=401, headers=headers, request=request + ) + request = flow.send(response) + assert request.headers["Authorization"].startswith("Digest") + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_with_401_nonce_counting(): + auth = httpx.DigestAuth(username="user", password="pass") + request = httpx.Request("GET", "https://www.example.com") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 401 response is returned, then a digest auth request is made. + headers = { + "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."' + } + response = httpx.Response( + content=b"Auth required", status_code=401, headers=headers, request=request + ) + first_request = flow.send(response) + assert first_request.headers["Authorization"].startswith("Digest") + + # Each subsequent request contains the digest header by default... + request = httpx.Request("GET", "https://www.example.com") + flow = auth.sync_auth_flow(request) + second_request = next(flow) + assert second_request.headers["Authorization"].startswith("Digest") + + # ... and the client nonce count (nc) is increased + first_nc = parse_keqv_list(first_request.headers["Authorization"].split(", "))["nc"] + second_nc = parse_keqv_list(second_request.headers["Authorization"].split(", "))[ + "nc" + ] + assert int(first_nc, 16) + 1 == int(second_nc, 16) + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def set_cookies(request: httpx.Request) -> httpx.Response: + headers = { + "Set-Cookie": "session=.session_value...", + "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."', + } + if request.url.path == "/auth": + return httpx.Response( + content=b"Auth required", status_code=401, headers=headers + ) + else: + raise NotImplementedError() # pragma: no cover + + +def test_digest_auth_setting_cookie_in_request(): + url = "https://www.example.com/auth" + client = httpx.Client(transport=httpx.MockTransport(set_cookies)) + request = client.build_request("GET", url) + + auth = httpx.DigestAuth(username="user", password="pass") + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + response = client.get(url) + assert len(response.cookies) > 0 + assert response.cookies["session"] == ".session_value..." + + request = flow.send(response) + assert request.headers["Authorization"].startswith("Digest") + assert request.headers["Cookie"] == "session=.session_value..." + + # No other requests are made. + response = httpx.Response( + content=b"Hello, world!", status_code=200, request=request + ) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_rfc_2069(): + # Example from https://datatracker.ietf.org/doc/html/rfc2069#section-2.4 + # with corrected response from https://www.rfc-editor.org/errata/eid749 + + auth = httpx.DigestAuth(username="Mufasa", password="CircleOfLife") + request = httpx.Request("GET", "https://www.example.com/dir/index.html") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 401 response is returned, then a digest auth request is made. + headers = { + "WWW-Authenticate": ( + 'Digest realm="testrealm@host.com", ' + 'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", ' + 'opaque="5ccc069c403ebaf9f0171e9517f40e41"' + ) + } + response = httpx.Response( + content=b"Auth required", status_code=401, headers=headers, request=request + ) + request = flow.send(response) + assert request.headers["Authorization"].startswith("Digest") + assert 'username="Mufasa"' in request.headers["Authorization"] + assert 'realm="testrealm@host.com"' in request.headers["Authorization"] + assert ( + 'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"' in request.headers["Authorization"] + ) + assert 'uri="/dir/index.html"' in request.headers["Authorization"] + assert ( + 'opaque="5ccc069c403ebaf9f0171e9517f40e41"' in request.headers["Authorization"] + ) + assert ( + 'response="1949323746fe6a43ef61f9606e7febea"' + in request.headers["Authorization"] + ) + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_rfc_7616_md5(monkeypatch): + # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1 + + def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes: + return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode() + + auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life") + monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce) + + request = httpx.Request("GET", "https://www.example.com/dir/index.html") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 401 response is returned, then a digest auth request is made. + headers = { + "WWW-Authenticate": ( + 'Digest realm="http-auth@example.org", ' + 'qop="auth, auth-int", ' + "algorithm=MD5, " + 'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", ' + 'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"' + ) + } + response = httpx.Response( + content=b"Auth required", status_code=401, headers=headers, request=request + ) + request = flow.send(response) + assert request.headers["Authorization"].startswith("Digest") + assert 'username="Mufasa"' in request.headers["Authorization"] + assert 'realm="http-auth@example.org"' in request.headers["Authorization"] + assert 'uri="/dir/index.html"' in request.headers["Authorization"] + assert "algorithm=MD5" in request.headers["Authorization"] + assert ( + 'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"' + in request.headers["Authorization"] + ) + assert "nc=00000001" in request.headers["Authorization"] + assert ( + 'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"' + in request.headers["Authorization"] + ) + assert "qop=auth" in request.headers["Authorization"] + assert ( + 'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"' + in request.headers["Authorization"] + ) + assert ( + 'response="8ca523f5e9506fed4657c9700eebdbec"' + in request.headers["Authorization"] + ) + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) + + +def test_digest_auth_rfc_7616_sha_256(monkeypatch): + # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1 + + def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes: + return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode() + + auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life") + monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce) + + request = httpx.Request("GET", "https://www.example.com/dir/index.html") + + # The initial request should not include an auth header. + flow = auth.sync_auth_flow(request) + request = next(flow) + assert "Authorization" not in request.headers + + # If a 401 response is returned, then a digest auth request is made. + headers = { + "WWW-Authenticate": ( + 'Digest realm="http-auth@example.org", ' + 'qop="auth, auth-int", ' + "algorithm=SHA-256, " + 'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", ' + 'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"' + ) + } + response = httpx.Response( + content=b"Auth required", status_code=401, headers=headers, request=request + ) + request = flow.send(response) + assert request.headers["Authorization"].startswith("Digest") + assert 'username="Mufasa"' in request.headers["Authorization"] + assert 'realm="http-auth@example.org"' in request.headers["Authorization"] + assert 'uri="/dir/index.html"' in request.headers["Authorization"] + assert "algorithm=SHA-256" in request.headers["Authorization"] + assert ( + 'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"' + in request.headers["Authorization"] + ) + assert "nc=00000001" in request.headers["Authorization"] + assert ( + 'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"' + in request.headers["Authorization"] + ) + assert "qop=auth" in request.headers["Authorization"] + assert ( + 'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"' + in request.headers["Authorization"] + ) + assert ( + 'response="753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"' + in request.headers["Authorization"] + ) + + # No other requests are made. + response = httpx.Response(content=b"Hello, world!", status_code=200) + with pytest.raises(StopIteration): + flow.send(response) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_config.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..22abd4c22c70c3600dd3a4b01b98df181c1bf624 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_config.py @@ -0,0 +1,184 @@ +import ssl +import typing +from pathlib import Path + +import certifi +import pytest + +import httpx + + +def test_load_ssl_config(): + context = httpx.create_ssl_context() + assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED + assert context.check_hostname is True + + +def test_load_ssl_config_verify_non_existing_file(): + with pytest.raises(IOError): + context = httpx.create_ssl_context() + context.load_verify_locations(cafile="/path/to/nowhere") + + +def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None: + monkeypatch.setenv("SSLKEYLOGFILE", "test") + context = httpx.create_ssl_context() + assert context.keylog_filename == "test" + + +def test_load_ssl_config_verify_existing_file(): + context = httpx.create_ssl_context() + context.load_verify_locations(capath=certifi.where()) + assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED + assert context.check_hostname is True + + +def test_load_ssl_config_verify_directory(): + context = httpx.create_ssl_context() + context.load_verify_locations(capath=Path(certifi.where()).parent) + assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED + assert context.check_hostname is True + + +def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file): + context = httpx.create_ssl_context() + context.load_cert_chain(cert_pem_file, cert_private_key_file) + assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED + assert context.check_hostname is True + + +@pytest.mark.parametrize("password", [b"password", "password"]) +def test_load_ssl_config_cert_and_encrypted_key( + cert_pem_file, cert_encrypted_private_key_file, password +): + context = httpx.create_ssl_context() + context.load_cert_chain(cert_pem_file, cert_encrypted_private_key_file, password) + assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED + assert context.check_hostname is True + + +def test_load_ssl_config_cert_and_key_invalid_password( + cert_pem_file, cert_encrypted_private_key_file +): + with pytest.raises(ssl.SSLError): + context = httpx.create_ssl_context() + context.load_cert_chain( + cert_pem_file, cert_encrypted_private_key_file, "password1" + ) + + +def test_load_ssl_config_cert_without_key_raises(cert_pem_file): + with pytest.raises(ssl.SSLError): + context = httpx.create_ssl_context() + context.load_cert_chain(cert_pem_file) + + +def test_load_ssl_config_no_verify(): + context = httpx.create_ssl_context(verify=False) + assert context.verify_mode == ssl.VerifyMode.CERT_NONE + assert context.check_hostname is False + + +def test_SSLContext_with_get_request(server, cert_pem_file): + context = httpx.create_ssl_context() + context.load_verify_locations(cert_pem_file) + response = httpx.get(server.url, verify=context) + assert response.status_code == 200 + + +def test_limits_repr(): + limits = httpx.Limits(max_connections=100) + expected = ( + "Limits(max_connections=100, max_keepalive_connections=None," + " keepalive_expiry=5.0)" + ) + assert repr(limits) == expected + + +def test_limits_eq(): + limits = httpx.Limits(max_connections=100) + assert limits == httpx.Limits(max_connections=100) + + +def test_timeout_eq(): + timeout = httpx.Timeout(timeout=5.0) + assert timeout == httpx.Timeout(timeout=5.0) + + +def test_timeout_all_parameters_set(): + timeout = httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=5.0) + assert timeout == httpx.Timeout(timeout=5.0) + + +def test_timeout_from_nothing(): + timeout = httpx.Timeout(None) + assert timeout.connect is None + assert timeout.read is None + assert timeout.write is None + assert timeout.pool is None + + +def test_timeout_from_none(): + timeout = httpx.Timeout(timeout=None) + assert timeout == httpx.Timeout(None) + + +def test_timeout_from_one_none_value(): + timeout = httpx.Timeout(None, read=None) + assert timeout == httpx.Timeout(None) + + +def test_timeout_from_one_value(): + timeout = httpx.Timeout(None, read=5.0) + assert timeout == httpx.Timeout(timeout=(None, 5.0, None, None)) + + +def test_timeout_from_one_value_and_default(): + timeout = httpx.Timeout(5.0, pool=60.0) + assert timeout == httpx.Timeout(timeout=(5.0, 5.0, 5.0, 60.0)) + + +def test_timeout_missing_default(): + with pytest.raises(ValueError): + httpx.Timeout(pool=60.0) + + +def test_timeout_from_tuple(): + timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0)) + assert timeout == httpx.Timeout(timeout=5.0) + + +def test_timeout_from_config_instance(): + timeout = httpx.Timeout(timeout=5.0) + assert httpx.Timeout(timeout) == httpx.Timeout(timeout=5.0) + + +def test_timeout_repr(): + timeout = httpx.Timeout(timeout=5.0) + assert repr(timeout) == "Timeout(timeout=5.0)" + + timeout = httpx.Timeout(None, read=5.0) + assert repr(timeout) == "Timeout(connect=None, read=5.0, write=None, pool=None)" + + +def test_proxy_from_url(): + proxy = httpx.Proxy("https://example.com") + + assert str(proxy.url) == "https://example.com" + assert proxy.auth is None + assert proxy.headers == {} + assert repr(proxy) == "Proxy('https://example.com')" + + +def test_proxy_with_auth_from_url(): + proxy = httpx.Proxy("https://username:password@example.com") + + assert str(proxy.url) == "https://example.com" + assert proxy.auth == ("username", "password") + assert proxy.headers == {} + assert repr(proxy) == "Proxy('https://example.com', auth=('username', '********'))" + + +def test_invalid_proxy_scheme(): + with pytest.raises(ValueError): + httpx.Proxy("invalid://example.com") diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_content.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_content.py new file mode 100644 index 0000000000000000000000000000000000000000..f63ec18a6b8f94d29ae09dfad84b36987c78c1ac --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_content.py @@ -0,0 +1,518 @@ +import io +import typing + +import pytest + +import httpx + +method = "POST" +url = "https://www.example.com" + + +@pytest.mark.anyio +async def test_empty_content(): + request = httpx.Request(method, url) + assert isinstance(request.stream, httpx.SyncByteStream) + assert isinstance(request.stream, httpx.AsyncByteStream) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == {"Host": "www.example.com", "Content-Length": "0"} + assert sync_content == b"" + assert async_content == b"" + + +@pytest.mark.anyio +async def test_bytes_content(): + request = httpx.Request(method, url, content=b"Hello, world!") + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == {"Host": "www.example.com", "Content-Length": "13"} + assert sync_content == b"Hello, world!" + assert async_content == b"Hello, world!" + + # Support 'data' for compat with requests. + with pytest.warns(DeprecationWarning): + request = httpx.Request(method, url, data=b"Hello, world!") # type: ignore + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == {"Host": "www.example.com", "Content-Length": "13"} + assert sync_content == b"Hello, world!" + assert async_content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_bytesio_content(): + request = httpx.Request(method, url, content=io.BytesIO(b"Hello, world!")) + assert isinstance(request.stream, typing.Iterable) + assert not isinstance(request.stream, typing.AsyncIterable) + + content = b"".join(list(request.stream)) + + assert request.headers == {"Host": "www.example.com", "Content-Length": "13"} + assert content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_async_bytesio_content(): + class AsyncBytesIO: + def __init__(self, content: bytes) -> None: + self._idx = 0 + self._content = content + + async def aread(self, chunk_size: int) -> bytes: + chunk = self._content[self._idx : self._idx + chunk_size] + self._idx = self._idx + chunk_size + return chunk + + async def __aiter__(self): + yield self._content # pragma: no cover + + request = httpx.Request(method, url, content=AsyncBytesIO(b"Hello, world!")) + assert not isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Transfer-Encoding": "chunked", + } + assert content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_iterator_content(): + def hello_world() -> typing.Iterator[bytes]: + yield b"Hello, " + yield b"world!" + + request = httpx.Request(method, url, content=hello_world()) + assert isinstance(request.stream, typing.Iterable) + assert not isinstance(request.stream, typing.AsyncIterable) + + content = b"".join(list(request.stream)) + + assert request.headers == { + "Host": "www.example.com", + "Transfer-Encoding": "chunked", + } + assert content == b"Hello, world!" + + with pytest.raises(httpx.StreamConsumed): + list(request.stream) + + # Support 'data' for compat with requests. + with pytest.warns(DeprecationWarning): + request = httpx.Request(method, url, data=hello_world()) # type: ignore + assert isinstance(request.stream, typing.Iterable) + assert not isinstance(request.stream, typing.AsyncIterable) + + content = b"".join(list(request.stream)) + + assert request.headers == { + "Host": "www.example.com", + "Transfer-Encoding": "chunked", + } + assert content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_aiterator_content(): + async def hello_world() -> typing.AsyncIterator[bytes]: + yield b"Hello, " + yield b"world!" + + request = httpx.Request(method, url, content=hello_world()) + assert not isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Transfer-Encoding": "chunked", + } + assert content == b"Hello, world!" + + with pytest.raises(httpx.StreamConsumed): + [part async for part in request.stream] + + # Support 'data' for compat with requests. + with pytest.warns(DeprecationWarning): + request = httpx.Request(method, url, data=hello_world()) # type: ignore + assert not isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Transfer-Encoding": "chunked", + } + assert content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_json_content(): + request = httpx.Request(method, url, json={"Hello": "world!"}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "18", + "Content-Type": "application/json", + } + assert sync_content == b'{"Hello":"world!"}' + assert async_content == b'{"Hello":"world!"}' + + +@pytest.mark.anyio +async def test_urlencoded_content(): + request = httpx.Request(method, url, data={"Hello": "world!"}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "14", + "Content-Type": "application/x-www-form-urlencoded", + } + assert sync_content == b"Hello=world%21" + assert async_content == b"Hello=world%21" + + +@pytest.mark.anyio +async def test_urlencoded_boolean(): + request = httpx.Request(method, url, data={"example": True}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "12", + "Content-Type": "application/x-www-form-urlencoded", + } + assert sync_content == b"example=true" + assert async_content == b"example=true" + + +@pytest.mark.anyio +async def test_urlencoded_none(): + request = httpx.Request(method, url, data={"example": None}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "8", + "Content-Type": "application/x-www-form-urlencoded", + } + assert sync_content == b"example=" + assert async_content == b"example=" + + +@pytest.mark.anyio +async def test_urlencoded_list(): + request = httpx.Request(method, url, data={"example": ["a", 1, True]}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "32", + "Content-Type": "application/x-www-form-urlencoded", + } + assert sync_content == b"example=a&example=1&example=true" + assert async_content == b"example=a&example=1&example=true" + + +@pytest.mark.anyio +async def test_multipart_files_content(): + files = {"file": io.BytesIO(b"")} + headers = {"Content-Type": "multipart/form-data; boundary=+++"} + request = httpx.Request( + method, + url, + files=files, + headers=headers, + ) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "138", + "Content-Type": "multipart/form-data; boundary=+++", + } + assert sync_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + assert async_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + + +@pytest.mark.anyio +async def test_multipart_data_and_files_content(): + data = {"message": "Hello, world!"} + files = {"file": io.BytesIO(b"")} + headers = {"Content-Type": "multipart/form-data; boundary=+++"} + request = httpx.Request(method, url, data=data, files=files, headers=headers) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "210", + "Content-Type": "multipart/form-data; boundary=+++", + } + assert sync_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="message"\r\n', + b"\r\n", + b"Hello, world!\r\n", + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + assert async_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="message"\r\n', + b"\r\n", + b"Hello, world!\r\n", + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + + +@pytest.mark.anyio +async def test_empty_request(): + request = httpx.Request(method, url, data={}, files={}) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == {"Host": "www.example.com", "Content-Length": "0"} + assert sync_content == b"" + assert async_content == b"" + + +def test_invalid_argument(): + with pytest.raises(TypeError): + httpx.Request(method, url, content=123) # type: ignore + + with pytest.raises(TypeError): + httpx.Request(method, url, content={"a": "b"}) # type: ignore + + +@pytest.mark.anyio +async def test_multipart_multiple_files_single_input_content(): + files = [ + ("file", io.BytesIO(b"")), + ("file", io.BytesIO(b"")), + ] + headers = {"Content-Type": "multipart/form-data; boundary=+++"} + request = httpx.Request(method, url, files=files, headers=headers) + assert isinstance(request.stream, typing.Iterable) + assert isinstance(request.stream, typing.AsyncIterable) + + sync_content = b"".join(list(request.stream)) + async_content = b"".join([part async for part in request.stream]) + + assert request.headers == { + "Host": "www.example.com", + "Content-Length": "271", + "Content-Type": "multipart/form-data; boundary=+++", + } + assert sync_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + assert async_content == b"".join( + [ + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--+++--\r\n", + ] + ) + + +@pytest.mark.anyio +async def test_response_empty_content(): + response = httpx.Response(200) + assert isinstance(response.stream, typing.Iterable) + assert isinstance(response.stream, typing.AsyncIterable) + + sync_content = b"".join(list(response.stream)) + async_content = b"".join([part async for part in response.stream]) + + assert response.headers == {} + assert sync_content == b"" + assert async_content == b"" + + +@pytest.mark.anyio +async def test_response_bytes_content(): + response = httpx.Response(200, content=b"Hello, world!") + assert isinstance(response.stream, typing.Iterable) + assert isinstance(response.stream, typing.AsyncIterable) + + sync_content = b"".join(list(response.stream)) + async_content = b"".join([part async for part in response.stream]) + + assert response.headers == {"Content-Length": "13"} + assert sync_content == b"Hello, world!" + assert async_content == b"Hello, world!" + + +@pytest.mark.anyio +async def test_response_iterator_content(): + def hello_world() -> typing.Iterator[bytes]: + yield b"Hello, " + yield b"world!" + + response = httpx.Response(200, content=hello_world()) + assert isinstance(response.stream, typing.Iterable) + assert not isinstance(response.stream, typing.AsyncIterable) + + content = b"".join(list(response.stream)) + + assert response.headers == {"Transfer-Encoding": "chunked"} + assert content == b"Hello, world!" + + with pytest.raises(httpx.StreamConsumed): + list(response.stream) + + +@pytest.mark.anyio +async def test_response_aiterator_content(): + async def hello_world() -> typing.AsyncIterator[bytes]: + yield b"Hello, " + yield b"world!" + + response = httpx.Response(200, content=hello_world()) + assert not isinstance(response.stream, typing.Iterable) + assert isinstance(response.stream, typing.AsyncIterable) + + content = b"".join([part async for part in response.stream]) + + assert response.headers == {"Transfer-Encoding": "chunked"} + assert content == b"Hello, world!" + + with pytest.raises(httpx.StreamConsumed): + [part async for part in response.stream] + + +def test_response_invalid_argument(): + with pytest.raises(TypeError): + httpx.Response(200, content=123) # type: ignore + + +def test_ensure_ascii_false_with_french_characters(): + data = {"greeting": "Bonjour, ça va ?"} + response = httpx.Response(200, json=data) + assert ( + "ça va" in response.text + ), "ensure_ascii=False should preserve French accented characters" + assert response.headers["Content-Type"] == "application/json" + + +def test_separators_for_compact_json(): + data = {"clé": "valeur", "liste": [1, 2, 3]} + response = httpx.Response(200, json=data) + assert ( + response.text == '{"clé":"valeur","liste":[1,2,3]}' + ), "separators=(',', ':') should produce a compact representation" + assert response.headers["Content-Type"] == "application/json" + + +def test_allow_nan_false(): + data_with_nan = {"nombre": float("nan")} + data_with_inf = {"nombre": float("inf")} + + with pytest.raises( + ValueError, match="Out of range float values are not JSON compliant" + ): + httpx.Response(200, json=data_with_nan) + with pytest.raises( + ValueError, match="Out of range float values are not JSON compliant" + ): + httpx.Response(200, json=data_with_inf) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_decoders.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..9ffaba189d03052e88a77403bc5b1ebb07f32d3e --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_decoders.py @@ -0,0 +1,355 @@ +from __future__ import annotations + +import io +import typing +import zlib + +import chardet +import pytest +import zstandard as zstd + +import httpx + + +def test_deflate(): + """ + Deflate encoding may use either 'zlib' or 'deflate' in the wild. + + https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297 + """ + body = b"test 123" + compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) + compressed_body = compressor.compress(body) + compressor.flush() + + headers = [(b"Content-Encoding", b"deflate")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_zlib(): + """ + Deflate encoding may use either 'zlib' or 'deflate' in the wild. + + https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297 + """ + body = b"test 123" + compressed_body = zlib.compress(body) + + headers = [(b"Content-Encoding", b"deflate")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_gzip(): + body = b"test 123" + compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) + compressed_body = compressor.compress(body) + compressor.flush() + + headers = [(b"Content-Encoding", b"gzip")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_brotli(): + body = b"test 123" + compressed_body = b"\x8b\x03\x80test 123\x03" + + headers = [(b"Content-Encoding", b"br")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_zstd(): + body = b"test 123" + compressed_body = zstd.compress(body) + + headers = [(b"Content-Encoding", b"zstd")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_zstd_decoding_error(): + compressed_body = "this_is_not_zstd_compressed_data" + + headers = [(b"Content-Encoding", b"zstd")] + with pytest.raises(httpx.DecodingError): + httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + + +def test_zstd_empty(): + headers = [(b"Content-Encoding", b"zstd")] + response = httpx.Response(200, headers=headers, content=b"") + assert response.content == b"" + + +def test_zstd_truncated(): + body = b"test 123" + compressed_body = zstd.compress(body) + + headers = [(b"Content-Encoding", b"zstd")] + with pytest.raises(httpx.DecodingError): + httpx.Response( + 200, + headers=headers, + content=compressed_body[1:3], + ) + + +def test_zstd_multiframe(): + # test inspired by urllib3 test suite + data = ( + # Zstandard frame + zstd.compress(b"foo") + # skippable frame (must be ignored) + + bytes.fromhex( + "50 2A 4D 18" # Magic_Number (little-endian) + "07 00 00 00" # Frame_Size (little-endian) + "00 00 00 00 00 00 00" # User_Data + ) + # Zstandard frame + + zstd.compress(b"bar") + ) + compressed_body = io.BytesIO(data) + + headers = [(b"Content-Encoding", b"zstd")] + response = httpx.Response(200, headers=headers, content=compressed_body) + response.read() + assert response.content == b"foobar" + + +def test_multi(): + body = b"test 123" + + deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) + compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush() + + gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) + compressed_body = ( + gzip_compressor.compress(compressed_body) + gzip_compressor.flush() + ) + + headers = [(b"Content-Encoding", b"deflate, gzip")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +def test_multi_with_identity(): + body = b"test 123" + compressed_body = b"\x8b\x03\x80test 123\x03" + + headers = [(b"Content-Encoding", b"br, identity")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + headers = [(b"Content-Encoding", b"identity, br")] + response = httpx.Response( + 200, + headers=headers, + content=compressed_body, + ) + assert response.content == body + + +@pytest.mark.anyio +async def test_streaming(): + body = b"test 123" + compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) + + async def compress(body: bytes) -> typing.AsyncIterator[bytes]: + yield compressor.compress(body) + yield compressor.flush() + + headers = [(b"Content-Encoding", b"gzip")] + response = httpx.Response( + 200, + headers=headers, + content=compress(body), + ) + assert not hasattr(response, "body") + assert await response.aread() == body + + +@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity")) +def test_empty_content(header_value): + headers = [(b"Content-Encoding", header_value)] + response = httpx.Response( + 200, + headers=headers, + content=b"", + ) + assert response.content == b"" + + +@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity")) +def test_decoders_empty_cases(header_value): + headers = [(b"Content-Encoding", header_value)] + response = httpx.Response(content=b"", status_code=200, headers=headers) + assert response.read() == b"" + + +@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br")) +def test_decoding_errors(header_value): + headers = [(b"Content-Encoding", header_value)] + compressed_body = b"invalid" + with pytest.raises(httpx.DecodingError): + request = httpx.Request("GET", "https://example.org") + httpx.Response(200, headers=headers, content=compressed_body, request=request) + + with pytest.raises(httpx.DecodingError): + httpx.Response(200, headers=headers, content=compressed_body) + + +@pytest.mark.parametrize( + ["data", "encoding"], + [ + ((b"Hello,", b" world!"), "ascii"), + ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"), + ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"), + ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"), + ], +) +@pytest.mark.anyio +async def test_text_decoder_with_autodetect(data, encoding): + async def iterator() -> typing.AsyncIterator[bytes]: + nonlocal data + for chunk in data: + yield chunk + + def autodetect(content): + return chardet.detect(content).get("encoding") + + # Accessing `.text` on a read response. + response = httpx.Response(200, content=iterator(), default_encoding=autodetect) + await response.aread() + assert response.text == (b"".join(data)).decode(encoding) + + # Streaming `.aiter_text` iteratively. + # Note that if we streamed the text *without* having read it first, then + # we won't get a `charset_normalizer` guess, and will instead always rely + # on utf-8 if no charset is specified. + text = "".join([part async for part in response.aiter_text()]) + assert text == (b"".join(data)).decode(encoding) + + +@pytest.mark.anyio +async def test_text_decoder_known_encoding(): + async def iterator() -> typing.AsyncIterator[bytes]: + yield b"\x83g" + yield b"\x83" + yield b"\x89\x83x\x83\x8b" + + response = httpx.Response( + 200, + headers=[(b"Content-Type", b"text/html; charset=shift-jis")], + content=iterator(), + ) + + await response.aread() + assert "".join(response.text) == "トラベル" + + +def test_text_decoder_empty_cases(): + response = httpx.Response(200, content=b"") + assert response.text == "" + + response = httpx.Response(200, content=[b""]) + response.read() + assert response.text == "" + + +@pytest.mark.parametrize( + ["data", "expected"], + [((b"Hello,", b" world!"), ["Hello,", " world!"])], +) +def test_streaming_text_decoder( + data: typing.Iterable[bytes], expected: list[str] +) -> None: + response = httpx.Response(200, content=iter(data)) + assert list(response.iter_text()) == expected + + +def test_line_decoder_nl(): + response = httpx.Response(200, content=[b""]) + assert list(response.iter_lines()) == [] + + response = httpx.Response(200, content=[b"", b"a\n\nb\nc"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + # Issue #1033 + response = httpx.Response( + 200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"] + ) + assert list(response.iter_lines()) == ["12345", "foo bar baz"] + + +def test_line_decoder_cr(): + response = httpx.Response(200, content=[b"", b"a\r\rb\rc"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + # Issue #1033 + response = httpx.Response( + 200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"] + ) + assert list(response.iter_lines()) == ["12345", "foo bar baz"] + + +def test_line_decoder_crnl(): + response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"]) + assert list(response.iter_lines()) == ["a", "", "b", "c"] + + # Issue #1033 + response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"]) + assert list(response.iter_lines()) == ["12345", "foo bar baz"] + + +def test_invalid_content_encoding_header(): + headers = [(b"Content-Encoding", b"invalid-header")] + body = b"test 123" + + response = httpx.Response( + 200, + headers=headers, + content=body, + ) + assert response.content == body diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exceptions.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..60c8721c02300f688a407154a5e64ab97a21e8a6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exceptions.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import typing + +import httpcore +import pytest + +import httpx + +if typing.TYPE_CHECKING: # pragma: no cover + from conftest import TestServer + + +def test_httpcore_all_exceptions_mapped() -> None: + """ + All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific + exception class. + """ + expected_mapped_httpcore_exceptions = { + value.__name__ + for _, value in vars(httpcore).items() + if isinstance(value, type) + and issubclass(value, Exception) + and value is not httpcore.ConnectionNotAvailable + } + + httpx_exceptions = { + value.__name__ + for _, value in vars(httpx).items() + if isinstance(value, type) and issubclass(value, Exception) + } + + unmapped_exceptions = expected_mapped_httpcore_exceptions - httpx_exceptions + + if unmapped_exceptions: # pragma: no cover + pytest.fail(f"Unmapped httpcore exceptions: {unmapped_exceptions}") + + +def test_httpcore_exception_mapping(server: TestServer) -> None: + """ + HTTPCore exception mapping works as expected. + """ + impossible_port = 123456 + with pytest.raises(httpx.ConnectError): + httpx.get(server.url.copy_with(port=impossible_port)) + + with pytest.raises(httpx.ReadTimeout): + httpx.get( + server.url.copy_with(path="/slow_response"), + timeout=httpx.Timeout(5, read=0.01), + ) + + +def test_request_attribute() -> None: + # Exception without request attribute + exc = httpx.ReadTimeout("Read operation timed out") + with pytest.raises(RuntimeError): + exc.request # noqa: B018 + + # Exception with request attribute + request = httpx.Request("GET", "https://www.example.com") + exc = httpx.ReadTimeout("Read operation timed out", request=request) + assert exc.request == request diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exported_members.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exported_members.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9c8a74ca77a5a6b25e20b70a3f70e739218a96 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_exported_members.py @@ -0,0 +1,13 @@ +import httpx + + +def test_all_imports_are_exported() -> None: + included_private_members = ["__description__", "__title__", "__version__"] + assert httpx.__all__ == sorted( + ( + member + for member in vars(httpx).keys() + if not member.startswith("_") or member in included_private_members + ), + key=str.casefold, + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_main.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_main.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a77d485b4b9d2a19aad640a17d6d84679a1db7 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_main.py @@ -0,0 +1,187 @@ +import os +import typing + +from click.testing import CliRunner + +import httpx + + +def splitlines(output: str) -> typing.Iterable[str]: + return [line.strip() for line in output.splitlines()] + + +def remove_date_header(lines: typing.Iterable[str]) -> typing.Iterable[str]: + return [line for line in lines if not line.startswith("date:")] + + +def test_help(): + runner = CliRunner() + result = runner.invoke(httpx.main, ["--help"]) + assert result.exit_code == 0 + assert "A next generation HTTP client." in result.output + + +def test_get(server): + url = str(server.url) + runner = CliRunner() + result = runner.invoke(httpx.main, [url]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: text/plain", + "Transfer-Encoding: chunked", + "", + "Hello, world!", + ] + + +def test_json(server): + url = str(server.url.copy_with(path="/json")) + runner = CliRunner() + result = runner.invoke(httpx.main, [url]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: application/json", + "Transfer-Encoding: chunked", + "", + "{", + '"Hello": "world!"', + "}", + ] + + +def test_binary(server): + url = str(server.url.copy_with(path="/echo_binary")) + runner = CliRunner() + content = "Hello, world!" + result = runner.invoke(httpx.main, [url, "-c", content]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: application/octet-stream", + "Transfer-Encoding: chunked", + "", + f"<{len(content)} bytes of binary data>", + ] + + +def test_redirects(server): + url = str(server.url.copy_with(path="/redirect_301")) + runner = CliRunner() + result = runner.invoke(httpx.main, [url]) + assert result.exit_code == 1 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 301 Moved Permanently", + "server: uvicorn", + "location: /", + "Transfer-Encoding: chunked", + "", + ] + + +def test_follow_redirects(server): + url = str(server.url.copy_with(path="/redirect_301")) + runner = CliRunner() + result = runner.invoke(httpx.main, [url, "--follow-redirects"]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 301 Moved Permanently", + "server: uvicorn", + "location: /", + "Transfer-Encoding: chunked", + "", + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: text/plain", + "Transfer-Encoding: chunked", + "", + "Hello, world!", + ] + + +def test_post(server): + url = str(server.url.copy_with(path="/echo_body")) + runner = CliRunner() + result = runner.invoke(httpx.main, [url, "-m", "POST", "-j", '{"hello": "world"}']) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: text/plain", + "Transfer-Encoding: chunked", + "", + '{"hello":"world"}', + ] + + +def test_verbose(server): + url = str(server.url) + runner = CliRunner() + result = runner.invoke(httpx.main, [url, "-v"]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "* Connecting to '127.0.0.1'", + "* Connected to '127.0.0.1' on port 8000", + "GET / HTTP/1.1", + f"Host: {server.url.netloc.decode('ascii')}", + "Accept: */*", + "Accept-Encoding: gzip, deflate, br, zstd", + "Connection: keep-alive", + f"User-Agent: python-httpx/{httpx.__version__}", + "", + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: text/plain", + "Transfer-Encoding: chunked", + "", + "Hello, world!", + ] + + +def test_auth(server): + url = str(server.url) + runner = CliRunner() + result = runner.invoke(httpx.main, [url, "-v", "--auth", "username", "password"]) + print(result.output) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "* Connecting to '127.0.0.1'", + "* Connected to '127.0.0.1' on port 8000", + "GET / HTTP/1.1", + f"Host: {server.url.netloc.decode('ascii')}", + "Accept: */*", + "Accept-Encoding: gzip, deflate, br, zstd", + "Connection: keep-alive", + f"User-Agent: python-httpx/{httpx.__version__}", + "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + "", + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: text/plain", + "Transfer-Encoding: chunked", + "", + "Hello, world!", + ] + + +def test_download(server): + url = str(server.url) + runner = CliRunner() + with runner.isolated_filesystem(): + runner.invoke(httpx.main, [url, "--download", "index.txt"]) + assert os.path.exists("index.txt") + with open("index.txt", "r") as input_file: + assert input_file.read() == "Hello, world!" + + +def test_errors(): + runner = CliRunner() + result = runner.invoke(httpx.main, ["invalid://example.org"]) + assert result.exit_code == 1 + assert splitlines(result.output) == [ + "UnsupportedProtocol: Request URL has an unsupported protocol 'invalid://'.", + ] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_multipart.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..764f85a253076731d802dc2a81af8e226c0a31f7 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_multipart.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import io +import tempfile +import typing + +import pytest + +import httpx + + +def echo_request_content(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=request.content) + + +@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc"))) +def test_multipart(value, output): + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + # Test with a single-value 'data' argument, and a plain file 'files' argument. + data = {"text": value} + files = {"file": io.BytesIO(b"")} + response = client.post("http://127.0.0.1:8000/", data=data, files=files) + boundary = response.request.headers["Content-Type"].split("boundary=")[-1] + boundary_bytes = boundary.encode("ascii") + + assert response.status_code == 200 + assert response.content == b"".join( + [ + b"--" + boundary_bytes + b"\r\n", + b'Content-Disposition: form-data; name="text"\r\n', + b"\r\n", + b"abc\r\n", + b"--" + boundary_bytes + b"\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--" + boundary_bytes + b"--\r\n", + ] + ) + + +@pytest.mark.parametrize( + "header", + [ + "multipart/form-data; boundary=+++; charset=utf-8", + "multipart/form-data; charset=utf-8; boundary=+++", + "multipart/form-data; boundary=+++", + "multipart/form-data; boundary=+++ ;", + 'multipart/form-data; boundary="+++"; charset=utf-8', + 'multipart/form-data; charset=utf-8; boundary="+++"', + 'multipart/form-data; boundary="+++"', + 'multipart/form-data; boundary="+++" ;', + ], +) +def test_multipart_explicit_boundary(header: str) -> None: + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + files = {"file": io.BytesIO(b"")} + headers = {"content-type": header} + response = client.post("http://127.0.0.1:8000/", files=files, headers=headers) + boundary_bytes = b"+++" + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == header + assert response.content == b"".join( + [ + b"--" + boundary_bytes + b"\r\n", + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n', + b"Content-Type: application/octet-stream\r\n", + b"\r\n", + b"\r\n", + b"--" + boundary_bytes + b"--\r\n", + ] + ) + + +@pytest.mark.parametrize( + "header", + [ + "multipart/form-data; charset=utf-8", + "multipart/form-data; charset=utf-8; ", + ], +) +def test_multipart_header_without_boundary(header: str) -> None: + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + files = {"file": io.BytesIO(b"")} + headers = {"content-type": header} + response = client.post("http://127.0.0.1:8000/", files=files, headers=headers) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == header + + +@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None)) +def test_multipart_invalid_key(key): + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + data = {key: "abc"} + files = {"file": io.BytesIO(b"")} + with pytest.raises(TypeError) as e: + client.post( + "http://127.0.0.1:8000/", + data=data, + files=files, + ) + assert "Invalid type for name" in str(e.value) + assert repr(key) in str(e.value) + + +@pytest.mark.parametrize(("value"), (object(), {"key": "value"})) +def test_multipart_invalid_value(value): + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + data = {"text": value} + files = {"file": io.BytesIO(b"")} + with pytest.raises(TypeError) as e: + client.post("http://127.0.0.1:8000/", data=data, files=files) + assert "Invalid type for value" in str(e.value) + + +def test_multipart_file_tuple(): + client = httpx.Client(transport=httpx.MockTransport(echo_request_content)) + + # Test with a list of values 'data' argument, + # and a tuple style 'files' argument. + data = {"text": ["abc"]} + files = {"file": ("name.txt", io.BytesIO(b""))} + response = client.post("http://127.0.0.1:8000/", data=data, files=files) + boundary = response.request.headers["Content-Type"].split("boundary=")[-1] + boundary_bytes = boundary.encode("ascii") + + assert response.status_code == 200 + assert response.content == b"".join( + [ + b"--" + boundary_bytes + b"\r\n", + b'Content-Disposition: form-data; name="text"\r\n', + b"\r\n", + b"abc\r\n", + b"--" + boundary_bytes + b"\r\n", + b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n', + b"Content-Type: text/plain\r\n", + b"\r\n", + b"\r\n", + b"--" + boundary_bytes + b"--\r\n", + ] + ) + + +@pytest.mark.parametrize("file_content_type", [None, "text/plain"]) +def test_multipart_file_tuple_headers(file_content_type: str | None) -> None: + file_name = "test.txt" + file_content = io.BytesIO(b"") + file_headers = {"Expires": "0"} + + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": (file_name, file_content, file_content_type, file_headers)} + + request = httpx.Request("POST", url, headers=headers, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; ' + f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: ' + f"text/plain\r\n\r\n\r\n--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_headers_include_content_type() -> None: + """ + Content-Type from 4th tuple parameter (headers) should + override the 3rd parameter (content_type) + """ + file_name = "test.txt" + file_content = io.BytesIO(b"") + file_content_type = "text/plain" + file_headers = {"Content-Type": "image/png"} + + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": (file_name, file_content, file_content_type, file_headers)} + + request = httpx.Request("POST", url, headers=headers, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; ' + f'filename="{file_name}"\r\nContent-Type: ' + f"image/png\r\n\r\n\r\n--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_encode(tmp_path: typing.Any) -> None: + path = str(tmp_path / "name.txt") + with open(path, "wb") as f: + f.write(b"") + + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + data = { + "a": "1", + "b": b"C", + "c": ["11", "22", "33"], + "d": "", + "e": True, + "f": "", + } + with open(path, "rb") as input_file: + files = {"file": ("name.txt", input_file)} + + request = httpx.Request("POST", url, headers=headers, data=data, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + '--BOUNDARY\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n' + '--BOUNDARY\r\nContent-Disposition: form-data; name="file";' + ' filename="name.txt"\r\n' + "Content-Type: text/plain\r\n\r\n\r\n" + "--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_encode_unicode_file_contents() -> None: + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": ("name.txt", b"")} + + request = httpx.Request("POST", url, headers=headers, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + b'--BOUNDARY\r\nContent-Disposition: form-data; name="file";' + b' filename="name.txt"\r\n' + b"Content-Type: text/plain\r\n\r\n\r\n" + b"--BOUNDARY--\r\n" + ) + + +def test_multipart_encode_files_allows_filenames_as_none() -> None: + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": (None, io.BytesIO(b""))} + + request = httpx.Request("POST", url, headers=headers, data={}, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + '--BOUNDARY\r\nContent-Disposition: form-data; name="file"\r\n\r\n' + "\r\n--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +@pytest.mark.parametrize( + "file_name,expected_content_type", + [ + ("example.json", "application/json"), + ("example.txt", "text/plain"), + ("no-extension", "application/octet-stream"), + ], +) +def test_multipart_encode_files_guesses_correct_content_type( + file_name: str, expected_content_type: str +) -> None: + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": (file_name, io.BytesIO(b""))} + + request = httpx.Request("POST", url, headers=headers, data={}, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; ' + f'filename="{file_name}"\r\nContent-Type: ' + f"{expected_content_type}\r\n\r\n\r\n--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_encode_files_allows_bytes_content() -> None: + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": ("test.txt", b"", "text/plain")} + + request = httpx.Request("POST", url, headers=headers, data={}, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; ' + 'filename="test.txt"\r\n' + "Content-Type: text/plain\r\n\r\n\r\n" + "--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_encode_files_allows_str_content() -> None: + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + files = {"file": ("test.txt", "", "text/plain")} + + request = httpx.Request("POST", url, headers=headers, data={}, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Content-Length": str(len(request.content)), + } + assert request.content == ( + '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; ' + 'filename="test.txt"\r\n' + "Content-Type: text/plain\r\n\r\n\r\n" + "--BOUNDARY--\r\n" + "".encode("ascii") + ) + + +def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None: + url = "https://www.example.com" + files = {"file": ("test.txt", io.StringIO("content"), "text/plain")} + with pytest.raises(TypeError): + httpx.Request("POST", url, data={}, files=files) # type: ignore + + +def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None: + url = "https://www.example.com" + with tempfile.TemporaryFile(mode="w") as upload: + files = {"file": ("test.txt", upload, "text/plain")} + with pytest.raises(TypeError): + httpx.Request("POST", url, data={}, files=files) # type: ignore + + +def test_multipart_encode_non_seekable_filelike() -> None: + """ + Test that special readable but non-seekable filelike objects are supported. + In this case uploads with use 'Transfer-Encoding: chunked', instead of + a 'Content-Length' header. + """ + + class IteratorIO(io.IOBase): + def __init__(self, iterator: typing.Iterator[bytes]) -> None: + self._iterator = iterator + + def read(self, *args: typing.Any) -> bytes: + return b"".join(self._iterator) + + def data() -> typing.Iterator[bytes]: + yield b"Hello" + yield b"World" + + url = "https://www.example.com/" + headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"} + fileobj: typing.Any = IteratorIO(data()) + files = {"file": fileobj} + + request = httpx.Request("POST", url, headers=headers, files=files) + request.read() + + assert request.headers == { + "Host": "www.example.com", + "Content-Type": "multipart/form-data; boundary=BOUNDARY", + "Transfer-Encoding": "chunked", + } + assert request.content == ( + b"--BOUNDARY\r\n" + b'Content-Disposition: form-data; name="file"; filename="upload"\r\n' + b"Content-Type: application/octet-stream\r\n" + b"\r\n" + b"HelloWorld\r\n" + b"--BOUNDARY--\r\n" + ) + + +def test_multipart_rewinds_files(): + with tempfile.TemporaryFile() as upload: + upload.write(b"Hello, world!") + + transport = httpx.MockTransport(echo_request_content) + client = httpx.Client(transport=transport) + + files = {"file": upload} + response = client.post("http://127.0.0.1:8000/", files=files) + assert response.status_code == 200 + assert b"\r\nHello, world!\r\n" in response.content + + # POSTing the same file instance a second time should have the same content. + files = {"file": upload} + response = client.post("http://127.0.0.1:8000/", files=files) + assert response.status_code == 200 + assert b"\r\nHello, world!\r\n" in response.content + + +class TestHeaderParamHTML5Formatting: + def test_unicode(self): + filename = "n\u00e4me" + expected = b'filename="n\xc3\xa4me"' + files = {"upload": (filename, b"")} + request = httpx.Request("GET", "https://www.example.com", files=files) + assert expected in request.read() + + def test_ascii(self): + filename = "name" + expected = b'filename="name"' + files = {"upload": (filename, b"")} + request = httpx.Request("GET", "https://www.example.com", files=files) + assert expected in request.read() + + def test_unicode_escape(self): + filename = "hello\\world\u0022" + expected = b'filename="hello\\\\world%22"' + files = {"upload": (filename, b"")} + request = httpx.Request("GET", "https://www.example.com", files=files) + assert expected in request.read() + + def test_unicode_with_control_character(self): + filename = "hello\x1a\x1b\x1c" + expected = b'filename="hello%1A\x1b%1C"' + files = {"upload": (filename, b"")} + request = httpx.Request("GET", "https://www.example.com", files=files) + assert expected in request.read() diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_status_codes.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..13314db788b536bea62c0b57e5c50a8e05ef713c --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_status_codes.py @@ -0,0 +1,27 @@ +import httpx + + +def test_status_code_as_int(): + # mypy doesn't (yet) recognize that IntEnum members are ints, so ignore it here + assert httpx.codes.NOT_FOUND == 404 # type: ignore[comparison-overlap] + assert str(httpx.codes.NOT_FOUND) == "404" + + +def test_status_code_value_lookup(): + assert httpx.codes(404) == 404 + + +def test_status_code_phrase_lookup(): + assert httpx.codes["NOT_FOUND"] == 404 + + +def test_lowercase_status_code(): + assert httpx.codes.not_found == 404 # type: ignore + + +def test_reason_phrase_for_status_code(): + assert httpx.codes.get_reason_phrase(404) == "Not Found" + + +def test_reason_phrase_for_unknown_status_code(): + assert httpx.codes.get_reason_phrase(499) == "" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_timeouts.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_timeouts.py new file mode 100644 index 0000000000000000000000000000000000000000..666cc8e376f31d4307137329f741f3c326689edf --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_timeouts.py @@ -0,0 +1,55 @@ +import pytest + +import httpx + + +@pytest.mark.anyio +async def test_read_timeout(server): + timeout = httpx.Timeout(None, read=1e-6) + + async with httpx.AsyncClient(timeout=timeout) as client: + with pytest.raises(httpx.ReadTimeout): + await client.get(server.url.copy_with(path="/slow_response")) + + +@pytest.mark.anyio +async def test_write_timeout(server): + timeout = httpx.Timeout(None, write=1e-6) + + async with httpx.AsyncClient(timeout=timeout) as client: + with pytest.raises(httpx.WriteTimeout): + data = b"*" * 1024 * 1024 * 100 + await client.put(server.url.copy_with(path="/slow_response"), content=data) + + +@pytest.mark.anyio +@pytest.mark.network +async def test_connect_timeout(server): + timeout = httpx.Timeout(None, connect=1e-6) + + async with httpx.AsyncClient(timeout=timeout) as client: + with pytest.raises(httpx.ConnectTimeout): + # See https://stackoverflow.com/questions/100841/ + await client.get("http://10.255.255.1/") + + +@pytest.mark.anyio +async def test_pool_timeout(server): + limits = httpx.Limits(max_connections=1) + timeout = httpx.Timeout(None, pool=1e-4) + + async with httpx.AsyncClient(limits=limits, timeout=timeout) as client: + with pytest.raises(httpx.PoolTimeout): + async with client.stream("GET", server.url): + await client.get(server.url) + + +@pytest.mark.anyio +async def test_async_client_new_request_send_timeout(server): + timeout = httpx.Timeout(1e-6) + + async with httpx.AsyncClient(timeout=timeout) as client: + with pytest.raises(httpx.TimeoutException): + await client.send( + httpx.Request("GET", server.url.copy_with(path="/slow_response")) + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_utils.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c215f65a131e9a96cf3be6002e0117a1f59050 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_utils.py @@ -0,0 +1,150 @@ +import json +import logging +import os +import random + +import pytest + +import httpx +from httpx._utils import URLPattern, get_environment_proxies + + +@pytest.mark.parametrize( + "encoding", + ( + "utf-32", + "utf-8-sig", + "utf-16", + "utf-8", + "utf-16-be", + "utf-16-le", + "utf-32-be", + "utf-32-le", + ), +) +def test_encoded(encoding): + content = '{"abc": 123}'.encode(encoding) + response = httpx.Response(200, content=content) + assert response.json() == {"abc": 123} + + +def test_bad_utf_like_encoding(): + content = b"\x00\x00\x00\x00" + response = httpx.Response(200, content=content) + with pytest.raises(json.decoder.JSONDecodeError): + response.json() + + +@pytest.mark.parametrize( + ("encoding", "expected"), + ( + ("utf-16-be", "utf-16"), + ("utf-16-le", "utf-16"), + ("utf-32-be", "utf-32"), + ("utf-32-le", "utf-32"), + ), +) +def test_guess_by_bom(encoding, expected): + content = '\ufeff{"abc": 123}'.encode(encoding) + response = httpx.Response(200, content=content) + assert response.json() == {"abc": 123} + + +def test_logging_request(server, caplog): + caplog.set_level(logging.INFO) + with httpx.Client() as client: + response = client.get(server.url) + assert response.status_code == 200 + + assert caplog.record_tuples == [ + ( + "httpx", + logging.INFO, + 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"', + ) + ] + + +def test_logging_redirect_chain(server, caplog): + caplog.set_level(logging.INFO) + with httpx.Client(follow_redirects=True) as client: + response = client.get(server.url.copy_with(path="/redirect_301")) + assert response.status_code == 200 + + assert caplog.record_tuples == [ + ( + "httpx", + logging.INFO, + "HTTP Request: GET http://127.0.0.1:8000/redirect_301" + ' "HTTP/1.1 301 Moved Permanently"', + ), + ( + "httpx", + logging.INFO, + 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"', + ), + ] + + +@pytest.mark.parametrize( + ["environment", "proxies"], + [ + ({}, {}), + ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}), + ( + {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"}, + {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"}, + ), + ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}), + ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}), + ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}), + ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}), + ({"no_proxy": "::1"}, {"all://[::1]": None}), + ({"no_proxy": "localhost"}, {"all://localhost": None}), + ({"no_proxy": "github.com"}, {"all://*github.com": None}), + ({"no_proxy": ".github.com"}, {"all://*.github.com": None}), + ({"no_proxy": "http://github.com"}, {"http://github.com": None}), + ], +) +def test_get_environment_proxies(environment, proxies): + os.environ.update(environment) + + assert get_environment_proxies() == proxies + + +@pytest.mark.parametrize( + ["pattern", "url", "expected"], + [ + ("http://example.com", "http://example.com", True), + ("http://example.com", "https://example.com", False), + ("http://example.com", "http://other.com", False), + ("http://example.com:123", "http://example.com:123", True), + ("http://example.com:123", "http://example.com:456", False), + ("http://example.com:123", "http://example.com", False), + ("all://example.com", "http://example.com", True), + ("all://example.com", "https://example.com", True), + ("http://", "http://example.com", True), + ("http://", "https://example.com", False), + ("all://", "https://example.com:123", True), + ("", "https://example.com:123", True), + ], +) +def test_url_matches(pattern, url, expected): + pattern = URLPattern(pattern) + assert pattern.matches(httpx.URL(url)) == expected + + +def test_pattern_priority(): + matchers = [ + URLPattern("all://"), + URLPattern("http://"), + URLPattern("http://example.com"), + URLPattern("http://example.com:123"), + ] + random.shuffle(matchers) + assert sorted(matchers) == [ + URLPattern("http://example.com:123"), + URLPattern("http://example.com"), + URLPattern("http://"), + URLPattern("all://"), + ] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_wsgi.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..dc2b52885afe1f6097c503b6d1a5260a58c8e699 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/info/test/tests/test_wsgi.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import sys +import typing +import wsgiref.validate +from functools import partial +from io import StringIO + +import pytest + +import httpx + +if typing.TYPE_CHECKING: # pragma: no cover + from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment + + +def application_factory(output: typing.Iterable[bytes]) -> WSGIApplication: + def application(environ, start_response): + status = "200 OK" + + response_headers = [ + ("Content-type", "text/plain"), + ] + + start_response(status, response_headers) + + for item in output: + yield item + + return wsgiref.validate.validator(application) + + +def echo_body( + environ: WSGIEnvironment, start_response: StartResponse +) -> typing.Iterable[bytes]: + status = "200 OK" + output = environ["wsgi.input"].read() + + response_headers = [ + ("Content-type", "text/plain"), + ] + + start_response(status, response_headers) + + return [output] + + +def echo_body_with_response_stream( + environ: WSGIEnvironment, start_response: StartResponse +) -> typing.Iterable[bytes]: + status = "200 OK" + + response_headers = [("Content-Type", "text/plain")] + + start_response(status, response_headers) + + def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]: + while True: + output = f.read(2) + if not output: + break + yield output + + return output_generator(f=environ["wsgi.input"]) + + +def raise_exc( + environ: WSGIEnvironment, + start_response: StartResponse, + exc: type[Exception] = ValueError, +) -> typing.Iterable[bytes]: + status = "500 Server Error" + output = b"Nope!" + + response_headers = [ + ("Content-type", "text/plain"), + ] + + try: + raise exc() + except exc: + exc_info = sys.exc_info() + start_response(status, response_headers, exc_info) + + return [output] + + +def log_to_wsgi_log_buffer(environ, start_response): + print("test1", file=environ["wsgi.errors"]) + environ["wsgi.errors"].write("test2") + return echo_body(environ, start_response) + + +def test_wsgi(): + transport = httpx.WSGITransport(app=application_factory([b"Hello, World!"])) + client = httpx.Client(transport=transport) + response = client.get("http://www.example.org/") + assert response.status_code == 200 + assert response.text == "Hello, World!" + + +def test_wsgi_upload(): + transport = httpx.WSGITransport(app=echo_body) + client = httpx.Client(transport=transport) + response = client.post("http://www.example.org/", content=b"example") + assert response.status_code == 200 + assert response.text == "example" + + +def test_wsgi_upload_with_response_stream(): + transport = httpx.WSGITransport(app=echo_body_with_response_stream) + client = httpx.Client(transport=transport) + response = client.post("http://www.example.org/", content=b"example") + assert response.status_code == 200 + assert response.text == "example" + + +def test_wsgi_exc(): + transport = httpx.WSGITransport(app=raise_exc) + client = httpx.Client(transport=transport) + with pytest.raises(ValueError): + client.get("http://www.example.org/") + + +def test_wsgi_http_error(): + transport = httpx.WSGITransport(app=partial(raise_exc, exc=RuntimeError)) + client = httpx.Client(transport=transport) + with pytest.raises(RuntimeError): + client.get("http://www.example.org/") + + +def test_wsgi_generator(): + output = [b"", b"", b"Some content", b" and more content"] + transport = httpx.WSGITransport(app=application_factory(output)) + client = httpx.Client(transport=transport) + response = client.get("http://www.example.org/") + assert response.status_code == 200 + assert response.text == "Some content and more content" + + +def test_wsgi_generator_empty(): + output = [b"", b"", b"", b""] + transport = httpx.WSGITransport(app=application_factory(output)) + client = httpx.Client(transport=transport) + response = client.get("http://www.example.org/") + assert response.status_code == 200 + assert response.text == "" + + +def test_logging(): + buffer = StringIO() + transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer) + client = httpx.Client(transport=transport) + response = client.post("http://www.example.org/", content=b"example") + assert response.status_code == 200 # no errors + buffer.seek(0) + assert buffer.read() == "test1\ntest2" + + +@pytest.mark.parametrize( + "url, expected_server_port", + [ + pytest.param("http://www.example.org", "80", id="auto-http"), + pytest.param("https://www.example.org", "443", id="auto-https"), + pytest.param("http://www.example.org:8000", "8000", id="explicit-port"), + ], +) +def test_wsgi_server_port(url: str, expected_server_port: str) -> None: + """ + SERVER_PORT is populated correctly from the requested URL. + """ + hello_world_app = application_factory([b"Hello, World!"]) + server_port: str | None = None + + def app(environ, start_response): + nonlocal server_port + server_port = environ["SERVER_PORT"] + return hello_world_app(environ, start_response) + + transport = httpx.WSGITransport(app=app) + client = httpx.Client(transport=transport) + response = client.get(url) + assert response.status_code == 200 + assert response.text == "Hello, World!" + assert server_port == expected_server_port + + +def test_wsgi_server_protocol(): + server_protocol = None + + def app(environ, start_response): + nonlocal server_protocol + server_protocol = environ["SERVER_PROTOCOL"] + start_response("200 OK", [("Content-Type", "text/plain")]) + return [b"success"] + + transport = httpx.WSGITransport(app=app) + with httpx.Client(transport=transport, base_url="http://testserver") as client: + response = client.get("/") + + assert response.status_code == 200 + assert response.text == "success" + assert server_protocol == "HTTP/1.1" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..764b3f4a607f9f2b4f52a89af52b36c5c7995865 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA @@ -0,0 +1,204 @@ +Metadata-Version: 2.4 +Name: httpx +Version: 0.28.1 +Summary: The next generation HTTP client. +Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md +Project-URL: Documentation, https://www.python-httpx.org +Project-URL: Homepage, https://github.com/encode/httpx +Project-URL: Source, https://github.com/encode/httpx +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: anyio +Requires-Dist: certifi +Requires-Dist: httpcore==1.* +Requires-Dist: idna +Provides-Extra: brotli +Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: cli +Requires-Dist: click==8.*; extra == 'cli' +Requires-Dist: pygments==2.*; extra == 'cli' +Requires-Dist: rich<14,>=10; extra == 'cli' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: zstandard>=0.18.0; extra == 'zstd' +Description-Content-Type: text/markdown + +

+ HTTPX +

+ +

HTTPX - A next-generation HTTP client for Python.

+ +

+ + Test Suite + + + Package version + +

+ +HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**. + +--- + +Install HTTPX using pip: + +```shell +$ pip install httpx +``` + +Now, let's get started: + +```pycon +>>> import httpx +>>> r = httpx.get('https://www.example.org/') +>>> r + +>>> r.status_code +200 +>>> r.headers['content-type'] +'text/html; charset=UTF-8' +>>> r.text +'\n\n\nExample Domain...' +``` + +Or, using the command-line client. + +```shell +$ pip install 'httpx[cli]' # The command line client is an optional dependency. +``` + +Which now allows us to use HTTPX directly from the command-line... + +

+ httpx --help +

+ +Sending a request... + +

+ httpx http://httpbin.org/json +

+ +## Features + +HTTPX builds on the well-established usability of `requests`, and gives you: + +* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). +* An integrated command-line client. +* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). +* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). +* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport). +* Strict timeouts everywhere. +* Fully type annotated. +* 100% test coverage. + +Plus all the standard features of `requests`... + +* International Domains and URLs +* Keep-Alive & Connection Pooling +* Sessions with Cookie Persistence +* Browser-style SSL Verification +* Basic/Digest Authentication +* Elegant Key/Value Cookies +* Automatic Decompression +* Automatic Content Decoding +* Unicode Response Bodies +* Multipart File Uploads +* HTTP(S) Proxy Support +* Connection Timeouts +* Streaming Downloads +* .netrc Support +* Chunked Requests + +## Installation + +Install with pip: + +```shell +$ pip install httpx +``` + +Or, to include the optional HTTP/2 support, use: + +```shell +$ pip install httpx[http2] +``` + +HTTPX requires Python 3.8+. + +## Documentation + +Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). + +For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). + +For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. + +The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. + +To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). + +## Contribute + +If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. + +## Dependencies + +The HTTPX project relies on these excellent libraries: + +* `httpcore` - The underlying transport implementation for `httpx`. + * `h11` - HTTP/1.1 support. +* `certifi` - SSL certificates. +* `idna` - Internationalized domain name support. +* `sniffio` - Async library autodetection. + +As well as these optional installs: + +* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* +* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* +* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* +* `click` - Command line client support. *(Optional, with `httpx[cli]`)* +* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* +* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)* + +A huge amount of credit is due to `requests` for the API layout that +much of this work follows, as well as to `urllib3` for plenty of design +inspiration around the lower-level networking details. + +--- + +

HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —

+ +## Release Information + +### Fixed + +* Reintroduced supposedly-private `URLTypes` shortcut. (#2673) + + +--- + +[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..99445f201bfdd33bef192d782ae30e0d6c8fa985 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD @@ -0,0 +1,56 @@ +../../../bin/httpx,sha256=QmIWjnxQuoYACqvzsz6zGv26BbnlQUxpV2wOpGYFCwQ,460 +httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx-0.28.1.dist-info/METADATA,sha256=uMXJmfTAKLnlhjWnRouagXCuB5b7AXWG5sQuxIreudg,7088 +httpx-0.28.1.dist-info/RECORD,, +httpx-0.28.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpx-0.28.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +httpx-0.28.1.dist-info/direct_url.json,sha256=dqkn8GlVcxir9fK_pdpN9rK0DRZ97Hk4F6oPvkx-OR8,95 +httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37 +httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508 +httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171 +httpx/__pycache__/__init__.cpython-313.pyc,, +httpx/__pycache__/__version__.cpython-313.pyc,, +httpx/__pycache__/_api.cpython-313.pyc,, +httpx/__pycache__/_auth.cpython-313.pyc,, +httpx/__pycache__/_client.cpython-313.pyc,, +httpx/__pycache__/_config.cpython-313.pyc,, +httpx/__pycache__/_content.cpython-313.pyc,, +httpx/__pycache__/_decoders.cpython-313.pyc,, +httpx/__pycache__/_exceptions.cpython-313.pyc,, +httpx/__pycache__/_main.cpython-313.pyc,, +httpx/__pycache__/_models.cpython-313.pyc,, +httpx/__pycache__/_multipart.cpython-313.pyc,, +httpx/__pycache__/_status_codes.cpython-313.pyc,, +httpx/__pycache__/_types.cpython-313.pyc,, +httpx/__pycache__/_urlparse.cpython-313.pyc,, +httpx/__pycache__/_urls.cpython-313.pyc,, +httpx/__pycache__/_utils.cpython-313.pyc,, +httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108 +httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743 +httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891 +httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714 +httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547 +httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161 +httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041 +httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527 +httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626 +httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700 +httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843 +httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639 +httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275 +httpx/_transports/__pycache__/__init__.cpython-313.pyc,, +httpx/_transports/__pycache__/asgi.cpython-313.pyc,, +httpx/_transports/__pycache__/base.cpython-313.pyc,, +httpx/_transports/__pycache__/default.cpython-313.pyc,, +httpx/_transports/__pycache__/mock.cpython-313.pyc,, +httpx/_transports/__pycache__/wsgi.cpython-313.pyc,, +httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501 +httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523 +httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983 +httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232 +httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825 +httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965 +httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546 +httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550 +httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285 +httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/REQUESTED b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/direct_url.json b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..4cbedb7b93e4c6e01e815f1204006fc7aa42d369 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176044729083783/conda-bld/httpx_1760447344657/work"} \ No newline at end of file diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ae96007f7d725813fd02dc1d06d3834ee1939e4 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +httpx = httpx:main diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ab79d16a3f4c6c894c028d1f7431811e8711b42b --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md @@ -0,0 +1,12 @@ +Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__init__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9addde071f81758baf350c4ab6bde2556340131 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__init__.py @@ -0,0 +1,105 @@ +from .__version__ import __description__, __title__, __version__ +from ._api import * +from ._auth import * +from ._client import * +from ._config import * +from ._content import * +from ._exceptions import * +from ._models import * +from ._status_codes import * +from ._transports import * +from ._types import * +from ._urls import * + +try: + from ._main import main +except ImportError: # pragma: no cover + + def main() -> None: # type: ignore + import sys + + print( + "The httpx command line client could not run because the required " + "dependencies were not installed.\nMake sure you've installed " + "everything with: pip install 'httpx[cli]'" + ) + sys.exit(1) + + +__all__ = [ + "__description__", + "__title__", + "__version__", + "ASGITransport", + "AsyncBaseTransport", + "AsyncByteStream", + "AsyncClient", + "AsyncHTTPTransport", + "Auth", + "BaseTransport", + "BasicAuth", + "ByteStream", + "Client", + "CloseError", + "codes", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "Cookies", + "create_ssl_context", + "DecodingError", + "delete", + "DigestAuth", + "get", + "head", + "Headers", + "HTTPError", + "HTTPStatusError", + "HTTPTransport", + "InvalidURL", + "Limits", + "LocalProtocolError", + "main", + "MockTransport", + "NetRCAuth", + "NetworkError", + "options", + "patch", + "PoolTimeout", + "post", + "ProtocolError", + "Proxy", + "ProxyError", + "put", + "QueryParams", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "request", + "Request", + "RequestError", + "RequestNotRead", + "Response", + "ResponseNotRead", + "stream", + "StreamClosed", + "StreamConsumed", + "StreamError", + "SyncByteStream", + "Timeout", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "URL", + "USE_CLIENT_DEFAULT", + "WriteError", + "WriteTimeout", + "WSGITransport", +] + + +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + setattr(__locals[__name], "__module__", "httpx") # noqa diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__version__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..801bfacf671017cfbebf1ac26ec385daa02ed260 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/__version__.py @@ -0,0 +1,3 @@ +__title__ = "httpx" +__description__ = "A next generation HTTP client, for Python 3." +__version__ = "0.28.1" diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_api.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cda1ecda8629edbdca2e3bc04bc51dba5e1430 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_api.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import typing +from contextlib import contextmanager + +from ._client import Client +from ._config import DEFAULT_TIMEOUT_CONFIG +from ._models import Response +from ._types import ( + AuthTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestFiles, + TimeoutTypes, +) +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + +__all__ = [ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "request", + "stream", +] + + +def request( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends an HTTP request. + + **Parameters:** + + * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, + `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. + * **url** - URL for the new `Request` object. + * **params** - *(optional)* Query parameters to include in the URL, as a + string, dictionary, or sequence of two-tuples. + * **content** - *(optional)* Binary content to include in the body of the + request, as bytes or a byte iterator. + * **data** - *(optional)* Form data to include in the body of the request, + as a dictionary. + * **files** - *(optional)* A dictionary of upload files to include in the + body of the request. + * **json** - *(optional)* A JSON serializable object to include in the body + of the request. + * **headers** - *(optional)* Dictionary of HTTP headers to include in the + request. + * **cookies** - *(optional)* Dictionary of Cookie items to include in the + request. + * **auth** - *(optional)* An authentication class to use when sending the + request. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + the request. + * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + + **Returns:** `Response` + + Usage: + + ``` + >>> import httpx + >>> response = httpx.request('GET', 'https://httpbin.org/get') + >>> response + + ``` + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + return client.request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) + + +@contextmanager +def stream( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + with client.stream( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) as response: + yield response + + +def get( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `GET` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `GET` requests should not include a request body. + """ + return request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def options( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `OPTIONS` requests should not include a request body. + """ + return request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def head( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `HEAD` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `HEAD` requests should not include a request body. + """ + return request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def post( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def put( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def patch( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def delete( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends a `DELETE` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `DELETE` requests should not include a request body. + """ + return request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_auth.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..b03971ab4b311d60790dc22ca24d9966426ec0a4 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_auth.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import hashlib +import os +import re +import time +import typing +from base64 import b64encode +from urllib.request import parse_http_list + +from ._exceptions import ProtocolError +from ._models import Cookies, Request, Response +from ._utils import to_bytes, to_str, unquote + +if typing.TYPE_CHECKING: # pragma: no cover + from hashlib import _Hash + + +__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"] + + +class Auth: + """ + Base class for all authentication schemes. + + To implement a custom authentication scheme, subclass `Auth` and override + the `.auth_flow()` method. + + If the authentication scheme does I/O such as disk access or network calls, or uses + synchronization primitives such as locks, you should override `.sync_auth_flow()` + and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized + implementations that will be used by `Client` and `AsyncClient` respectively. + """ + + requires_request_body = False + requires_response_body = False + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow. + + To dispatch a request, `yield` it: + + ``` + yield request + ``` + + The client will `.send()` the response back into the flow generator. You can + access it like so: + + ``` + response = yield request + ``` + + A `return` (or reaching the end of the generator) will result in the + client returning the last response obtained from the server. + + You can dispatch as many requests as is necessary. + """ + yield request + + def sync_auth_flow( + self, request: Request + ) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow synchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + request.read() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + response.read() + + try: + request = flow.send(response) + except StopIteration: + break + + async def async_auth_flow( + self, request: Request + ) -> typing.AsyncGenerator[Request, Response]: + """ + Execute the authentication flow asynchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + await request.aread() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + await response.aread() + + try: + request = flow.send(response) + except StopIteration: + break + + +class FunctionAuth(Auth): + """ + Allows the 'auth' argument to be passed as a simple callable function, + that takes the request, and returns a new, modified request. + """ + + def __init__(self, func: typing.Callable[[Request], Request]) -> None: + self._func = func + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + yield self._func(request) + + +class BasicAuth(Auth): + """ + Allows the 'auth' argument to be passed as a (username, password) pair, + and uses HTTP Basic authentication. + """ + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._auth_header = self._build_auth_header(username, password) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + request.headers["Authorization"] = self._auth_header + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class NetRCAuth(Auth): + """ + Use a 'netrc' file to lookup basic auth credentials based on the url host. + """ + + def __init__(self, file: str | None = None) -> None: + # Lazily import 'netrc'. + # There's no need for us to load this module unless 'NetRCAuth' is being used. + import netrc + + self._netrc_info = netrc.netrc(file) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + auth_info = self._netrc_info.authenticators(request.url.host) + if auth_info is None or not auth_info[2]: + # The netrc file did not have authentication credentials for this host. + yield request + else: + # Build a basic auth header with credentials from the netrc file. + request.headers["Authorization"] = self._build_auth_header( + username=auth_info[0], password=auth_info[2] + ) + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class DigestAuth(Auth): + _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { + "MD5": hashlib.md5, + "MD5-SESS": hashlib.md5, + "SHA": hashlib.sha1, + "SHA-SESS": hashlib.sha1, + "SHA-256": hashlib.sha256, + "SHA-256-SESS": hashlib.sha256, + "SHA-512": hashlib.sha512, + "SHA-512-SESS": hashlib.sha512, + } + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._username = to_bytes(username) + self._password = to_bytes(password) + self._last_challenge: _DigestAuthChallenge | None = None + self._nonce_count = 1 + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + if self._last_challenge: + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + + response = yield request + + if response.status_code != 401 or "www-authenticate" not in response.headers: + # If the response is not a 401 then we don't + # need to build an authenticated request. + return + + for auth_header in response.headers.get_list("www-authenticate"): + if auth_header.lower().startswith("digest "): + break + else: + # If the response does not include a 'WWW-Authenticate: Digest ...' + # header, then we don't need to build an authenticated request. + return + + self._last_challenge = self._parse_challenge(request, response, auth_header) + self._nonce_count = 1 + + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + if response.cookies: + Cookies(response.cookies).set_cookie_header(request=request) + yield request + + def _parse_challenge( + self, request: Request, response: Response, auth_header: str + ) -> _DigestAuthChallenge: + """ + Returns a challenge from a Digest WWW-Authenticate header. + These take the form of: + `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` + """ + scheme, _, fields = auth_header.partition(" ") + + # This method should only ever have been called with a Digest auth header. + assert scheme.lower() == "digest" + + header_dict: dict[str, str] = {} + for field in parse_http_list(fields): + key, value = field.strip().split("=", 1) + header_dict[key] = unquote(value) + + try: + realm = header_dict["realm"].encode() + nonce = header_dict["nonce"].encode() + algorithm = header_dict.get("algorithm", "MD5") + opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None + qop = header_dict["qop"].encode() if "qop" in header_dict else None + return _DigestAuthChallenge( + realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop + ) + except KeyError as exc: + message = "Malformed Digest WWW-Authenticate header" + raise ProtocolError(message, request=request) from exc + + def _build_auth_header( + self, request: Request, challenge: _DigestAuthChallenge + ) -> str: + hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()] + + def digest(data: bytes) -> bytes: + return hash_func(data).hexdigest().encode() + + A1 = b":".join((self._username, challenge.realm, self._password)) + + path = request.url.raw_path + A2 = b":".join((request.method.encode(), path)) + # TODO: implement auth-int + HA2 = digest(A2) + + nc_value = b"%08x" % self._nonce_count + cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) + self._nonce_count += 1 + + HA1 = digest(A1) + if challenge.algorithm.lower().endswith("-sess"): + HA1 = digest(b":".join((HA1, challenge.nonce, cnonce))) + + qop = self._resolve_qop(challenge.qop, request=request) + if qop is None: + # Following RFC 2069 + digest_data = [HA1, challenge.nonce, HA2] + else: + # Following RFC 2617/7616 + digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2] + + format_args = { + "username": self._username, + "realm": challenge.realm, + "nonce": challenge.nonce, + "uri": path, + "response": digest(b":".join(digest_data)), + "algorithm": challenge.algorithm.encode(), + } + if challenge.opaque: + format_args["opaque"] = challenge.opaque + if qop: + format_args["qop"] = b"auth" + format_args["nc"] = nc_value + format_args["cnonce"] = cnonce + + return "Digest " + self._get_header_value(format_args) + + def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: + s = str(nonce_count).encode() + s += nonce + s += time.ctime().encode() + s += os.urandom(8) + + return hashlib.sha1(s).hexdigest()[:16].encode() + + def _get_header_value(self, header_fields: dict[str, bytes]) -> str: + NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") + QUOTED_TEMPLATE = '{}="{}"' + NON_QUOTED_TEMPLATE = "{}={}" + + header_value = "" + for i, (field, value) in enumerate(header_fields.items()): + if i > 0: + header_value += ", " + template = ( + QUOTED_TEMPLATE + if field not in NON_QUOTED_FIELDS + else NON_QUOTED_TEMPLATE + ) + header_value += template.format(field, to_str(value)) + + return header_value + + def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: + if qop is None: + return None + qops = re.split(b", ?", qop) + if b"auth" in qops: + return b"auth" + + if qops == [b"auth-int"]: + raise NotImplementedError("Digest auth-int support is not yet implemented") + + message = f'Unexpected qop value "{qop!r}" in digest auth' + raise ProtocolError(message, request=request) + + +class _DigestAuthChallenge(typing.NamedTuple): + realm: bytes + nonce: bytes + algorithm: str + opaque: bytes | None + qop: bytes | None diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_client.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2249231f8c3b912c731ff160344d3672e2f11738 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_client.py @@ -0,0 +1,2019 @@ +from __future__ import annotations + +import datetime +import enum +import logging +import time +import typing +import warnings +from contextlib import asynccontextmanager, contextmanager +from types import TracebackType + +from .__version__ import __version__ +from ._auth import Auth, BasicAuth, FunctionAuth +from ._config import ( + DEFAULT_LIMITS, + DEFAULT_MAX_REDIRECTS, + DEFAULT_TIMEOUT_CONFIG, + Limits, + Proxy, + Timeout, +) +from ._decoders import SUPPORTED_DECODERS +from ._exceptions import ( + InvalidURL, + RemoteProtocolError, + TooManyRedirects, + request_context, +) +from ._models import Cookies, Headers, Request, Response +from ._status_codes import codes +from ._transports.base import AsyncBaseTransport, BaseTransport +from ._transports.default import AsyncHTTPTransport, HTTPTransport +from ._types import ( + AsyncByteStream, + AuthTypes, + CertTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + SyncByteStream, + TimeoutTypes, +) +from ._urls import URL, QueryParams +from ._utils import URLPattern, get_environment_proxies + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"] + +# The type annotation for @classmethod and context managers here follows PEP 484 +# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods +T = typing.TypeVar("T", bound="Client") +U = typing.TypeVar("U", bound="AsyncClient") + + +def _is_https_redirect(url: URL, location: URL) -> bool: + """ + Return 'True' if 'location' is a HTTPS upgrade of 'url' + """ + if url.host != location.host: + return False + + return ( + url.scheme == "http" + and _port_or_default(url) == 80 + and location.scheme == "https" + and _port_or_default(location) == 443 + ) + + +def _port_or_default(url: URL) -> int | None: + if url.port is not None: + return url.port + return {"http": 80, "https": 443}.get(url.scheme) + + +def _same_origin(url: URL, other: URL) -> bool: + """ + Return 'True' if the given URLs share the same origin. + """ + return ( + url.scheme == other.scheme + and url.host == other.host + and _port_or_default(url) == _port_or_default(other) + ) + + +class UseClientDefault: + """ + For some parameters such as `auth=...` and `timeout=...` we need to be able + to indicate the default "unset" state, in a way that is distinctly different + to using `None`. + + The default "unset" state indicates that whatever default is set on the + client should be used. This is different to setting `None`, which + explicitly disables the parameter, possibly overriding a client default. + + For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. + Omitting the `timeout` parameter will send a request using whatever default + timeout has been configured on the client. Including `timeout=None` will + ensure no timeout is used. + + Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, + but it is used internally when a parameter is not included. + """ + + +USE_CLIENT_DEFAULT = UseClientDefault() + + +logger = logging.getLogger("httpx") + +USER_AGENT = f"python-httpx/{__version__}" +ACCEPT_ENCODING = ", ".join( + [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] +) + + +class ClientState(enum.Enum): + # UNOPENED: + # The client has been instantiated, but has not been used to send a request, + # or been opened by entering the context of a `with` block. + UNOPENED = 1 + # OPENED: + # The client has either sent a request, or is within a `with` block. + OPENED = 2 + # CLOSED: + # The client has either exited the `with` block, or `close()` has + # been called explicitly. + CLOSED = 3 + + +class BoundSyncStream(SyncByteStream): + """ + A byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: SyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self._stream: + yield chunk + + def close(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + self._stream.close() + + +class BoundAsyncStream(AsyncByteStream): + """ + An async byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: AsyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + async for chunk in self._stream: + yield chunk + + async def aclose(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + await self._stream.aclose() + + +EventHook = typing.Callable[..., typing.Any] + + +class BaseClient: + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + event_hooks = {} if event_hooks is None else event_hooks + + self._base_url = self._enforce_trailing_slash(URL(base_url)) + + self._auth = self._build_auth(auth) + self._params = QueryParams(params) + self.headers = Headers(headers) + self._cookies = Cookies(cookies) + self._timeout = Timeout(timeout) + self.follow_redirects = follow_redirects + self.max_redirects = max_redirects + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + self._trust_env = trust_env + self._default_encoding = default_encoding + self._state = ClientState.UNOPENED + + @property + def is_closed(self) -> bool: + """ + Check if the client being closed + """ + return self._state == ClientState.CLOSED + + @property + def trust_env(self) -> bool: + return self._trust_env + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _get_proxy_map( + self, proxy: ProxyTypes | None, allow_env_proxies: bool + ) -> dict[str, Proxy | None]: + if proxy is None: + if allow_env_proxies: + return { + key: None if url is None else Proxy(url=url) + for key, url in get_environment_proxies().items() + } + return {} + else: + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + return {"all://": proxy} + + @property + def timeout(self) -> Timeout: + return self._timeout + + @timeout.setter + def timeout(self, timeout: TimeoutTypes) -> None: + self._timeout = Timeout(timeout) + + @property + def event_hooks(self) -> dict[str, list[EventHook]]: + return self._event_hooks + + @event_hooks.setter + def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + + @property + def auth(self) -> Auth | None: + """ + Authentication class used when none is passed at the request-level. + + See also [Authentication][0]. + + [0]: /quickstart/#authentication + """ + return self._auth + + @auth.setter + def auth(self, auth: AuthTypes) -> None: + self._auth = self._build_auth(auth) + + @property + def base_url(self) -> URL: + """ + Base URL to use when sending requests with relative URLs. + """ + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(URL(url)) + + @property + def headers(self) -> Headers: + """ + HTTP headers to include when sending requests. + """ + return self._headers + + @headers.setter + def headers(self, headers: HeaderTypes) -> None: + client_headers = Headers( + { + b"Accept": b"*/*", + b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), + b"Connection": b"keep-alive", + b"User-Agent": USER_AGENT.encode("ascii"), + } + ) + client_headers.update(headers) + self._headers = client_headers + + @property + def cookies(self) -> Cookies: + """ + Cookie values to include when sending requests. + """ + return self._cookies + + @cookies.setter + def cookies(self, cookies: CookieTypes) -> None: + self._cookies = Cookies(cookies) + + @property + def params(self) -> QueryParams: + """ + Query parameters to include in the URL when sending requests. + """ + return self._params + + @params.setter + def params(self, params: QueryParamTypes) -> None: + self._params = QueryParams(params) + + def build_request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Request: + """ + Build and return a request instance. + + * The `params`, `headers` and `cookies` arguments + are merged with any values set on the client. + * The `url` argument is merged with any `base_url` set on the client. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + url = self._merge_url(url) + headers = self._merge_headers(headers) + cookies = self._merge_cookies(cookies) + params = self._merge_queryparams(params) + extensions = {} if extensions is None else extensions + if "timeout" not in extensions: + timeout = ( + self.timeout + if isinstance(timeout, UseClientDefault) + else Timeout(timeout) + ) + extensions = dict(**extensions, timeout=timeout.as_dict()) + return Request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + extensions=extensions, + ) + + def _merge_url(self, url: URL | str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + merge_url = URL(url) + if merge_url.is_relative_url: + # To merge URLs we always append to the base URL. To get this + # behaviour correct we always ensure the base URL ends in a '/' + # separator, and strip any leading '/' from the merge URL. + # + # So, eg... + # + # >>> client = Client(base_url="https://www.example.com/subpath") + # >>> client.base_url + # URL('https://www.example.com/subpath/') + # >>> client.build_request("GET", "/path").url + # URL('https://www.example.com/subpath/path') + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + return merge_url + + def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: + """ + Merge a cookies argument together with any cookies on the client, + to create the cookies used for the outgoing request. + """ + if cookies or self.cookies: + merged_cookies = Cookies(self.cookies) + merged_cookies.update(cookies) + return merged_cookies + return cookies + + def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: + """ + Merge a headers argument together with any headers on the client, + to create the headers used for the outgoing request. + """ + merged_headers = Headers(self.headers) + merged_headers.update(headers) + return merged_headers + + def _merge_queryparams( + self, params: QueryParamTypes | None = None + ) -> QueryParamTypes | None: + """ + Merge a queryparams argument together with any queryparams on the client, + to create the queryparams used for the outgoing request. + """ + if params or self.params: + merged_queryparams = QueryParams(self.params) + return merged_queryparams.merge(params) + return params + + def _build_auth(self, auth: AuthTypes | None) -> Auth | None: + if auth is None: + return None + elif isinstance(auth, tuple): + return BasicAuth(username=auth[0], password=auth[1]) + elif isinstance(auth, Auth): + return auth + elif callable(auth): + return FunctionAuth(func=auth) + else: + raise TypeError(f'Invalid "auth" argument: {auth!r}') + + def _build_request_auth( + self, + request: Request, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + ) -> Auth: + auth = ( + self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) + ) + + if auth is not None: + return auth + + username, password = request.url.username, request.url.password + if username or password: + return BasicAuth(username=username, password=password) + + return Auth() + + def _build_redirect_request(self, request: Request, response: Response) -> Request: + """ + Given a request and a redirect response, return a new request that + should be used to effect the redirect. + """ + method = self._redirect_method(request, response) + url = self._redirect_url(request, response) + headers = self._redirect_headers(request, url, method) + stream = self._redirect_stream(request, method) + cookies = Cookies(self.cookies) + return Request( + method=method, + url=url, + headers=headers, + cookies=cookies, + stream=stream, + extensions=request.extensions, + ) + + def _redirect_method(self, request: Request, response: Response) -> str: + """ + When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.SEE_OTHER and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # Turn 302s into GETs. + if response.status_code == codes.FOUND and method != "HEAD": + method = "GET" + + # If a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in 'requests' issue 1704. + if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": + method = "GET" + + return method + + def _redirect_url(self, request: Request, response: Response) -> URL: + """ + Return the URL for the redirect to follow. + """ + location = response.headers["Location"] + + try: + url = URL(location) + except InvalidURL as exc: + raise RemoteProtocolError( + f"Invalid URL in location header: {exc}.", request=request + ) from None + + # Handle malformed 'Location' headers that are "absolute" form, have no host. + # See: https://github.com/encode/httpx/issues/771 + if url.scheme and not url.host: + url = url.copy_with(host=request.url.host) + + # Facilitate relative 'Location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + if url.is_relative_url: + url = request.url.join(url) + + # Attach previous fragment if needed (RFC 7231 7.1.2) + if request.url.fragment and not url.fragment: + url = url.copy_with(fragment=request.url.fragment) + + return url + + def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: + """ + Return the headers that should be used for the redirect request. + """ + headers = Headers(request.headers) + + if not _same_origin(url, request.url): + if not _is_https_redirect(request.url, url): + # Strip Authorization headers when responses are redirected + # away from the origin. (Except for direct HTTP to HTTPS redirects.) + headers.pop("Authorization", None) + + # Update the Host header. + headers["Host"] = url.netloc.decode("ascii") + + if method != request.method and method == "GET": + # If we've switch to a 'GET' request, then strip any headers which + # are only relevant to the request body. + headers.pop("Content-Length", None) + headers.pop("Transfer-Encoding", None) + + # We should use the client cookie store to determine any cookie header, + # rather than whatever was on the original outgoing request. + headers.pop("Cookie", None) + + return headers + + def _redirect_stream( + self, request: Request, method: str + ) -> SyncByteStream | AsyncByteStream | None: + """ + Return the body that should be used for the redirect request. + """ + if method != request.method and method == "GET": + return None + + return request.stream + + def _set_timeout(self, request: Request) -> None: + if "timeout" not in request.extensions: + timeout = ( + self.timeout + if isinstance(self.timeout, UseClientDefault) + else Timeout(self.timeout) + ) + request.extensions = dict(**request.extensions, timeout=timeout.as_dict()) + + +class Client(BaseClient): + """ + An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. + + It can be shared between threads. + + Usage: + + ```python + >>> client = httpx.Client() + >>> response = client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: BaseTransport | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + self._mounts: dict[URLPattern, BaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: BaseTransport | None = None, + ) -> BaseTransport: + if transport is not None: + return transport + + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> BaseTransport: + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> BaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = client.send(request, ...) + ``` + + See `Client.build_request()`, `Client.send()` and + [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + if cookies is not None: + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return self.send(request, auth=auth, follow_redirects=follow_redirects) + + @contextmanager + def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + response.close() + + def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `Client.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + response.read() + + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.sync_auth_flow(request) + try: + request = next(auth_flow) + + while True: + response = self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = auth_flow.send(response) + except StopIteration: + return response + + response.history = list(history) + response.read() + request = next_request + history.append(response) + + except BaseException as exc: + response.close() + raise exc + finally: + auth_flow.close() + + def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + hook(request) + + response = self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + hook(response) + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + response.read() + else: + response.next_request = request + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, SyncByteStream): + raise RuntimeError( + "Attempted to send an async request with a sync Client instance." + ) + + with request_context(request=request): + response = transport.handle_request(request) + + assert isinstance(response.stream, SyncByteStream) + + response.request = request + response.stream = BoundSyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def close(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + self._transport.close() + for transport in self._mounts.values(): + if transport is not None: + transport.close() + + def __enter__(self: T) -> T: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + self._transport.__enter__() + for transport in self._mounts.values(): + if transport is not None: + transport.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + self._transport.__exit__(exc_type, exc_value, traceback) + for transport in self._mounts.values(): + if transport is not None: + transport.__exit__(exc_type, exc_value, traceback) + + +class AsyncClient(BaseClient): + """ + An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, + cookie persistence, etc. + + It can be shared between tasks. + + Usage: + + ```python + >>> async with httpx.AsyncClient() as client: + >>> response = await client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: AsyncBaseTransport | None = None, + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + + self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: AsyncBaseTransport | None = None, + ) -> AsyncBaseTransport: + if transport is not None: + return transport + + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> AsyncBaseTransport: + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> AsyncBaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + async def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = await client.send(request, ...) + ``` + + See `AsyncClient.build_request()`, `AsyncClient.send()` + and [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + + if cookies is not None: # pragma: no cover + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return await self.send(request, auth=auth, follow_redirects=follow_redirects) + + @asynccontextmanager + async def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.AsyncIterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = await self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + await response.aclose() + + async def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `AsyncClient.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = await self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + await response.aread() + + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.async_auth_flow(request) + try: + request = await auth_flow.__anext__() + + while True: + response = await self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = await auth_flow.asend(response) + except StopAsyncIteration: + return response + + response.history = list(history) + await response.aread() + request = next_request + history.append(response) + + except BaseException as exc: + await response.aclose() + raise exc + finally: + await auth_flow.aclose() + + async def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + await hook(request) + + response = await self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + await hook(response) + + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + await response.aread() + else: + response.next_request = request + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, AsyncByteStream): + raise RuntimeError( + "Attempted to send an sync request with an AsyncClient instance." + ) + + with request_context(request=request): + response = await transport.handle_async_request(request) + + assert isinstance(response.stream, AsyncByteStream) + response.request = request + response.stream = BoundAsyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + async def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def aclose(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + await self._transport.aclose() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.aclose() + + async def __aenter__(self: U) -> U: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + await self._transport.__aenter__() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + await self._transport.__aexit__(exc_type, exc_value, traceback) + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_config.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..467a6c90ae269babe3af7963d9d7c78b9f012268 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_config.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import os +import typing + +from ._models import Headers +from ._types import CertTypes, HeaderTypes, TimeoutTypes +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] + + +class UnsetType: + pass # pragma: no cover + + +UNSET = UnsetType() + + +def create_ssl_context( + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, +) -> ssl.SSLContext: + import ssl + import warnings + + import certifi + + if verify is True: + if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover + ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) + elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover + ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) + else: + # Default case... + ctx = ssl.create_default_context(cafile=certifi.where()) + elif verify is False: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif isinstance(verify, str): # pragma: nocover + message = ( + "`verify=` is deprecated. " + "Use `verify=ssl.create_default_context(cafile=...)` " + "or `verify=ssl.create_default_context(capath=...)` instead." + ) + warnings.warn(message, DeprecationWarning) + if os.path.isdir(verify): + return ssl.create_default_context(capath=verify) + return ssl.create_default_context(cafile=verify) + else: + ctx = verify + + if cert: # pragma: nocover + message = ( + "`cert=...` is deprecated. Use `verify=` instead," + "with `.load_cert_chain()` to configure the certificate chain." + ) + warnings.warn(message, DeprecationWarning) + if isinstance(cert, str): + ctx.load_cert_chain(cert) + else: + ctx.load_cert_chain(*cert) + + return ctx + + +class Timeout: + """ + Timeout configuration. + + **Usage**: + + Timeout(None) # No timeouts. + Timeout(5.0) # 5s timeout on all operations. + Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. + Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. + Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. + # 5s timeout elsewhere. + """ + + def __init__( + self, + timeout: TimeoutTypes | UnsetType = UNSET, + *, + connect: None | float | UnsetType = UNSET, + read: None | float | UnsetType = UNSET, + write: None | float | UnsetType = UNSET, + pool: None | float | UnsetType = UNSET, + ) -> None: + if isinstance(timeout, Timeout): + # Passed as a single explicit Timeout. + assert connect is UNSET + assert read is UNSET + assert write is UNSET + assert pool is UNSET + self.connect = timeout.connect # type: typing.Optional[float] + self.read = timeout.read # type: typing.Optional[float] + self.write = timeout.write # type: typing.Optional[float] + self.pool = timeout.pool # type: typing.Optional[float] + elif isinstance(timeout, tuple): + # Passed as a tuple. + self.connect = timeout[0] + self.read = timeout[1] + self.write = None if len(timeout) < 3 else timeout[2] + self.pool = None if len(timeout) < 4 else timeout[3] + elif not ( + isinstance(connect, UnsetType) + or isinstance(read, UnsetType) + or isinstance(write, UnsetType) + or isinstance(pool, UnsetType) + ): + self.connect = connect + self.read = read + self.write = write + self.pool = pool + else: + if isinstance(timeout, UnsetType): + raise ValueError( + "httpx.Timeout must either include a default, or set all " + "four parameters explicitly." + ) + self.connect = timeout if isinstance(connect, UnsetType) else connect + self.read = timeout if isinstance(read, UnsetType) else read + self.write = timeout if isinstance(write, UnsetType) else write + self.pool = timeout if isinstance(pool, UnsetType) else pool + + def as_dict(self) -> dict[str, float | None]: + return { + "connect": self.connect, + "read": self.read, + "write": self.write, + "pool": self.pool, + } + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.connect == other.connect + and self.read == other.read + and self.write == other.write + and self.pool == other.pool + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + if len({self.connect, self.read, self.write, self.pool}) == 1: + return f"{class_name}(timeout={self.connect})" + return ( + f"{class_name}(connect={self.connect}, " + f"read={self.read}, write={self.write}, pool={self.pool})" + ) + + +class Limits: + """ + Configuration for limits to various client behaviors. + + **Parameters:** + + * **max_connections** - The maximum number of concurrent connections that may be + established. + * **max_keepalive_connections** - Allow the connection pool to maintain + keep-alive connections below this point. Should be less than or equal + to `max_connections`. + * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. + """ + + def __init__( + self, + *, + max_connections: int | None = None, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = 5.0, + ) -> None: + self.max_connections = max_connections + self.max_keepalive_connections = max_keepalive_connections + self.keepalive_expiry = keepalive_expiry + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.max_connections == other.max_connections + and self.max_keepalive_connections == other.max_keepalive_connections + and self.keepalive_expiry == other.keepalive_expiry + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return ( + f"{class_name}(max_connections={self.max_connections}, " + f"max_keepalive_connections={self.max_keepalive_connections}, " + f"keepalive_expiry={self.keepalive_expiry})" + ) + + +class Proxy: + def __init__( + self, + url: URL | str, + *, + ssl_context: ssl.SSLContext | None = None, + auth: tuple[str, str] | None = None, + headers: HeaderTypes | None = None, + ) -> None: + url = URL(url) + headers = Headers(headers) + + if url.scheme not in ("http", "https", "socks5", "socks5h"): + raise ValueError(f"Unknown scheme for proxy URL {url!r}") + + if url.username or url.password: + # Remove any auth credentials from the URL. + auth = (url.username, url.password) + url = url.copy_with(username=None, password=None) + + self.url = url + self.auth = auth + self.headers = headers + self.ssl_context = ssl_context + + @property + def raw_auth(self) -> tuple[bytes, bytes] | None: + # The proxy authentication as raw bytes. + return ( + None + if self.auth is None + else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) + ) + + def __repr__(self) -> str: + # The authentication is represented with the password component masked. + auth = (self.auth[0], "********") if self.auth else None + + # Build a nice concise representation. + url_str = f"{str(self.url)!r}" + auth_str = f", auth={auth!r}" if auth else "" + headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" + return f"Proxy({url_str}{auth_str}{headers_str})" + + +DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) +DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_MAX_REDIRECTS = 20 diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_content.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_content.py new file mode 100644 index 0000000000000000000000000000000000000000..6f479a0885f723b7395843d41164a87041820776 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_content.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import inspect +import warnings +from json import dumps as json_dumps +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Iterable, + Iterator, + Mapping, +) +from urllib.parse import urlencode + +from ._exceptions import StreamClosed, StreamConsumed +from ._multipart import MultipartStream +from ._types import ( + AsyncByteStream, + RequestContent, + RequestData, + RequestFiles, + ResponseContent, + SyncByteStream, +) +from ._utils import peek_filelike_length, primitive_value_to_str + +__all__ = ["ByteStream"] + + +class ByteStream(AsyncByteStream, SyncByteStream): + def __init__(self, stream: bytes) -> None: + self._stream = stream + + def __iter__(self) -> Iterator[bytes]: + yield self._stream + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self._stream + + +class IteratorByteStream(SyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: Iterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isgenerator(stream) + + def __iter__(self) -> Iterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "read"): + # File-like interfaces should use 'read' directly. + chunk = self._stream.read(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = self._stream.read(self.CHUNK_SIZE) + else: + # Otherwise iterate. + for part in self._stream: + yield part + + +class AsyncIteratorByteStream(AsyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: AsyncIterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isasyncgen(stream) + + async def __aiter__(self) -> AsyncIterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "aread"): + # File-like interfaces should use 'aread' directly. + chunk = await self._stream.aread(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = await self._stream.aread(self.CHUNK_SIZE) + else: + # Otherwise iterate. + async for part in self._stream: + yield part + + +class UnattachedStream(AsyncByteStream, SyncByteStream): + """ + If a request or response is serialized using pickle, then it is no longer + attached to a stream for I/O purposes. Any stream operations should result + in `httpx.StreamClosed`. + """ + + def __iter__(self) -> Iterator[bytes]: + raise StreamClosed() + + async def __aiter__(self) -> AsyncIterator[bytes]: + raise StreamClosed() + yield b"" # pragma: no cover + + +def encode_content( + content: str | bytes | Iterable[bytes] | AsyncIterable[bytes], +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + if isinstance(content, (bytes, str)): + body = content.encode("utf-8") if isinstance(content, str) else content + content_length = len(body) + headers = {"Content-Length": str(content_length)} if body else {} + return headers, ByteStream(body) + + elif isinstance(content, Iterable) and not isinstance(content, dict): + # `not isinstance(content, dict)` is a bit oddly specific, but it + # catches a case that's easy for users to make in error, and would + # otherwise pass through here, like any other bytes-iterable, + # because `dict` happens to be iterable. See issue #2491. + content_length_or_none = peek_filelike_length(content) + + if content_length_or_none is None: + headers = {"Transfer-Encoding": "chunked"} + else: + headers = {"Content-Length": str(content_length_or_none)} + return headers, IteratorByteStream(content) # type: ignore + + elif isinstance(content, AsyncIterable): + headers = {"Transfer-Encoding": "chunked"} + return headers, AsyncIteratorByteStream(content) + + raise TypeError(f"Unexpected type for 'content', {type(content)!r}") + + +def encode_urlencoded_data( + data: RequestData, +) -> tuple[dict[str, str], ByteStream]: + plain_data = [] + for key, value in data.items(): + if isinstance(value, (list, tuple)): + plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) + else: + plain_data.append((key, primitive_value_to_str(value))) + body = urlencode(plain_data, doseq=True).encode("utf-8") + content_length = str(len(body)) + content_type = "application/x-www-form-urlencoded" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_multipart_data( + data: RequestData, files: RequestFiles, boundary: bytes | None +) -> tuple[dict[str, str], MultipartStream]: + multipart = MultipartStream(data=data, files=files, boundary=boundary) + headers = multipart.get_headers() + return headers, multipart + + +def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: + body = text.encode("utf-8") + content_length = str(len(body)) + content_type = "text/plain; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: + body = html.encode("utf-8") + content_length = str(len(body)) + content_type = "text/html; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: + body = json_dumps( + json, ensure_ascii=False, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + content_length = str(len(body)) + content_type = "application/json" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_request( + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: Any | None = None, + boundary: bytes | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, `data`, `files`, and `json`, + returning a two-tuple of (, ). + """ + if data is not None and not isinstance(data, Mapping): + # We prefer to separate `content=` + # for raw request content, and `data=
` for url encoded or + # multipart form content. + # + # However for compat with requests, we *do* still support + # `data=` usages. We deal with that case here, treating it + # as if `content=<...>` had been supplied instead. + message = "Use 'content=<...>' to upload raw bytes/text content." + warnings.warn(message, DeprecationWarning, stacklevel=2) + return encode_content(data) + + if content is not None: + return encode_content(content) + elif files: + return encode_multipart_data(data or {}, files, boundary) + elif data: + return encode_urlencoded_data(data) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") + + +def encode_response( + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: Any | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, returning a two-tuple of + (, ). + """ + if content is not None: + return encode_content(content) + elif text is not None: + return encode_text(text) + elif html is not None: + return encode_html(html) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_decoders.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..899dfada878e1181fca6d3c75a79526a076abb9e --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_decoders.py @@ -0,0 +1,393 @@ +""" +Handlers for Content-Encoding. + +See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding +""" + +from __future__ import annotations + +import codecs +import io +import typing +import zlib + +from ._exceptions import DecodingError + +# Brotli support is optional +try: + # The C bindings in `brotli` are recommended for CPython. + import brotli +except ImportError: # pragma: no cover + try: + # The CFFI bindings in `brotlicffi` are recommended for PyPy + # and other environments. + import brotlicffi as brotli + except ImportError: + brotli = None + + +# Zstandard support is optional +try: + import zstandard +except ImportError: # pragma: no cover + zstandard = None # type: ignore + + +class ContentDecoder: + def decode(self, data: bytes) -> bytes: + raise NotImplementedError() # pragma: no cover + + def flush(self) -> bytes: + raise NotImplementedError() # pragma: no cover + + +class IdentityDecoder(ContentDecoder): + """ + Handle unencoded data. + """ + + def decode(self, data: bytes) -> bytes: + return data + + def flush(self) -> bytes: + return b"" + + +class DeflateDecoder(ContentDecoder): + """ + Handle 'deflate' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.first_attempt = True + self.decompressor = zlib.decompressobj() + + def decode(self, data: bytes) -> bytes: + was_first_attempt = self.first_attempt + self.first_attempt = False + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + if was_first_attempt: + self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + return self.decode(data) + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class GZipDecoder(ContentDecoder): + """ + Handle 'gzip' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16) + + def decode(self, data: bytes) -> bytes: + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class BrotliDecoder(ContentDecoder): + """ + Handle 'brotli' decoding. + + Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ + or `pip install brotli`. See https://github.com/google/brotli + Supports both 'brotlipy' and 'Brotli' packages since they share an import + name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' + """ + + def __init__(self) -> None: + if brotli is None: # pragma: no cover + raise ImportError( + "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " + "packages have been installed. " + "Make sure to install httpx using `pip install httpx[brotli]`." + ) from None + + self.decompressor = brotli.Decompressor() + self.seen_data = False + self._decompress: typing.Callable[[bytes], bytes] + if hasattr(self.decompressor, "decompress"): + # The 'brotlicffi' package. + self._decompress = self.decompressor.decompress # pragma: no cover + else: + # The 'brotli' package. + self._decompress = self.decompressor.process # pragma: no cover + + def decode(self, data: bytes) -> bytes: + if not data: + return b"" + self.seen_data = True + try: + return self._decompress(data) + except brotli.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + try: + if hasattr(self.decompressor, "finish"): + # Only available in the 'brotlicffi' package. + + # As the decompressor decompresses eagerly, this + # will never actually emit any data. However, it will potentially throw + # errors if a truncated or damaged data stream has been used. + self.decompressor.finish() # pragma: no cover + return b"" + except brotli.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class ZStandardDecoder(ContentDecoder): + """ + Handle 'zstd' RFC 8878 decoding. + + Requires `pip install zstandard`. + Can be installed as a dependency of httpx using `pip install httpx[zstd]`. + """ + + # inspired by the ZstdDecoder implementation in urllib3 + def __init__(self) -> None: + if zstandard is None: # pragma: no cover + raise ImportError( + "Using 'ZStandardDecoder', ..." + "Make sure to install httpx using `pip install httpx[zstd]`." + ) from None + + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + self.seen_data = False + + def decode(self, data: bytes) -> bytes: + assert zstandard is not None + self.seen_data = True + output = io.BytesIO() + try: + output.write(self.decompressor.decompress(data)) + while self.decompressor.eof and self.decompressor.unused_data: + unused_data = self.decompressor.unused_data + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + output.write(self.decompressor.decompress(unused_data)) + except zstandard.ZstdError as exc: + raise DecodingError(str(exc)) from exc + return output.getvalue() + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + ret = self.decompressor.flush() # note: this is a no-op + if not self.decompressor.eof: + raise DecodingError("Zstandard data is incomplete") # pragma: no cover + return bytes(ret) + + +class MultiDecoder(ContentDecoder): + """ + Handle the case where multiple encodings have been applied. + """ + + def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: + """ + 'children' should be a sequence of decoders in the order in which + each was applied. + """ + # Note that we reverse the order for decoding. + self.children = list(reversed(children)) + + def decode(self, data: bytes) -> bytes: + for child in self.children: + data = child.decode(data) + return data + + def flush(self) -> bytes: + data = b"" + for child in self.children: + data = child.decode(data) + child.flush() + return data + + +class ByteChunker: + """ + Handles returning byte content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.BytesIO() + self._chunk_size = chunk_size + + def decode(self, content: bytes) -> list[bytes]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[bytes]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextChunker: + """ + Handles returning text content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.StringIO() + self._chunk_size = chunk_size + + def decode(self, content: str) -> list[str]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[str]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextDecoder: + """ + Handles incrementally decoding bytes into text + """ + + def __init__(self, encoding: str = "utf-8") -> None: + self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace") + + def decode(self, data: bytes) -> str: + return self.decoder.decode(data) + + def flush(self) -> str: + return self.decoder.decode(b"", True) + + +class LineDecoder: + """ + Handles incrementally reading lines from text. + + Has the same behaviour as the stdllib splitlines, + but handling the input iteratively. + """ + + def __init__(self) -> None: + self.buffer: list[str] = [] + self.trailing_cr: bool = False + + def decode(self, text: str) -> list[str]: + # See https://docs.python.org/3/library/stdtypes.html#str.splitlines + NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" + + # We always push a trailing `\r` into the next decode iteration. + if self.trailing_cr: + text = "\r" + text + self.trailing_cr = False + if text.endswith("\r"): + self.trailing_cr = True + text = text[:-1] + + if not text: + # NOTE: the edge case input of empty text doesn't occur in practice, + # because other httpx internals filter out this value + return [] # pragma: no cover + + trailing_newline = text[-1] in NEWLINE_CHARS + lines = text.splitlines() + + if len(lines) == 1 and not trailing_newline: + # No new lines, buffer the input and continue. + self.buffer.append(lines[0]) + return [] + + if self.buffer: + # Include any existing buffer in the first portion of the + # splitlines result. + lines = ["".join(self.buffer) + lines[0]] + lines[1:] + self.buffer = [] + + if not trailing_newline: + # If the last segment of splitlines is not newline terminated, + # then drop it from our output and start a new buffer. + self.buffer = [lines.pop()] + + return lines + + def flush(self) -> list[str]: + if not self.buffer and not self.trailing_cr: + return [] + + lines = ["".join(self.buffer)] + self.buffer = [] + self.trailing_cr = False + return lines + + +SUPPORTED_DECODERS = { + "identity": IdentityDecoder, + "gzip": GZipDecoder, + "deflate": DeflateDecoder, + "br": BrotliDecoder, + "zstd": ZStandardDecoder, +} + + +if brotli is None: + SUPPORTED_DECODERS.pop("br") # pragma: no cover +if zstandard is None: + SUPPORTED_DECODERS.pop("zstd") # pragma: no cover diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_exceptions.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..77f45a6d3986d15626fc8a5fd459d6a3e0fbe466 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_exceptions.py @@ -0,0 +1,379 @@ +""" +Our exception hierarchy: + +* HTTPError + x RequestError + + TransportError + - TimeoutException + · ConnectTimeout + · ReadTimeout + · WriteTimeout + · PoolTimeout + - NetworkError + · ConnectError + · ReadError + · WriteError + · CloseError + - ProtocolError + · LocalProtocolError + · RemoteProtocolError + - ProxyError + - UnsupportedProtocol + + DecodingError + + TooManyRedirects + x HTTPStatusError +* InvalidURL +* CookieConflict +* StreamError + x StreamConsumed + x StreamClosed + x ResponseNotRead + x RequestNotRead +""" + +from __future__ import annotations + +import contextlib +import typing + +if typing.TYPE_CHECKING: + from ._models import Request, Response # pragma: no cover + +__all__ = [ + "CloseError", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "DecodingError", + "HTTPError", + "HTTPStatusError", + "InvalidURL", + "LocalProtocolError", + "NetworkError", + "PoolTimeout", + "ProtocolError", + "ProxyError", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "RequestError", + "RequestNotRead", + "ResponseNotRead", + "StreamClosed", + "StreamConsumed", + "StreamError", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "WriteError", + "WriteTimeout", +] + + +class HTTPError(Exception): + """ + Base class for `RequestError` and `HTTPStatusError`. + + Useful for `try...except` blocks when issuing a request, + and then calling `.raise_for_status()`. + + For example: + + ``` + try: + response = httpx.get("https://www.example.com") + response.raise_for_status() + except httpx.HTTPError as exc: + print(f"HTTP Exception for {exc.request.url} - {exc}") + ``` + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + self._request: Request | None = None + + @property + def request(self) -> Request: + if self._request is None: + raise RuntimeError("The .request property has not been set.") + return self._request + + @request.setter + def request(self, request: Request) -> None: + self._request = request + + +class RequestError(HTTPError): + """ + Base class for all exceptions that may occur when issuing a `.request()`. + """ + + def __init__(self, message: str, *, request: Request | None = None) -> None: + super().__init__(message) + # At the point an exception is raised we won't typically have a request + # instance to associate it with. + # + # The 'request_context' context manager is used within the Client and + # Response methods in order to ensure that any raised exceptions + # have a `.request` property set on them. + self._request = request + + +class TransportError(RequestError): + """ + Base class for all exceptions that occur at the level of the Transport API. + """ + + +# Timeout exceptions... + + +class TimeoutException(TransportError): + """ + The base class for timeout errors. + + An operation has timed out. + """ + + +class ConnectTimeout(TimeoutException): + """ + Timed out while connecting to the host. + """ + + +class ReadTimeout(TimeoutException): + """ + Timed out while receiving data from the host. + """ + + +class WriteTimeout(TimeoutException): + """ + Timed out while sending data to the host. + """ + + +class PoolTimeout(TimeoutException): + """ + Timed out waiting to acquire a connection from the pool. + """ + + +# Core networking exceptions... + + +class NetworkError(TransportError): + """ + The base class for network-related errors. + + An error occurred while interacting with the network. + """ + + +class ReadError(NetworkError): + """ + Failed to receive data from the network. + """ + + +class WriteError(NetworkError): + """ + Failed to send data through the network. + """ + + +class ConnectError(NetworkError): + """ + Failed to establish a connection. + """ + + +class CloseError(NetworkError): + """ + Failed to close a connection. + """ + + +# Other transport exceptions... + + +class ProxyError(TransportError): + """ + An error occurred while establishing a proxy connection. + """ + + +class UnsupportedProtocol(TransportError): + """ + Attempted to make a request to an unsupported protocol. + + For example issuing a request to `ftp://www.example.com`. + """ + + +class ProtocolError(TransportError): + """ + The protocol was violated. + """ + + +class LocalProtocolError(ProtocolError): + """ + A protocol was violated by the client. + + For example if the user instantiated a `Request` instance explicitly, + failed to include the mandatory `Host:` header, and then issued it directly + using `client.send()`. + """ + + +class RemoteProtocolError(ProtocolError): + """ + The protocol was violated by the server. + + For example, returning malformed HTTP. + """ + + +# Other request exceptions... + + +class DecodingError(RequestError): + """ + Decoding of the response failed, due to a malformed encoding. + """ + + +class TooManyRedirects(RequestError): + """ + Too many redirects. + """ + + +# Client errors + + +class HTTPStatusError(HTTPError): + """ + The response had an error HTTP status of 4xx or 5xx. + + May be raised when calling `response.raise_for_status()` + """ + + def __init__(self, message: str, *, request: Request, response: Response) -> None: + super().__init__(message) + self.request = request + self.response = response + + +class InvalidURL(Exception): + """ + URL is improperly formed or cannot be parsed. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class CookieConflict(Exception): + """ + Attempted to lookup a cookie by name, but multiple cookies existed. + + Can occur when calling `response.cookies.get(...)`. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +# Stream exceptions... + +# These may occur as the result of a programming error, by accessing +# the request/response stream in an invalid manner. + + +class StreamError(RuntimeError): + """ + The base class for stream exceptions. + + The developer made an error in accessing the request stream in + an invalid way. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class StreamConsumed(StreamError): + """ + Attempted to read or stream content, but the content has already + been streamed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. For requests, this could be due to passing " + "a generator as request content, and then receiving a redirect " + "response or a secondary request as part of an authentication flow." + "For responses, this could be due to attempting to stream the response " + "content more than once." + ) + super().__init__(message) + + +class StreamClosed(StreamError): + """ + Attempted to read or stream response content, but the request has been + closed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream content, but the stream has " "been closed." + ) + super().__init__(message) + + +class ResponseNotRead(StreamError): + """ + Attempted to access streaming response content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming response content," + " without having called `read()`." + ) + super().__init__(message) + + +class RequestNotRead(StreamError): + """ + Attempted to access streaming request content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming request content," + " without having called `read()`." + ) + super().__init__(message) + + +@contextlib.contextmanager +def request_context( + request: Request | None = None, +) -> typing.Iterator[None]: + """ + A context manager that can be used to attach the given request context + to any `RequestError` exceptions that are raised within the block. + """ + try: + yield + except RequestError as exc: + if request is not None: + exc.request = request + raise exc diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_main.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..cffa4bb7db0f930f4db56653a061c4d7400ba4e6 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_main.py @@ -0,0 +1,506 @@ +from __future__ import annotations + +import functools +import json +import sys +import typing + +import click +import pygments.lexers +import pygments.util +import rich.console +import rich.markup +import rich.progress +import rich.syntax +import rich.table + +from ._client import Client +from ._exceptions import RequestError +from ._models import Response +from ._status_codes import codes + +if typing.TYPE_CHECKING: + import httpcore # pragma: no cover + + +def print_help() -> None: + console = rich.console.Console() + + console.print("[bold]HTTPX :butterfly:", justify="center") + console.print() + console.print("A next generation HTTP client.", justify="center") + console.print() + console.print( + "Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] ", justify="left" + ) + console.print() + + table = rich.table.Table.grid(padding=1, pad_edge=True) + table.add_column("Parameter", no_wrap=True, justify="left", style="bold") + table.add_column("Description") + table.add_row( + "-m, --method [cyan]METHOD", + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" + "[Default: GET, or POST if a request body is included]", + ) + table.add_row( + "-p, --params [cyan] ...", + "Query parameters to include in the request URL.", + ) + table.add_row( + "-c, --content [cyan]TEXT", "Byte content to include in the request body." + ) + table.add_row( + "-d, --data [cyan] ...", "Form data to include in the request body." + ) + table.add_row( + "-f, --files [cyan] ...", + "Form files to include in the request body.", + ) + table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") + table.add_row( + "-h, --headers [cyan] ...", + "Include additional HTTP headers in the request.", + ) + table.add_row( + "--cookies [cyan] ...", "Cookies to include in the request." + ) + table.add_row( + "--auth [cyan]", + "Username and password to include in the request. Specify '-' for the password" + " to use a password prompt. Note that using --verbose/-v will expose" + " the Authorization header, including the password encoding" + " in a trivially reversible format.", + ) + + table.add_row( + "--proxy [cyan]URL", + "Send the request via a proxy. Should be the URL giving the proxy address.", + ) + + table.add_row( + "--timeout [cyan]FLOAT", + "Timeout value to use for network operations, such as establishing the" + " connection, reading some data, etc... [Default: 5.0]", + ) + + table.add_row("--follow-redirects", "Automatically follow redirects.") + table.add_row("--no-verify", "Disable SSL verification.") + table.add_row( + "--http2", "Send the request using HTTP/2, if the remote server supports it." + ) + + table.add_row( + "--download [cyan]FILE", + "Save the response content as a file, rather than displaying it.", + ) + + table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") + table.add_row("--help", "Show this message and exit.") + console.print(table) + + +def get_lexer_for_response(response: Response) -> str: + content_type = response.headers.get("Content-Type") + if content_type is not None: + mime_type, _, _ = content_type.partition(";") + try: + return typing.cast( + str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name + ) + except pygments.util.ClassNotFound: # pragma: no cover + pass + return "" # pragma: no cover + + +def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: + version = "HTTP/2" if http2 else "HTTP/1.1" + headers = [ + (name.lower() if http2 else name, value) for name, value in request.headers + ] + method = request.method.decode("ascii") + target = request.url.target.decode("ascii") + lines = [f"{method} {target} {version}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def format_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> str: + version = http_version.decode("ascii") + reason = ( + codes.get_reason_phrase(status) + if reason_phrase is None + else reason_phrase.decode("ascii") + ) + lines = [f"{version} {status} {reason}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: + console = rich.console.Console() + http_text = format_request_headers(request, http2=http2) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> None: + console = rich.console.Console() + http_text = format_response_headers(http_version, status, reason_phrase, headers) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response(response: Response) -> None: + console = rich.console.Console() + lexer_name = get_lexer_for_response(response) + if lexer_name: + if lexer_name.lower() == "json": + try: + data = response.json() + text = json.dumps(data, indent=4) + except ValueError: # pragma: no cover + text = response.text + else: + text = response.text + + syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) + console.print(syntax) + else: + console.print(f"<{len(response.content)} bytes of binary data>") + + +_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...] +_PCTRTTT = typing.Tuple[_PCTRTT, ...] +_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]] + + +def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover + lines = [] + for key, value in cert.items(): + if isinstance(value, (list, tuple)): + lines.append(f"* {key}:") + for item in value: + if key in ("subject", "issuer"): + for sub_item in item: + lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") + elif isinstance(item, tuple) and len(item) == 2: + lines.append(f"* {item[0]}: {item[1]!r}") + else: + lines.append(f"* {item!r}") + else: + lines.append(f"* {key}: {value!r}") + return "\n".join(lines) + + +def trace( + name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False +) -> None: + console = rich.console.Console() + if name == "connection.connect_tcp.started" and verbose: + host = info["host"] + console.print(f"* Connecting to {host!r}") + elif name == "connection.connect_tcp.complete" and verbose: + stream = info["return_value"] + server_addr = stream.get_extra_info("server_addr") + console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") + elif name == "connection.start_tls.complete" and verbose: # pragma: no cover + stream = info["return_value"] + ssl_object = stream.get_extra_info("ssl_object") + version = ssl_object.version() + cipher = ssl_object.cipher() + server_cert = ssl_object.getpeercert() + alpn = ssl_object.selected_alpn_protocol() + console.print(f"* SSL established using {version!r} / {cipher[0]!r}") + console.print(f"* Selected ALPN protocol: {alpn!r}") + if server_cert: + console.print("* Server certificate:") + console.print(format_certificate(server_cert)) + elif name == "http11.send_request_headers.started" and verbose: + request = info["request"] + print_request_headers(request, http2=False) + elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover + request = info["request"] + print_request_headers(request, http2=True) + elif name == "http11.receive_response_headers.complete": + http_version, status, reason_phrase, headers = info["return_value"] + print_response_headers(http_version, status, reason_phrase, headers) + elif name == "http2.receive_response_headers.complete": # pragma: no cover + status, headers = info["return_value"] + http_version = b"HTTP/2" + reason_phrase = None + print_response_headers(http_version, status, reason_phrase, headers) + + +def download_response(response: Response, download: typing.BinaryIO) -> None: + console = rich.console.Console() + console.print() + content_length = response.headers.get("Content-Length") + with rich.progress.Progress( + "[progress.description]{task.description}", + "[progress.percentage]{task.percentage:>3.0f}%", + rich.progress.BarColumn(bar_width=None), + rich.progress.DownloadColumn(), + rich.progress.TransferSpeedColumn(), + ) as progress: + description = f"Downloading [bold]{rich.markup.escape(download.name)}" + download_task = progress.add_task( + description, + total=int(content_length or 0), + start=content_length is not None, + ) + for chunk in response.iter_bytes(): + download.write(chunk) + progress.update(download_task, completed=response.num_bytes_downloaded) + + +def validate_json( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value is None: + return None + + try: + return json.loads(value) + except json.JSONDecodeError: # pragma: no cover + raise click.BadParameter("Not valid JSON") + + +def validate_auth( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value == (None, None): + return None + + username, password = value + if password == "-": # pragma: no cover + password = click.prompt("Password", hide_input=True) + return (username, password) + + +def handle_help( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> None: + if not value or ctx.resilient_parsing: + return + + print_help() + ctx.exit() + + +@click.command(add_help_option=False) +@click.argument("url", type=str) +@click.option( + "--method", + "-m", + "method", + type=str, + help=( + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " + "[Default: GET, or POST if a request body is included]" + ), +) +@click.option( + "--params", + "-p", + "params", + type=(str, str), + multiple=True, + help="Query parameters to include in the request URL.", +) +@click.option( + "--content", + "-c", + "content", + type=str, + help="Byte content to include in the request body.", +) +@click.option( + "--data", + "-d", + "data", + type=(str, str), + multiple=True, + help="Form data to include in the request body.", +) +@click.option( + "--files", + "-f", + "files", + type=(str, click.File(mode="rb")), + multiple=True, + help="Form files to include in the request body.", +) +@click.option( + "--json", + "-j", + "json", + type=str, + callback=validate_json, + help="JSON data to include in the request body.", +) +@click.option( + "--headers", + "-h", + "headers", + type=(str, str), + multiple=True, + help="Include additional HTTP headers in the request.", +) +@click.option( + "--cookies", + "cookies", + type=(str, str), + multiple=True, + help="Cookies to include in the request.", +) +@click.option( + "--auth", + "auth", + type=(str, str), + default=(None, None), + callback=validate_auth, + help=( + "Username and password to include in the request. " + "Specify '-' for the password to use a password prompt. " + "Note that using --verbose/-v will expose the Authorization header, " + "including the password encoding in a trivially reversible format." + ), +) +@click.option( + "--proxy", + "proxy", + type=str, + default=None, + help="Send the request via a proxy. Should be the URL giving the proxy address.", +) +@click.option( + "--timeout", + "timeout", + type=float, + default=5.0, + help=( + "Timeout value to use for network operations, such as establishing the " + "connection, reading some data, etc... [Default: 5.0]" + ), +) +@click.option( + "--follow-redirects", + "follow_redirects", + is_flag=True, + default=False, + help="Automatically follow redirects.", +) +@click.option( + "--no-verify", + "verify", + is_flag=True, + default=True, + help="Disable SSL verification.", +) +@click.option( + "--http2", + "http2", + type=bool, + is_flag=True, + default=False, + help="Send the request using HTTP/2, if the remote server supports it.", +) +@click.option( + "--download", + type=click.File("wb"), + help="Save the response content as a file, rather than displaying it.", +) +@click.option( + "--verbose", + "-v", + type=bool, + is_flag=True, + default=False, + help="Verbose. Show request as well as response.", +) +@click.option( + "--help", + is_flag=True, + is_eager=True, + expose_value=False, + callback=handle_help, + help="Show this message and exit.", +) +def main( + url: str, + method: str, + params: list[tuple[str, str]], + content: str, + data: list[tuple[str, str]], + files: list[tuple[str, click.File]], + json: str, + headers: list[tuple[str, str]], + cookies: list[tuple[str, str]], + auth: tuple[str, str] | None, + proxy: str, + timeout: float, + follow_redirects: bool, + verify: bool, + http2: bool, + download: typing.BinaryIO | None, + verbose: bool, +) -> None: + """ + An HTTP command line client. + Sends a request and displays the response. + """ + if not method: + method = "POST" if content or data or files or json else "GET" + + try: + with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: + with client.stream( + method, + url, + params=list(params), + content=content, + data=dict(data), + files=files, # type: ignore + json=json, + headers=headers, + cookies=dict(cookies), + auth=auth, + follow_redirects=follow_redirects, + extensions={"trace": functools.partial(trace, verbose=verbose)}, + ) as response: + if download is not None: + download_response(response, download) + else: + response.read() + if response.content: + print_response(response) + + except RequestError as exc: + console = rich.console.Console() + console.print(f"[red]{type(exc).__name__}[/red]: {exc}") + sys.exit(1) + + sys.exit(0 if response.is_success else 1) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_models.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..67d74bf86bfc80e22d9a4a3153572845accd9039 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_models.py @@ -0,0 +1,1277 @@ +from __future__ import annotations + +import codecs +import datetime +import email.message +import json as jsonlib +import re +import typing +import urllib.request +from collections.abc import Mapping +from http.cookiejar import Cookie, CookieJar + +from ._content import ByteStream, UnattachedStream, encode_request, encode_response +from ._decoders import ( + SUPPORTED_DECODERS, + ByteChunker, + ContentDecoder, + IdentityDecoder, + LineDecoder, + MultiDecoder, + TextChunker, + TextDecoder, +) +from ._exceptions import ( + CookieConflict, + HTTPStatusError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + request_context, +) +from ._multipart import get_multipart_boundary_from_content_type +from ._status_codes import codes +from ._types import ( + AsyncByteStream, + CookieTypes, + HeaderTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + ResponseContent, + ResponseExtensions, + SyncByteStream, +) +from ._urls import URL +from ._utils import to_bytes_or_str, to_str + +__all__ = ["Cookies", "Headers", "Request", "Response"] + +SENSITIVE_HEADERS = {"authorization", "proxy-authorization"} + + +def _is_known_encoding(encoding: str) -> bool: + """ + Return `True` if `encoding` is a known codec. + """ + try: + codecs.lookup(encoding) + except LookupError: + return False + return True + + +def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header key. + """ + return key if isinstance(key, bytes) else key.encode(encoding or "ascii") + + +def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header value. + """ + if isinstance(value, bytes): + return value + if not isinstance(value, str): + raise TypeError(f"Header value must be str or bytes, not {type(value)}") + return value.encode(encoding or "ascii") + + +def _parse_content_type_charset(content_type: str) -> str | None: + # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. + # See: https://peps.python.org/pep-0594/#cgi + msg = email.message.Message() + msg["content-type"] = content_type + return msg.get_content_charset(failobj=None) + + +def _parse_header_links(value: str) -> list[dict[str, str]]: + """ + Returns a list of parsed link headers, for more info see: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link + The generic syntax of those is: + Link: < uri-reference >; param1=value1; param2="value2" + So for instance: + Link; '; type="image/jpeg",;' + would return + [ + {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, + {"url": "http://.../back.jpeg"}, + ] + :param value: HTTP Link entity-header field + :return: list of parsed link headers + """ + links: list[dict[str, str]] = [] + replace_chars = " '\"" + value = value.strip(replace_chars) + if not value: + return links + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + link = {"url": url.strip("<> '\"")} + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + link[key.strip(replace_chars)] = value.strip(replace_chars) + links.append(link) + return links + + +def _obfuscate_sensitive_headers( + items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]], +) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: + for k, v in items: + if to_str(k.lower()) in SENSITIVE_HEADERS: + v = to_bytes_or_str("[secure]", match_type_of=v) + yield k, v + + +class Headers(typing.MutableMapping[str, str]): + """ + HTTP headers, as a case-insensitive multi-dict. + """ + + def __init__( + self, + headers: HeaderTypes | None = None, + encoding: str | None = None, + ) -> None: + self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]] + + if isinstance(headers, Headers): + self._list = list(headers._list) + elif isinstance(headers, Mapping): + for k, v in headers.items(): + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + elif headers is not None: + for k, v in headers: + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + + self._encoding = encoding + + @property + def encoding(self) -> str: + """ + Header encoding is mandated as ascii, but we allow fallbacks to utf-8 + or iso-8859-1. + """ + if self._encoding is None: + for encoding in ["ascii", "utf-8"]: + for key, value in self.raw: + try: + key.decode(encoding) + value.decode(encoding) + except UnicodeDecodeError: + break + else: + # The else block runs if 'break' did not occur, meaning + # all values fitted the encoding. + self._encoding = encoding + break + else: + # The ISO-8859-1 encoding covers all 256 code points in a byte, + # so will never raise decode errors. + self._encoding = "iso-8859-1" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + self._encoding = value + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + """ + Returns a list of the raw header items, as byte pairs. + """ + return [(raw_key, value) for raw_key, _, value in self._list] + + def keys(self) -> typing.KeysView[str]: + return {key.decode(self.encoding): None for _, key, value in self._list}.keys() + + def values(self) -> typing.ValuesView[str]: + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return `(key, value)` items of headers. Concatenate headers + into a single comma separated value when a key occurs multiple times. + """ + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return a list of `(key, value)` pairs of headers. Allow multiple + occurrences of the same key without concatenating into a single + comma separated value. + """ + return [ + (key.decode(self.encoding), value.decode(self.encoding)) + for _, key, value in self._list + ] + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Return a header value. If multiple occurrences of the header occur + then concatenate them together with commas. + """ + try: + return self[key] + except KeyError: + return default + + def get_list(self, key: str, split_commas: bool = False) -> list[str]: + """ + Return a list of all header values for a given key. + If `split_commas=True` is passed, then any comma separated header + values are split into multiple return strings. + """ + get_header_key = key.lower().encode(self.encoding) + + values = [ + item_value.decode(self.encoding) + for _, item_key, item_value in self._list + if item_key.lower() == get_header_key + ] + + if not split_commas: + return values + + split_values = [] + for value in values: + split_values.extend([item.strip() for item in value.split(",")]) + return split_values + + def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore + headers = Headers(headers) + for key in headers.keys(): + if key in self: + self.pop(key) + self._list.extend(headers._list) + + def copy(self) -> Headers: + return Headers(self, encoding=self.encoding) + + def __getitem__(self, key: str) -> str: + """ + Return a single header value. + + If there are multiple headers with the same key, then we concatenate + them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 + """ + normalized_key = key.lower().encode(self.encoding) + + items = [ + header_value.decode(self.encoding) + for _, header_key, header_value in self._list + if header_key == normalized_key + ] + + if items: + return ", ".join(items) + + raise KeyError(key) + + def __setitem__(self, key: str, value: str) -> None: + """ + Set the header `key` to `value`, removing any duplicate entries. + Retains insertion order. + """ + set_key = key.encode(self._encoding or "utf-8") + set_value = value.encode(self._encoding or "utf-8") + lookup_key = set_key.lower() + + found_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key == lookup_key + ] + + for idx in reversed(found_indexes[1:]): + del self._list[idx] + + if found_indexes: + idx = found_indexes[0] + self._list[idx] = (set_key, lookup_key, set_value) + else: + self._list.append((set_key, lookup_key, set_value)) + + def __delitem__(self, key: str) -> None: + """ + Remove the header `key`. + """ + del_key = key.lower().encode(self.encoding) + + pop_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key.lower() == del_key + ] + + if not pop_indexes: + raise KeyError(key) + + for idx in reversed(pop_indexes): + del self._list[idx] + + def __contains__(self, key: typing.Any) -> bool: + header_key = key.lower().encode(self.encoding) + return header_key in [key for _, key, _ in self._list] + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._list) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_headers = Headers(other) + except ValueError: + return False + + self_list = [(key, value) for _, key, value in self._list] + other_list = [(key, value) for _, key, value in other_headers._list] + return sorted(self_list) == sorted(other_list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + + encoding_str = "" + if self.encoding != "ascii": + encoding_str = f", encoding={self.encoding!r}" + + as_list = list(_obfuscate_sensitive_headers(self.multi_items())) + as_dict = dict(as_list) + + no_duplicate_keys = len(as_dict) == len(as_list) + if no_duplicate_keys: + return f"{class_name}({as_dict!r}{encoding_str})" + return f"{class_name}({as_list!r}{encoding_str})" + + +class Request: + def __init__( + self, + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + stream: SyncByteStream | AsyncByteStream | None = None, + extensions: RequestExtensions | None = None, + ) -> None: + self.method = method.upper() + self.url = URL(url) if params is None else URL(url, params=params) + self.headers = Headers(headers) + self.extensions = {} if extensions is None else dict(extensions) + + if cookies: + Cookies(cookies).set_cookie_header(self) + + if stream is None: + content_type: str | None = self.headers.get("content-type") + headers, stream = encode_request( + content=content, + data=data, + files=files, + json=json, + boundary=get_multipart_boundary_from_content_type( + content_type=content_type.encode(self.headers.encoding) + if content_type + else None + ), + ) + self._prepare(headers) + self.stream = stream + # Load the request body, except for streaming content. + if isinstance(stream, ByteStream): + self.read() + else: + # There's an important distinction between `Request(content=...)`, + # and `Request(stream=...)`. + # + # Using `content=...` implies automatically populated `Host` and content + # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include *any* + # auto-populated headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when: + # + # * Preserving the request stream when copying requests, eg for redirects. + # * Creating request instances on the *server-side* of the transport API. + self.stream = stream + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: + continue + self.headers.setdefault(key, value) + + auto_headers: list[tuple[bytes, bytes]] = [] + + has_host = "Host" in self.headers + has_content_length = ( + "Content-Length" in self.headers or "Transfer-Encoding" in self.headers + ) + + if not has_host and self.url.host: + auto_headers.append((b"Host", self.url.netloc)) + if not has_content_length and self.method in ("POST", "PUT", "PATCH"): + auto_headers.append((b"Content-Length", b"0")) + + self.headers = Headers(auto_headers + self.headers.raw) + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise RequestNotRead() + return self._content + + def read(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.Iterable) + self._content = b"".join(self.stream) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + async def aread(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.AsyncIterable) + self._content = b"".join([part async for part in self.stream]) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + url = str(self.url) + return f"<{class_name}({self.method!r}, {url!r})>" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.extensions = {} + self.stream = UnattachedStream() + + +class Response: + def __init__( + self, + status_code: int, + *, + headers: HeaderTypes | None = None, + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: typing.Any = None, + stream: SyncByteStream | AsyncByteStream | None = None, + request: Request | None = None, + extensions: ResponseExtensions | None = None, + history: list[Response] | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + self.status_code = status_code + self.headers = Headers(headers) + + self._request: Request | None = request + + # When follow_redirects=False and a redirect is received, + # the client will set `response.next_request`. + self.next_request: Request | None = None + + self.extensions = {} if extensions is None else dict(extensions) + self.history = [] if history is None else list(history) + + self.is_closed = False + self.is_stream_consumed = False + + self.default_encoding = default_encoding + + if stream is None: + headers, stream = encode_response(content, text, html, json) + self._prepare(headers) + self.stream = stream + if isinstance(stream, ByteStream): + # Load the response body, except for streaming content. + self.read() + else: + # There's an important distinction between `Response(content=...)`, + # and `Response(stream=...)`. + # + # Using `content=...` implies automatically populated content headers, + # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include any content headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when creating response instances having received a stream + # from the transport API. + self.stream = stream + + self._num_bytes_downloaded = 0 + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "content-length" in self.headers: + continue + self.headers.setdefault(key, value) + + @property + def elapsed(self) -> datetime.timedelta: + """ + Returns the time taken for the complete request/response + cycle to complete. + """ + if not hasattr(self, "_elapsed"): + raise RuntimeError( + "'.elapsed' may only be accessed after the response " + "has been read or closed." + ) + return self._elapsed + + @elapsed.setter + def elapsed(self, elapsed: datetime.timedelta) -> None: + self._elapsed = elapsed + + @property + def request(self) -> Request: + """ + Returns the request instance associated to the current response. + """ + if self._request is None: + raise RuntimeError( + "The request instance has not been set on this response." + ) + return self._request + + @request.setter + def request(self, value: Request) -> None: + self._request = value + + @property + def http_version(self) -> str: + try: + http_version: bytes = self.extensions["http_version"] + except KeyError: + return "HTTP/1.1" + else: + return http_version.decode("ascii", errors="ignore") + + @property + def reason_phrase(self) -> str: + try: + reason_phrase: bytes = self.extensions["reason_phrase"] + except KeyError: + return codes.get_reason_phrase(self.status_code) + else: + return reason_phrase.decode("ascii", errors="ignore") + + @property + def url(self) -> URL: + """ + Returns the URL for which the request was made. + """ + return self.request.url + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise ResponseNotRead() + return self._content + + @property + def text(self) -> str: + if not hasattr(self, "_text"): + content = self.content + if not content: + self._text = "" + else: + decoder = TextDecoder(encoding=self.encoding or "utf-8") + self._text = "".join([decoder.decode(self.content), decoder.flush()]) + return self._text + + @property + def encoding(self) -> str | None: + """ + Return an encoding to use for decoding the byte content into text. + The priority for determining this is given by... + + * `.encoding = <>` has been set explicitly. + * The encoding as specified by the charset parameter in the Content-Type header. + * The encoding as determined by `default_encoding`, which may either be + a string like "utf-8" indicating the encoding to use, or may be a callable + which enables charset autodetection. + """ + if not hasattr(self, "_encoding"): + encoding = self.charset_encoding + if encoding is None or not _is_known_encoding(encoding): + if isinstance(self.default_encoding, str): + encoding = self.default_encoding + elif hasattr(self, "_content"): + encoding = self.default_encoding(self._content) + self._encoding = encoding or "utf-8" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + """ + Set the encoding to use for decoding the byte content into text. + + If the `text` attribute has been accessed, attempting to set the + encoding will throw a ValueError. + """ + if hasattr(self, "_text"): + raise ValueError( + "Setting encoding after `text` has been accessed is not allowed." + ) + self._encoding = value + + @property + def charset_encoding(self) -> str | None: + """ + Return the encoding, as specified by the Content-Type header. + """ + content_type = self.headers.get("Content-Type") + if content_type is None: + return None + + return _parse_content_type_charset(content_type) + + def _get_content_decoder(self) -> ContentDecoder: + """ + Returns a decoder instance which can be used to decode the raw byte + content, depending on the Content-Encoding used in the response. + """ + if not hasattr(self, "_decoder"): + decoders: list[ContentDecoder] = [] + values = self.headers.get_list("content-encoding", split_commas=True) + for value in values: + value = value.strip().lower() + try: + decoder_cls = SUPPORTED_DECODERS[value] + decoders.append(decoder_cls()) + except KeyError: + continue + + if len(decoders) == 1: + self._decoder = decoders[0] + elif len(decoders) > 1: + self._decoder = MultiDecoder(children=decoders) + else: + self._decoder = IdentityDecoder() + + return self._decoder + + @property + def is_informational(self) -> bool: + """ + A property which is `True` for 1xx status codes, `False` otherwise. + """ + return codes.is_informational(self.status_code) + + @property + def is_success(self) -> bool: + """ + A property which is `True` for 2xx status codes, `False` otherwise. + """ + return codes.is_success(self.status_code) + + @property + def is_redirect(self) -> bool: + """ + A property which is `True` for 3xx status codes, `False` otherwise. + + Note that not all responses with a 3xx status code indicate a URL redirect. + + Use `response.has_redirect_location` to determine responses with a properly + formed URL redirection. + """ + return codes.is_redirect(self.status_code) + + @property + def is_client_error(self) -> bool: + """ + A property which is `True` for 4xx status codes, `False` otherwise. + """ + return codes.is_client_error(self.status_code) + + @property + def is_server_error(self) -> bool: + """ + A property which is `True` for 5xx status codes, `False` otherwise. + """ + return codes.is_server_error(self.status_code) + + @property + def is_error(self) -> bool: + """ + A property which is `True` for 4xx and 5xx status codes, `False` otherwise. + """ + return codes.is_error(self.status_code) + + @property + def has_redirect_location(self) -> bool: + """ + Returns True for 3xx responses with a properly formed URL redirection, + `False` otherwise. + """ + return ( + self.status_code + in ( + # 301 (Cacheable redirect. Method may change to GET.) + codes.MOVED_PERMANENTLY, + # 302 (Uncacheable redirect. Method may change to GET.) + codes.FOUND, + # 303 (Client should make a GET or HEAD request.) + codes.SEE_OTHER, + # 307 (Equiv. 302, but retain method) + codes.TEMPORARY_REDIRECT, + # 308 (Equiv. 301, but retain method) + codes.PERMANENT_REDIRECT, + ) + and "Location" in self.headers + ) + + def raise_for_status(self) -> Response: + """ + Raise the `HTTPStatusError` if one occurred. + """ + request = self._request + if request is None: + raise RuntimeError( + "Cannot call `raise_for_status` as the request " + "instance has not been set on this response." + ) + + if self.is_success: + return self + + if self.has_redirect_location: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "Redirect location: '{0.headers[location]}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + else: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + + status_class = self.status_code // 100 + error_types = { + 1: "Informational response", + 3: "Redirect response", + 4: "Client error", + 5: "Server error", + } + error_type = error_types.get(status_class, "Invalid status code") + message = message.format(self, error_type=error_type) + raise HTTPStatusError(message, request=request, response=self) + + def json(self, **kwargs: typing.Any) -> typing.Any: + return jsonlib.loads(self.content, **kwargs) + + @property + def cookies(self) -> Cookies: + if not hasattr(self, "_cookies"): + self._cookies = Cookies() + self._cookies.extract_cookies(self) + return self._cookies + + @property + def links(self) -> dict[str | None, dict[str, str]]: + """ + Returns the parsed header links of the response, if any + """ + header = self.headers.get("link") + if header is None: + return {} + + return { + (link.get("rel") or link.get("url")): link + for link in _parse_header_links(header) + } + + @property + def num_bytes_downloaded(self) -> int: + return self._num_bytes_downloaded + + def __repr__(self) -> str: + return f"" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream", "is_closed", "_decoder"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.is_closed = True + self.extensions = {} + self.stream = UnattachedStream() + + def read(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join(self.iter_bytes()) + return self._content + + def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for raw_bytes in self.iter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for byte_content in self.iter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_lines(self) -> typing.Iterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + for text in self.iter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call a sync iterator on an async stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call an sync close on an async stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + self.stream.close() + + async def aread(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_bytes()]) + return self._content + + async def aiter_bytes( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for raw_bytes in self.aiter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_text( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for byte_content in self.aiter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_lines(self) -> typing.AsyncIterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + async for text in self.aiter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + async def aiter_raw( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async iterator on an sync stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + async for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + await self.aclose() + + async def aclose(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async close on an sync stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + await self.stream.aclose() + + +class Cookies(typing.MutableMapping[str, str]): + """ + HTTP Cookies, as a mutable mapping. + """ + + def __init__(self, cookies: CookieTypes | None = None) -> None: + if cookies is None or isinstance(cookies, dict): + self.jar = CookieJar() + if isinstance(cookies, dict): + for key, value in cookies.items(): + self.set(key, value) + elif isinstance(cookies, list): + self.jar = CookieJar() + for key, value in cookies: + self.set(key, value) + elif isinstance(cookies, Cookies): + self.jar = CookieJar() + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + else: + self.jar = cookies + + def extract_cookies(self, response: Response) -> None: + """ + Loads any cookies based on the response `Set-Cookie` headers. + """ + urllib_response = self._CookieCompatResponse(response) + urllib_request = self._CookieCompatRequest(response.request) + + self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore + + def set_cookie_header(self, request: Request) -> None: + """ + Sets an appropriate 'Cookie:' HTTP header on the `Request`. + """ + urllib_request = self._CookieCompatRequest(request) + self.jar.add_cookie_header(urllib_request) + + def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: + """ + Set a cookie value by name. May optionally include domain and path. + """ + kwargs = { + "version": 0, + "name": name, + "value": value, + "port": None, + "port_specified": False, + "domain": domain, + "domain_specified": bool(domain), + "domain_initial_dot": domain.startswith("."), + "path": path, + "path_specified": bool(path), + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + cookie = Cookie(**kwargs) # type: ignore + self.jar.set_cookie(cookie) + + def get( # type: ignore + self, + name: str, + default: str | None = None, + domain: str | None = None, + path: str | None = None, + ) -> str | None: + """ + Get a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to retrieve. + """ + value = None + for cookie in self.jar: + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if value is not None: + message = f"Multiple cookies exist with name={name}" + raise CookieConflict(message) + value = cookie.value + + if value is None: + return default + return value + + def delete( + self, + name: str, + domain: str | None = None, + path: str | None = None, + ) -> None: + """ + Delete a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to delete. + """ + if domain is not None and path is not None: + return self.jar.clear(domain, path, name) + + remove = [ + cookie + for cookie in self.jar + if cookie.name == name + and (domain is None or cookie.domain == domain) + and (path is None or cookie.path == path) + ] + + for cookie in remove: + self.jar.clear(cookie.domain, cookie.path, cookie.name) + + def clear(self, domain: str | None = None, path: str | None = None) -> None: + """ + Delete all cookies. Optionally include a domain and path in + order to only delete a subset of all the cookies. + """ + args = [] + if domain is not None: + args.append(domain) + if path is not None: + assert domain is not None + args.append(path) + self.jar.clear(*args) + + def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore + cookies = Cookies(cookies) + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + + def __setitem__(self, name: str, value: str) -> None: + return self.set(name, value) + + def __getitem__(self, name: str) -> str: + value = self.get(name) + if value is None: + raise KeyError(name) + return value + + def __delitem__(self, name: str) -> None: + return self.delete(name) + + def __len__(self) -> int: + return len(self.jar) + + def __iter__(self) -> typing.Iterator[str]: + return (cookie.name for cookie in self.jar) + + def __bool__(self) -> bool: + for _ in self.jar: + return True + return False + + def __repr__(self) -> str: + cookies_repr = ", ".join( + [ + f"" + for cookie in self.jar + ] + ) + + return f"" + + class _CookieCompatRequest(urllib.request.Request): + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, request: Request) -> None: + super().__init__( + url=str(request.url), + headers=dict(request.headers), + method=request.method, + ) + self.request = request + + def add_unredirected_header(self, key: str, value: str) -> None: + super().add_unredirected_header(key, value) + self.request.headers[key] = value + + class _CookieCompatResponse: + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, response: Response) -> None: + self.response = response + + def info(self) -> email.message.Message: + info = email.message.Message() + for key, value in self.response.headers.multi_items(): + # Note that setting `info[key]` here is an "append" operation, + # not a "replace" operation. + # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ + info[key] = value + return info diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_multipart.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..b4761af9b2cf384de5189269927d781a700dbe46 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_multipart.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import io +import mimetypes +import os +import re +import typing +from pathlib import Path + +from ._types import ( + AsyncByteStream, + FileContent, + FileTypes, + RequestData, + RequestFiles, + SyncByteStream, +) +from ._utils import ( + peek_filelike_length, + primitive_value_to_str, + to_bytes, +) + +_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"} +_HTML5_FORM_ENCODING_REPLACEMENTS.update( + {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B} +) +_HTML5_FORM_ENCODING_RE = re.compile( + r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]) +) + + +def _format_form_param(name: str, value: str) -> bytes: + """ + Encode a name/value pair within a multipart form. + """ + + def replacer(match: typing.Match[str]) -> str: + return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] + + value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) + return f'{name}="{value}"'.encode() + + +def _guess_content_type(filename: str | None) -> str | None: + """ + Guesses the mimetype based on a filename. Defaults to `application/octet-stream`. + + Returns `None` if `filename` is `None` or empty. + """ + if filename: + return mimetypes.guess_type(filename)[0] or "application/octet-stream" + return None + + +def get_multipart_boundary_from_content_type( + content_type: bytes | None, +) -> bytes | None: + if not content_type or not content_type.startswith(b"multipart/form-data"): + return None + # parse boundary according to + # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 + if b";" in content_type: + for section in content_type.split(b";"): + if section.strip().lower().startswith(b"boundary="): + return section.strip()[len(b"boundary=") :].strip(b'"') + return None + + +class DataField: + """ + A single form field item, within a multipart form field. + """ + + def __init__(self, name: str, value: str | bytes | int | float | None) -> None: + if not isinstance(name, str): + raise TypeError( + f"Invalid type for name. Expected str, got {type(name)}: {name!r}" + ) + if value is not None and not isinstance(value, (str, bytes, int, float)): + raise TypeError( + "Invalid type for value. Expected primitive type," + f" got {type(value)}: {value!r}" + ) + self.name = name + self.value: str | bytes = ( + value if isinstance(value, bytes) else primitive_value_to_str(value) + ) + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + name = _format_form_param("name", self.name) + self._headers = b"".join( + [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] + ) + + return self._headers + + def render_data(self) -> bytes: + if not hasattr(self, "_data"): + self._data = to_bytes(self.value) + + return self._data + + def get_length(self) -> int: + headers = self.render_headers() + data = self.render_data() + return len(headers) + len(data) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield self.render_data() + + +class FileField: + """ + A single file field item, within a multipart form field. + """ + + CHUNK_SIZE = 64 * 1024 + + def __init__(self, name: str, value: FileTypes) -> None: + self.name = name + + fileobj: FileContent + + headers: dict[str, str] = {} + content_type: str | None = None + + # This large tuple based API largely mirror's requests' API + # It would be good to think of better APIs for this that we could + # include in httpx 2.0 since variable length tuples(especially of 4 elements) + # are quite unwieldly + if isinstance(value, tuple): + if len(value) == 2: + # neither the 3rd parameter (content_type) nor the 4th (headers) + # was included + filename, fileobj = value + elif len(value) == 3: + filename, fileobj, content_type = value + else: + # all 4 parameters included + filename, fileobj, content_type, headers = value # type: ignore + else: + filename = Path(str(getattr(value, "name", "upload"))).name + fileobj = value + + if content_type is None: + content_type = _guess_content_type(filename) + + has_content_type_header = any("content-type" in key.lower() for key in headers) + if content_type is not None and not has_content_type_header: + # note that unlike requests, we ignore the content_type provided in the 3rd + # tuple element if it is also included in the headers requests does + # the opposite (it overwrites the headerwith the 3rd tuple element) + headers["Content-Type"] = content_type + + if isinstance(fileobj, io.StringIO): + raise TypeError( + "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." + ) + if isinstance(fileobj, io.TextIOBase): + raise TypeError( + "Multipart file uploads must be opened in binary mode, not text mode." + ) + + self.filename = filename + self.file = fileobj + self.headers = headers + + def get_length(self) -> int | None: + headers = self.render_headers() + + if isinstance(self.file, (str, bytes)): + return len(headers) + len(to_bytes(self.file)) + + file_length = peek_filelike_length(self.file) + + # If we can't determine the filesize without reading it into memory, + # then return `None` here, to indicate an unknown file length. + if file_length is None: + return None + + return len(headers) + file_length + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + parts = [ + b"Content-Disposition: form-data; ", + _format_form_param("name", self.name), + ] + if self.filename: + filename = _format_form_param("filename", self.filename) + parts.extend([b"; ", filename]) + for header_name, header_value in self.headers.items(): + key, val = f"\r\n{header_name}: ".encode(), header_value.encode() + parts.extend([key, val]) + parts.append(b"\r\n\r\n") + self._headers = b"".join(parts) + + return self._headers + + def render_data(self) -> typing.Iterator[bytes]: + if isinstance(self.file, (str, bytes)): + yield to_bytes(self.file) + return + + if hasattr(self.file, "seek"): + try: + self.file.seek(0) + except io.UnsupportedOperation: + pass + + chunk = self.file.read(self.CHUNK_SIZE) + while chunk: + yield to_bytes(chunk) + chunk = self.file.read(self.CHUNK_SIZE) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield from self.render_data() + + +class MultipartStream(SyncByteStream, AsyncByteStream): + """ + Request content as streaming multipart encoded form data. + """ + + def __init__( + self, + data: RequestData, + files: RequestFiles, + boundary: bytes | None = None, + ) -> None: + if boundary is None: + boundary = os.urandom(16).hex().encode("ascii") + + self.boundary = boundary + self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( + "ascii" + ) + self.fields = list(self._iter_fields(data, files)) + + def _iter_fields( + self, data: RequestData, files: RequestFiles + ) -> typing.Iterator[FileField | DataField]: + for name, value in data.items(): + if isinstance(value, (tuple, list)): + for item in value: + yield DataField(name=name, value=item) + else: + yield DataField(name=name, value=value) + + file_items = files.items() if isinstance(files, typing.Mapping) else files + for name, value in file_items: + yield FileField(name=name, value=value) + + def iter_chunks(self) -> typing.Iterator[bytes]: + for field in self.fields: + yield b"--%s\r\n" % self.boundary + yield from field.render() + yield b"\r\n" + yield b"--%s--\r\n" % self.boundary + + def get_content_length(self) -> int | None: + """ + Return the length of the multipart encoded content, or `None` if + any of the files have a length that cannot be determined upfront. + """ + boundary_length = len(self.boundary) + length = 0 + + for field in self.fields: + field_length = field.get_length() + if field_length is None: + return None + + length += 2 + boundary_length + 2 # b"--{boundary}\r\n" + length += field_length + length += 2 # b"\r\n" + + length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" + return length + + # Content stream interface. + + def get_headers(self) -> dict[str, str]: + content_length = self.get_content_length() + content_type = self.content_type + if content_length is None: + return {"Transfer-Encoding": "chunked", "Content-Type": content_type} + return {"Content-Length": str(content_length), "Content-Type": content_type} + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_status_codes.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..133a6231a5b53fd2f073799ca1bd07c50abe40ae --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_status_codes.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from enum import IntEnum + +__all__ = ["codes"] + + +class codes(IntEnum): + """HTTP status codes and reason phrases + + Status codes from the following RFCs are all observed: + + * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 + * RFC 6585: Additional HTTP Status Codes + * RFC 3229: Delta encoding in HTTP + * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 + * RFC 5842: Binding Extensions to WebDAV + * RFC 7238: Permanent Redirect + * RFC 2295: Transparent Content Negotiation in HTTP + * RFC 2774: An HTTP Extension Framework + * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) + * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) + * RFC 7725: An HTTP Status Code to Report Legal Obstacles + * RFC 8297: An HTTP Status Code for Indicating Hints + * RFC 8470: Using Early Data in HTTP + """ + + def __new__(cls, value: int, phrase: str = "") -> codes: + obj = int.__new__(cls, value) + obj._value_ = value + + obj.phrase = phrase # type: ignore[attr-defined] + return obj + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def get_reason_phrase(cls, value: int) -> str: + try: + return codes(value).phrase # type: ignore + except ValueError: + return "" + + @classmethod + def is_informational(cls, value: int) -> bool: + """ + Returns `True` for 1xx status codes, `False` otherwise. + """ + return 100 <= value <= 199 + + @classmethod + def is_success(cls, value: int) -> bool: + """ + Returns `True` for 2xx status codes, `False` otherwise. + """ + return 200 <= value <= 299 + + @classmethod + def is_redirect(cls, value: int) -> bool: + """ + Returns `True` for 3xx status codes, `False` otherwise. + """ + return 300 <= value <= 399 + + @classmethod + def is_client_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx status codes, `False` otherwise. + """ + return 400 <= value <= 499 + + @classmethod + def is_server_error(cls, value: int) -> bool: + """ + Returns `True` for 5xx status codes, `False` otherwise. + """ + return 500 <= value <= 599 + + @classmethod + def is_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx or 5xx status codes, `False` otherwise. + """ + return 400 <= value <= 599 + + # informational + CONTINUE = 100, "Continue" + SWITCHING_PROTOCOLS = 101, "Switching Protocols" + PROCESSING = 102, "Processing" + EARLY_HINTS = 103, "Early Hints" + + # success + OK = 200, "OK" + CREATED = 201, "Created" + ACCEPTED = 202, "Accepted" + NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" + NO_CONTENT = 204, "No Content" + RESET_CONTENT = 205, "Reset Content" + PARTIAL_CONTENT = 206, "Partial Content" + MULTI_STATUS = 207, "Multi-Status" + ALREADY_REPORTED = 208, "Already Reported" + IM_USED = 226, "IM Used" + + # redirection + MULTIPLE_CHOICES = 300, "Multiple Choices" + MOVED_PERMANENTLY = 301, "Moved Permanently" + FOUND = 302, "Found" + SEE_OTHER = 303, "See Other" + NOT_MODIFIED = 304, "Not Modified" + USE_PROXY = 305, "Use Proxy" + TEMPORARY_REDIRECT = 307, "Temporary Redirect" + PERMANENT_REDIRECT = 308, "Permanent Redirect" + + # client error + BAD_REQUEST = 400, "Bad Request" + UNAUTHORIZED = 401, "Unauthorized" + PAYMENT_REQUIRED = 402, "Payment Required" + FORBIDDEN = 403, "Forbidden" + NOT_FOUND = 404, "Not Found" + METHOD_NOT_ALLOWED = 405, "Method Not Allowed" + NOT_ACCEPTABLE = 406, "Not Acceptable" + PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" + REQUEST_TIMEOUT = 408, "Request Timeout" + CONFLICT = 409, "Conflict" + GONE = 410, "Gone" + LENGTH_REQUIRED = 411, "Length Required" + PRECONDITION_FAILED = 412, "Precondition Failed" + REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" + REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" + UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" + REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" + EXPECTATION_FAILED = 417, "Expectation Failed" + IM_A_TEAPOT = 418, "I'm a teapot" + MISDIRECTED_REQUEST = 421, "Misdirected Request" + UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" + LOCKED = 423, "Locked" + FAILED_DEPENDENCY = 424, "Failed Dependency" + TOO_EARLY = 425, "Too Early" + UPGRADE_REQUIRED = 426, "Upgrade Required" + PRECONDITION_REQUIRED = 428, "Precondition Required" + TOO_MANY_REQUESTS = 429, "Too Many Requests" + REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" + UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" + + # server errors + INTERNAL_SERVER_ERROR = 500, "Internal Server Error" + NOT_IMPLEMENTED = 501, "Not Implemented" + BAD_GATEWAY = 502, "Bad Gateway" + SERVICE_UNAVAILABLE = 503, "Service Unavailable" + GATEWAY_TIMEOUT = 504, "Gateway Timeout" + HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" + VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" + INSUFFICIENT_STORAGE = 507, "Insufficient Storage" + LOOP_DETECTED = 508, "Loop Detected" + NOT_EXTENDED = 510, "Not Extended" + NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" + + +# Include lower-case styles for `requests` compatibility. +for code in codes: + setattr(codes, code._name_.lower(), int(code)) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/__init__.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a321053b29bcd48698cf2bd74a1d19c8556aefb --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/__init__.py @@ -0,0 +1,15 @@ +from .asgi import * +from .base import * +from .default import * +from .mock import * +from .wsgi import * + +__all__ = [ + "ASGITransport", + "AsyncBaseTransport", + "BaseTransport", + "AsyncHTTPTransport", + "HTTPTransport", + "MockTransport", + "WSGITransport", +] diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/asgi.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/asgi.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc4efae0e1b14620f75f712eb15ecf500d14eef --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/asgi.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +import typing + +from .._models import Request, Response +from .._types import AsyncByteStream +from .base import AsyncBaseTransport + +if typing.TYPE_CHECKING: # pragma: no cover + import asyncio + + import trio + + Event = typing.Union[asyncio.Event, trio.Event] + + +_Message = typing.MutableMapping[str, typing.Any] +_Receive = typing.Callable[[], typing.Awaitable[_Message]] +_Send = typing.Callable[ + [typing.MutableMapping[str, typing.Any]], typing.Awaitable[None] +] +_ASGIApp = typing.Callable[ + [typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None] +] + +__all__ = ["ASGITransport"] + + +def is_running_trio() -> bool: + try: + # sniffio is a dependency of trio. + + # See https://github.com/python-trio/trio/issues/2802 + import sniffio + + if sniffio.current_async_library() == "trio": + return True + except ImportError: # pragma: nocover + pass + + return False + + +def create_event() -> Event: + if is_running_trio(): + import trio + + return trio.Event() + + import asyncio + + return asyncio.Event() + + +class ASGIResponseStream(AsyncByteStream): + def __init__(self, body: list[bytes]) -> None: + self._body = body + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield b"".join(self._body) + + +class ASGITransport(AsyncBaseTransport): + """ + A custom AsyncTransport that handles sending requests directly to an ASGI app. + + ```python + transport = httpx.ASGITransport( + app=app, + root_path="/submount", + client=("1.2.3.4", 123) + ) + client = httpx.AsyncClient(transport=transport) + ``` + + Arguments: + + * `app` - The ASGI application. + * `raise_app_exceptions` - Boolean indicating if exceptions in the application + should be raised. Default to `True`. Can be set to `False` for use cases + such as testing the content of a client 500 response. + * `root_path` - The root path on which the ASGI application should be mounted. + * `client` - A two-tuple indicating the client IP and port of incoming requests. + ``` + """ + + def __init__( + self, + app: _ASGIApp, + raise_app_exceptions: bool = True, + root_path: str = "", + client: tuple[str, int] = ("127.0.0.1", 123), + ) -> None: + self.app = app + self.raise_app_exceptions = raise_app_exceptions + self.root_path = root_path + self.client = client + + async def handle_async_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, AsyncByteStream) + + # ASGI scope. + scope = { + "type": "http", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "method": request.method, + "headers": [(k.lower(), v) for (k, v) in request.headers.raw], + "scheme": request.url.scheme, + "path": request.url.path, + "raw_path": request.url.raw_path.split(b"?")[0], + "query_string": request.url.query, + "server": (request.url.host, request.url.port), + "client": self.client, + "root_path": self.root_path, + } + + # Request. + request_body_chunks = request.stream.__aiter__() + request_complete = False + + # Response. + status_code = None + response_headers = None + body_parts = [] + response_started = False + response_complete = create_event() + + # ASGI callables. + + async def receive() -> dict[str, typing.Any]: + nonlocal request_complete + + if request_complete: + await response_complete.wait() + return {"type": "http.disconnect"} + + try: + body = await request_body_chunks.__anext__() + except StopAsyncIteration: + request_complete = True + return {"type": "http.request", "body": b"", "more_body": False} + return {"type": "http.request", "body": body, "more_body": True} + + async def send(message: typing.MutableMapping[str, typing.Any]) -> None: + nonlocal status_code, response_headers, response_started + + if message["type"] == "http.response.start": + assert not response_started + + status_code = message["status"] + response_headers = message.get("headers", []) + response_started = True + + elif message["type"] == "http.response.body": + assert not response_complete.is_set() + body = message.get("body", b"") + more_body = message.get("more_body", False) + + if body and request.method != "HEAD": + body_parts.append(body) + + if not more_body: + response_complete.set() + + try: + await self.app(scope, receive, send) + except Exception: # noqa: PIE-786 + if self.raise_app_exceptions: + raise + + response_complete.set() + if status_code is None: + status_code = 500 + if response_headers is None: + response_headers = {} + + assert response_complete.is_set() + assert status_code is not None + assert response_headers is not None + + stream = ASGIResponseStream(body_parts) + + return Response(status_code, headers=response_headers, stream=stream) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/base.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..66fd99d702480b555c06694fe14715ea6df3dfc3 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/base.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import typing +from types import TracebackType + +from .._models import Request, Response + +T = typing.TypeVar("T", bound="BaseTransport") +A = typing.TypeVar("A", bound="AsyncBaseTransport") + +__all__ = ["AsyncBaseTransport", "BaseTransport"] + + +class BaseTransport: + def __enter__(self: T) -> T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self.close() + + def handle_request(self, request: Request) -> Response: + """ + Send a single HTTP request and return a response. + + Developers shouldn't typically ever need to call into this API directly, + since the Client class provides all the higher level user-facing API + niceties. + + In order to properly release any network resources, the response + stream should *either* be consumed immediately, with a call to + `response.stream.read()`, or else the `handle_request` call should + be followed with a try/finally block to ensuring the stream is + always closed. + + Example usage: + + with httpx.HTTPTransport() as transport: + req = httpx.Request( + method=b"GET", + url=(b"https", b"www.example.com", 443, b"/"), + headers=[(b"Host", b"www.example.com")], + ) + resp = transport.handle_request(req) + body = resp.stream.read() + print(resp.status_code, resp.headers, body) + + + Takes a `Request` instance as the only argument. + + Returns a `Response` instance. + """ + raise NotImplementedError( + "The 'handle_request' method must be implemented." + ) # pragma: no cover + + def close(self) -> None: + pass + + +class AsyncBaseTransport: + async def __aenter__(self: A) -> A: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + await self.aclose() + + async def handle_async_request( + self, + request: Request, + ) -> Response: + raise NotImplementedError( + "The 'handle_async_request' method must be implemented." + ) # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/default.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/default.py new file mode 100644 index 0000000000000000000000000000000000000000..d5aa05ff234fd3fbf4fee88c4a7d3e3c151a538f --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/default.py @@ -0,0 +1,406 @@ +""" +Custom transports, with nicely configured defaults. + +The following additional keyword arguments are currently supported by httpcore... + +* uds: str +* local_address: str +* retries: int + +Example usages... + +# Disable HTTP/2 on a single specific domain. +mounts = { + "all://": httpx.HTTPTransport(http2=True), + "all://*example.org": httpx.HTTPTransport() +} + +# Using advanced httpcore configuration, with connection retries. +transport = httpx.HTTPTransport(retries=1) +client = httpx.Client(transport=transport) + +# Using advanced httpcore configuration, with unix domain sockets. +transport = httpx.HTTPTransport(uds="socket.uds") +client = httpx.Client(transport=transport) +""" + +from __future__ import annotations + +import contextlib +import typing +from types import TracebackType + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + import httpx # pragma: no cover + +from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context +from .._exceptions import ( + ConnectError, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from .._models import Request, Response +from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream +from .._urls import URL +from .base import AsyncBaseTransport, BaseTransport + +T = typing.TypeVar("T", bound="HTTPTransport") +A = typing.TypeVar("A", bound="AsyncHTTPTransport") + +SOCKET_OPTION = typing.Union[ + typing.Tuple[int, int, int], + typing.Tuple[int, int, typing.Union[bytes, bytearray]], + typing.Tuple[int, int, None, int], +] + +__all__ = ["AsyncHTTPTransport", "HTTPTransport"] + +HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {} + + +def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]: + import httpcore + + return { + httpcore.TimeoutException: TimeoutException, + httpcore.ConnectTimeout: ConnectTimeout, + httpcore.ReadTimeout: ReadTimeout, + httpcore.WriteTimeout: WriteTimeout, + httpcore.PoolTimeout: PoolTimeout, + httpcore.NetworkError: NetworkError, + httpcore.ConnectError: ConnectError, + httpcore.ReadError: ReadError, + httpcore.WriteError: WriteError, + httpcore.ProxyError: ProxyError, + httpcore.UnsupportedProtocol: UnsupportedProtocol, + httpcore.ProtocolError: ProtocolError, + httpcore.LocalProtocolError: LocalProtocolError, + httpcore.RemoteProtocolError: RemoteProtocolError, + } + + +@contextlib.contextmanager +def map_httpcore_exceptions() -> typing.Iterator[None]: + global HTTPCORE_EXC_MAP + if len(HTTPCORE_EXC_MAP) == 0: + HTTPCORE_EXC_MAP = _load_httpcore_exceptions() + try: + yield + except Exception as exc: + mapped_exc = None + + for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): + if not isinstance(exc, from_exc): + continue + # We want to map to the most specific exception we can find. + # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to + # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. + if mapped_exc is None or issubclass(to_exc, mapped_exc): + mapped_exc = to_exc + + if mapped_exc is None: # pragma: no cover + raise + + message = str(exc) + raise mapped_exc(message) from exc + + +class ResponseStream(SyncByteStream): + def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None: + self._httpcore_stream = httpcore_stream + + def __iter__(self) -> typing.Iterator[bytes]: + with map_httpcore_exceptions(): + for part in self._httpcore_stream: + yield part + + def close(self) -> None: + if hasattr(self._httpcore_stream, "close"): + self._httpcore_stream.close() + + +class HTTPTransport(BaseTransport): + def __init__( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + proxy: ProxyTypes | None = None, + uds: str | None = None, + local_address: str | None = None, + retries: int = 0, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + import httpcore + + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) + + if proxy is None: + self._pool = httpcore.ConnectionPool( + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + uds=uds, + local_address=local_address, + retries=retries, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("http", "https"): + self._pool = httpcore.HTTPProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + proxy_headers=proxy.headers.raw, + ssl_context=ssl_context, + proxy_ssl_context=proxy.ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("socks5", "socks5h"): + try: + import socksio # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using SOCKS proxy, but the 'socksio' package is not installed. " + "Make sure to install httpx using `pip install httpx[socks]`." + ) from None + + self._pool = httpcore.SOCKSProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + ) + else: # pragma: no cover + raise ValueError( + "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," + f" but got {proxy.url.scheme!r}." + ) + + def __enter__(self: T) -> T: # Use generics for subclass support. + self._pool.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + with map_httpcore_exceptions(): + self._pool.__exit__(exc_type, exc_value, traceback) + + def handle_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, SyncByteStream) + import httpcore + + req = httpcore.Request( + method=request.method, + url=httpcore.URL( + scheme=request.url.raw_scheme, + host=request.url.raw_host, + port=request.url.port, + target=request.url.raw_path, + ), + headers=request.headers.raw, + content=request.stream, + extensions=request.extensions, + ) + with map_httpcore_exceptions(): + resp = self._pool.handle_request(req) + + assert isinstance(resp.stream, typing.Iterable) + + return Response( + status_code=resp.status, + headers=resp.headers, + stream=ResponseStream(resp.stream), + extensions=resp.extensions, + ) + + def close(self) -> None: + self._pool.close() + + +class AsyncResponseStream(AsyncByteStream): + def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None: + self._httpcore_stream = httpcore_stream + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + with map_httpcore_exceptions(): + async for part in self._httpcore_stream: + yield part + + async def aclose(self) -> None: + if hasattr(self._httpcore_stream, "aclose"): + await self._httpcore_stream.aclose() + + +class AsyncHTTPTransport(AsyncBaseTransport): + def __init__( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + proxy: ProxyTypes | None = None, + uds: str | None = None, + local_address: str | None = None, + retries: int = 0, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + import httpcore + + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) + + if proxy is None: + self._pool = httpcore.AsyncConnectionPool( + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + uds=uds, + local_address=local_address, + retries=retries, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("http", "https"): + self._pool = httpcore.AsyncHTTPProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + proxy_headers=proxy.headers.raw, + proxy_ssl_context=proxy.ssl_context, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("socks5", "socks5h"): + try: + import socksio # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using SOCKS proxy, but the 'socksio' package is not installed. " + "Make sure to install httpx using `pip install httpx[socks]`." + ) from None + + self._pool = httpcore.AsyncSOCKSProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + ) + else: # pragma: no cover + raise ValueError( + "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," + " but got {proxy.url.scheme!r}." + ) + + async def __aenter__(self: A) -> A: # Use generics for subclass support. + await self._pool.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + with map_httpcore_exceptions(): + await self._pool.__aexit__(exc_type, exc_value, traceback) + + async def handle_async_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, AsyncByteStream) + import httpcore + + req = httpcore.Request( + method=request.method, + url=httpcore.URL( + scheme=request.url.raw_scheme, + host=request.url.raw_host, + port=request.url.port, + target=request.url.raw_path, + ), + headers=request.headers.raw, + content=request.stream, + extensions=request.extensions, + ) + with map_httpcore_exceptions(): + resp = await self._pool.handle_async_request(req) + + assert isinstance(resp.stream, typing.AsyncIterable) + + return Response( + status_code=resp.status, + headers=resp.headers, + stream=AsyncResponseStream(resp.stream), + extensions=resp.extensions, + ) + + async def aclose(self) -> None: + await self._pool.aclose() diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/mock.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..8c418f59e06cae43abdbb626ec21cafc7e8c6277 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/mock.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .._models import Request, Response +from .base import AsyncBaseTransport, BaseTransport + +SyncHandler = typing.Callable[[Request], Response] +AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]] + + +__all__ = ["MockTransport"] + + +class MockTransport(AsyncBaseTransport, BaseTransport): + def __init__(self, handler: SyncHandler | AsyncHandler) -> None: + self.handler = handler + + def handle_request( + self, + request: Request, + ) -> Response: + request.read() + response = self.handler(request) + if not isinstance(response, Response): # pragma: no cover + raise TypeError("Cannot use an async handler in a sync Client") + return response + + async def handle_async_request( + self, + request: Request, + ) -> Response: + await request.aread() + response = self.handler(request) + + # Allow handler to *optionally* be an `async` function. + # If it is, then the `response` variable need to be awaited to actually + # return the result. + + if not isinstance(response, Response): + response = await response + + return response diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/wsgi.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..8592ffe017a87367cc7578184540096a9682908d --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_transports/wsgi.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import io +import itertools +import sys +import typing + +from .._models import Request, Response +from .._types import SyncByteStream +from .base import BaseTransport + +if typing.TYPE_CHECKING: + from _typeshed import OptExcInfo # pragma: no cover + from _typeshed.wsgi import WSGIApplication # pragma: no cover + +_T = typing.TypeVar("_T") + + +__all__ = ["WSGITransport"] + + +def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]: + body = iter(body) + for chunk in body: + if chunk: + return itertools.chain([chunk], body) + return [] + + +class WSGIByteStream(SyncByteStream): + def __init__(self, result: typing.Iterable[bytes]) -> None: + self._close = getattr(result, "close", None) + self._result = _skip_leading_empty_chunks(result) + + def __iter__(self) -> typing.Iterator[bytes]: + for part in self._result: + yield part + + def close(self) -> None: + if self._close is not None: + self._close() + + +class WSGITransport(BaseTransport): + """ + A custom transport that handles sending requests directly to an WSGI app. + The simplest way to use this functionality is to use the `app` argument. + + ``` + client = httpx.Client(app=app) + ``` + + Alternatively, you can setup the transport instance explicitly. + This allows you to include any additional configuration arguments specific + to the WSGITransport class: + + ``` + transport = httpx.WSGITransport( + app=app, + script_name="/submount", + remote_addr="1.2.3.4" + ) + client = httpx.Client(transport=transport) + ``` + + Arguments: + + * `app` - The WSGI application. + * `raise_app_exceptions` - Boolean indicating if exceptions in the application + should be raised. Default to `True`. Can be set to `False` for use cases + such as testing the content of a client 500 response. + * `script_name` - The root path on which the WSGI application should be mounted. + * `remote_addr` - A string indicating the client IP of incoming requests. + ``` + """ + + def __init__( + self, + app: WSGIApplication, + raise_app_exceptions: bool = True, + script_name: str = "", + remote_addr: str = "127.0.0.1", + wsgi_errors: typing.TextIO | None = None, + ) -> None: + self.app = app + self.raise_app_exceptions = raise_app_exceptions + self.script_name = script_name + self.remote_addr = remote_addr + self.wsgi_errors = wsgi_errors + + def handle_request(self, request: Request) -> Response: + request.read() + wsgi_input = io.BytesIO(request.content) + + port = request.url.port or {"http": 80, "https": 443}[request.url.scheme] + environ = { + "wsgi.version": (1, 0), + "wsgi.url_scheme": request.url.scheme, + "wsgi.input": wsgi_input, + "wsgi.errors": self.wsgi_errors or sys.stderr, + "wsgi.multithread": True, + "wsgi.multiprocess": False, + "wsgi.run_once": False, + "REQUEST_METHOD": request.method, + "SCRIPT_NAME": self.script_name, + "PATH_INFO": request.url.path, + "QUERY_STRING": request.url.query.decode("ascii"), + "SERVER_NAME": request.url.host, + "SERVER_PORT": str(port), + "SERVER_PROTOCOL": "HTTP/1.1", + "REMOTE_ADDR": self.remote_addr, + } + for header_key, header_value in request.headers.raw: + key = header_key.decode("ascii").upper().replace("-", "_") + if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"): + key = "HTTP_" + key + environ[key] = header_value.decode("ascii") + + seen_status = None + seen_response_headers = None + seen_exc_info = None + + def start_response( + status: str, + response_headers: list[tuple[str, str]], + exc_info: OptExcInfo | None = None, + ) -> typing.Callable[[bytes], typing.Any]: + nonlocal seen_status, seen_response_headers, seen_exc_info + seen_status = status + seen_response_headers = response_headers + seen_exc_info = exc_info + return lambda _: None + + result = self.app(environ, start_response) + + stream = WSGIByteStream(result) + + assert seen_status is not None + assert seen_response_headers is not None + if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions: + raise seen_exc_info[1] + + status_code = int(seen_status.split()[0]) + headers = [ + (key.encode("ascii"), value.encode("ascii")) + for key, value in seen_response_headers + ] + + return Response(status_code, headers=headers, stream=stream) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_types.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..704dfdffc8ba61eb913fa918072381e410b23c00 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_types.py @@ -0,0 +1,114 @@ +""" +Type definitions for type checking purposes. +""" + +from http.cookiejar import CookieJar +from typing import ( + IO, + TYPE_CHECKING, + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +if TYPE_CHECKING: # pragma: no cover + from ._auth import Auth # noqa: F401 + from ._config import Proxy, Timeout # noqa: F401 + from ._models import Cookies, Headers, Request # noqa: F401 + from ._urls import URL, QueryParams # noqa: F401 + + +PrimitiveData = Optional[Union[str, int, float, bool]] + +URLTypes = Union["URL", str] + +QueryParamTypes = Union[ + "QueryParams", + Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], + List[Tuple[str, PrimitiveData]], + Tuple[Tuple[str, PrimitiveData], ...], + str, + bytes, +] + +HeaderTypes = Union[ + "Headers", + Mapping[str, str], + Mapping[bytes, bytes], + Sequence[Tuple[str, str]], + Sequence[Tuple[bytes, bytes]], +] + +CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] + +TimeoutTypes = Union[ + Optional[float], + Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], + "Timeout", +] +ProxyTypes = Union["URL", str, "Proxy"] +CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]] + +AuthTypes = Union[ + Tuple[Union[str, bytes], Union[str, bytes]], + Callable[["Request"], "Request"], + "Auth", +] + +RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseExtensions = Mapping[str, Any] + +RequestData = Mapping[str, Any] + +FileContent = Union[IO[bytes], bytes, str] +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +RequestExtensions = Mapping[str, Any] + +__all__ = ["AsyncByteStream", "SyncByteStream"] + + +class SyncByteStream: + def __iter__(self) -> Iterator[bytes]: + raise NotImplementedError( + "The '__iter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + def close(self) -> None: + """ + Subclasses can override this method to release any network resources + after a request/response cycle is complete. + """ + + +class AsyncByteStream: + async def __aiter__(self) -> AsyncIterator[bytes]: + raise NotImplementedError( + "The '__aiter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urlparse.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urlparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bf190fd560ee4fc8a11af371a15fc5f1dc284d34 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urlparse.py @@ -0,0 +1,527 @@ +""" +An implementation of `urlparse` that provides URL validation and normalization +as described by RFC3986. + +We rely on this implementation rather than the one in Python's stdlib, because: + +* It provides more complete URL validation. +* It properly differentiates between an empty querystring and an absent querystring, + to distinguish URLs with a trailing '?'. +* It handles scheme, hostname, port, and path normalization. +* It supports IDNA hostnames, normalizing them to their encoded form. +* The API supports passing individual components, as well as the complete URL string. + +Previously we relied on the excellent `rfc3986` package to handle URL parsing and +validation, but this module provides a simpler alternative, with less indirection +required. +""" + +from __future__ import annotations + +import ipaddress +import re +import typing + +import idna + +from ._exceptions import InvalidURL + +MAX_URL_LENGTH = 65536 + +# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 +UNRESERVED_CHARACTERS = ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" +) +SUB_DELIMS = "!$&'()*+,;=" + +PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}") + +# https://url.spec.whatwg.org/#percent-encoded-bytes + +# The fragment percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`). +FRAG_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)] +) + +# The query percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>). +QUERY_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)] +) + +# The path percent-encode set is the query percent-encode set +# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}). +PATH_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + ] +) + +# The userinfo percent-encode set is the path percent-encode set +# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), +# U+005B ([) to U+005E (^), inclusive, and U+007C (|). +USERNAME_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +PASSWORD_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +# Note... The terminology 'userinfo' percent-encode set in the WHATWG document +# is used for the username and password quoting. For the joint userinfo component +# we remove U+003A (:) from the safe set. +USERINFO_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) + + +# {scheme}: (optional) +# //{authority} (optional) +# {path} +# ?{query} (optional) +# #{fragment} (optional) +URL_REGEX = re.compile( + ( + r"(?:(?P{scheme}):)?" + r"(?://(?P{authority}))?" + r"(?P{path})" + r"(?:\?(?P{query}))?" + r"(?:#(?P{fragment}))?" + ).format( + scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", + authority="[^/?#]*", + path="[^?#]*", + query="[^#]*", + fragment=".*", + ) +) + +# {userinfo}@ (optional) +# {host} +# :{port} (optional) +AUTHORITY_REGEX = re.compile( + ( + r"(?:(?P{userinfo})@)?" r"(?P{host})" r":?(?P{port})?" + ).format( + userinfo=".*", # Any character sequence. + host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', + # or an IPv6 address enclosed within square brackets. + port=".*", # Any character sequence. + ) +) + + +# If we call urlparse with an individual component, then we need to regex +# validate that component individually. +# Note that we're duplicating the same strings as above. Shock! Horror!! +COMPONENT_REGEX = { + "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), + "authority": re.compile("[^/?#]*"), + "path": re.compile("[^?#]*"), + "query": re.compile("[^#]*"), + "fragment": re.compile(".*"), + "userinfo": re.compile("[^@]*"), + "host": re.compile("(\\[.*\\]|[^:]*)"), + "port": re.compile(".*"), +} + + +# We use these simple regexs as a first pass before handing off to +# the stdlib 'ipaddress' module for IP address validation. +IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") +IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$") + + +class ParseResult(typing.NamedTuple): + scheme: str + userinfo: str + host: str + port: int | None + path: str + query: str | None + fragment: str | None + + @property + def authority(self) -> str: + return "".join( + [ + f"{self.userinfo}@" if self.userinfo else "", + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + @property + def netloc(self) -> str: + return "".join( + [ + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + def copy_with(self, **kwargs: str | None) -> ParseResult: + if not kwargs: + return self + + defaults = { + "scheme": self.scheme, + "authority": self.authority, + "path": self.path, + "query": self.query, + "fragment": self.fragment, + } + defaults.update(kwargs) + return urlparse("", **defaults) + + def __str__(self) -> str: + authority = self.authority + return "".join( + [ + f"{self.scheme}:" if self.scheme else "", + f"//{authority}" if authority else "", + self.path, + f"?{self.query}" if self.query is not None else "", + f"#{self.fragment}" if self.fragment is not None else "", + ] + ) + + +def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: + # Initial basic checks on allowable URLs. + # --------------------------------------- + + # Hard limit the maximum allowable URL length. + if len(url) > MAX_URL_LENGTH: + raise InvalidURL("URL too long") + + # If a URL includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in url): + char = next(char for char in url if char.isascii() and not char.isprintable()) + idx = url.find(char) + error = ( + f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Some keyword arguments require special handling. + # ------------------------------------------------ + + # Coerce "port" to a string, if it is provided as an integer. + if "port" in kwargs: + port = kwargs["port"] + kwargs["port"] = str(port) if isinstance(port, int) else port + + # Replace "netloc" with "host and "port". + if "netloc" in kwargs: + netloc = kwargs.pop("netloc") or "" + kwargs["host"], _, kwargs["port"] = netloc.partition(":") + + # Replace "username" and/or "password" with "userinfo". + if "username" in kwargs or "password" in kwargs: + username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) + password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) + kwargs["userinfo"] = f"{username}:{password}" if password else username + + # Replace "raw_path" with "path" and "query". + if "raw_path" in kwargs: + raw_path = kwargs.pop("raw_path") or "" + kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") + if not seperator: + kwargs["query"] = None + + # Ensure that IPv6 "host" addresses are always escaped with "[...]". + if "host" in kwargs: + host = kwargs.get("host") or "" + if ":" in host and not (host.startswith("[") and host.endswith("]")): + kwargs["host"] = f"[{host}]" + + # If any keyword arguments are provided, ensure they are valid. + # ------------------------------------------------------------- + + for key, value in kwargs.items(): + if value is not None: + if len(value) > MAX_URL_LENGTH: + raise InvalidURL(f"URL component '{key}' too long") + + # If a component includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in value): + char = next( + char for char in value if char.isascii() and not char.isprintable() + ) + idx = value.find(char) + error = ( + f"Invalid non-printable ASCII character in URL {key} component, " + f"{char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Ensure that keyword arguments match as a valid regex. + if not COMPONENT_REGEX[key].fullmatch(value): + raise InvalidURL(f"Invalid URL component '{key}'") + + # The URL_REGEX will always match, but may have empty components. + url_match = URL_REGEX.match(url) + assert url_match is not None + url_dict = url_match.groupdict() + + # * 'scheme', 'authority', and 'path' may be empty strings. + # * 'query' may be 'None', indicating no trailing "?" portion. + # Any string including the empty string, indicates a trailing "?". + # * 'fragment' may be 'None', indicating no trailing "#" portion. + # Any string including the empty string, indicates a trailing "#". + scheme = kwargs.get("scheme", url_dict["scheme"]) or "" + authority = kwargs.get("authority", url_dict["authority"]) or "" + path = kwargs.get("path", url_dict["path"]) or "" + query = kwargs.get("query", url_dict["query"]) + frag = kwargs.get("fragment", url_dict["fragment"]) + + # The AUTHORITY_REGEX will always match, but may have empty components. + authority_match = AUTHORITY_REGEX.match(authority) + assert authority_match is not None + authority_dict = authority_match.groupdict() + + # * 'userinfo' and 'host' may be empty strings. + # * 'port' may be 'None'. + userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" + host = kwargs.get("host", authority_dict["host"]) or "" + port = kwargs.get("port", authority_dict["port"]) + + # Normalize and validate each component. + # We end up with a parsed representation of the URL, + # with components that are plain ASCII bytestrings. + parsed_scheme: str = scheme.lower() + parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) + parsed_host: str = encode_host(host) + parsed_port: int | None = normalize_port(port, scheme) + + has_scheme = parsed_scheme != "" + has_authority = ( + parsed_userinfo != "" or parsed_host != "" or parsed_port is not None + ) + validate_path(path, has_scheme=has_scheme, has_authority=has_authority) + if has_scheme or has_authority: + path = normalize_path(path) + + parsed_path: str = quote(path, safe=PATH_SAFE) + parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) + parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE) + + # The parsed ASCII bytestrings are our canonical form. + # All properties of the URL are derived from these. + return ParseResult( + parsed_scheme, + parsed_userinfo, + parsed_host, + parsed_port, + parsed_path, + parsed_query, + parsed_frag, + ) + + +def encode_host(host: str) -> str: + if not host: + return "" + + elif IPv4_STYLE_HOSTNAME.match(host): + # Validate IPv4 hostnames like #.#.#.# + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + try: + ipaddress.IPv4Address(host) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv4 address: {host!r}") + return host + + elif IPv6_STYLE_HOSTNAME.match(host): + # Validate IPv6 hostnames like [...] + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # "A host identified by an Internet Protocol literal address, version 6 + # [RFC3513] or later, is distinguished by enclosing the IP literal + # within square brackets ("[" and "]"). This is the only place where + # square bracket characters are allowed in the URI syntax." + try: + ipaddress.IPv6Address(host[1:-1]) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv6 address: {host!r}") + return host[1:-1] + + elif host.isascii(): + # Regular ASCII hostnames + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # reg-name = *( unreserved / pct-encoded / sub-delims ) + WHATWG_SAFE = '"`{}%|\\' + return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE) + + # IDNA hostnames + try: + return idna.encode(host.lower()).decode("ascii") + except idna.IDNAError: + raise InvalidURL(f"Invalid IDNA hostname: {host!r}") + + +def normalize_port(port: str | int | None, scheme: str) -> int | None: + # From https://tools.ietf.org/html/rfc3986#section-3.2.3 + # + # "A scheme may define a default port. For example, the "http" scheme + # defines a default port of "80", corresponding to its reserved TCP + # port number. The type of port designated by the port number (e.g., + # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and + # normalizers should omit the port component and its ":" delimiter if + # port is empty or if its value would be the same as that of the + # scheme's default." + if port is None or port == "": + return None + + try: + port_as_int = int(port) + except ValueError: + raise InvalidURL(f"Invalid port: {port!r}") + + # See https://url.spec.whatwg.org/#url-miscellaneous + default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( + scheme + ) + if port_as_int == default_port: + return None + return port_as_int + + +def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: + """ + Path validation rules that depend on if the URL contains + a scheme or authority component. + + See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 + """ + if has_authority: + # If a URI contains an authority component, then the path component + # must either be empty or begin with a slash ("/") character." + if path and not path.startswith("/"): + raise InvalidURL("For absolute URLs, path must be empty or begin with '/'") + + if not has_scheme and not has_authority: + # If a URI does not contain an authority component, then the path cannot begin + # with two slash characters ("//"). + if path.startswith("//"): + raise InvalidURL("Relative URLs cannot have a path starting with '//'") + + # In addition, a URI reference (Section 4.1) may be a relative-path reference, + # in which case the first path segment cannot contain a colon (":") character. + if path.startswith(":"): + raise InvalidURL("Relative URLs cannot have a path starting with ':'") + + +def normalize_path(path: str) -> str: + """ + Drop "." and ".." segments from a URL path. + + For example: + + normalize_path("/path/./to/somewhere/..") == "/path/to" + """ + # Fast return when no '.' characters in the path. + if "." not in path: + return path + + components = path.split("/") + + # Fast return when no '.' or '..' components in the path. + if "." not in components and ".." not in components: + return path + + # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + output: list[str] = [] + for component in components: + if component == ".": + pass + elif component == "..": + if output and output != [""]: + output.pop() + else: + output.append(component) + return "/".join(output) + + +def PERCENT(string: str) -> str: + return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")]) + + +def percent_encoded(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string. + """ + NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe + + # Fast path for strings that don't need escaping. + if not string.rstrip(NON_ESCAPED_CHARS): + return string + + return "".join( + [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] + ) + + +def quote(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. + + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 + + * `string`: The string to be percent-escaped. + * `safe`: A string containing characters that may be treated as safe, and do not + need to be escaped. Unreserved characters are always treated as safe. + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 + """ + parts = [] + current_position = 0 + for match in re.finditer(PERCENT_ENCODED_REGEX, string): + start_position, end_position = match.start(), match.end() + matched_text = match.group(0) + # Add any text up to the '%xx' escape sequence. + if start_position != current_position: + leading_text = string[current_position:start_position] + parts.append(percent_encoded(leading_text, safe=safe)) + + # Add the '%xx' escape sequence. + parts.append(matched_text) + current_position = end_position + + # Add any text after the final '%xx' escape sequence. + if current_position != len(string): + trailing_text = string[current_position:] + parts.append(percent_encoded(trailing_text, safe=safe)) + + return "".join(parts) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urls.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..147a8fa333acaf31618d37ba2896e3a5bf5e4d02 --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_urls.py @@ -0,0 +1,641 @@ +from __future__ import annotations + +import typing +from urllib.parse import parse_qs, unquote, urlencode + +import idna + +from ._types import QueryParamTypes +from ._urlparse import urlparse +from ._utils import primitive_value_to_str + +__all__ = ["URL", "QueryParams"] + + +class URL: + """ + url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") + + assert url.scheme == "https" + assert url.username == "jo@email.com" + assert url.password == "a secret" + assert url.userinfo == b"jo%40email.com:a%20secret" + assert url.host == "müller.de" + assert url.raw_host == b"xn--mller-kva.de" + assert url.port == 1234 + assert url.netloc == b"xn--mller-kva.de:1234" + assert url.path == "/pa th" + assert url.query == b"?search=ab" + assert url.raw_path == b"/pa%20th?search=ab" + assert url.fragment == "anchorlink" + + The components of a URL are broken down like this: + + https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink + [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] + [ userinfo ] [ netloc ][ raw_path ] + + Note that: + + * `url.scheme` is normalized to always be lowercased. + + * `url.host` is normalized to always be lowercased. Internationalized domain + names are represented in unicode, without IDNA encoding applied. For instance: + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded. + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + * `url.port` is either None or an integer. URLs that include the default port for + "http", "https", "ws", "wss", and "ftp" schemes have their port + normalized to `None`. + + assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") + assert httpx.URL("http://example.com").port is None + assert httpx.URL("http://example.com:80").port is None + + * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work + with `url.username` and `url.password` instead, which handle the URL escaping. + + * `url.raw_path` is raw bytes of both the path and query, without URL escaping. + This portion is used as the target when constructing HTTP requests. Usually you'll + want to work with `url.path` instead. + + * `url.query` is raw bytes, without URL escaping. A URL query string portion can + only be properly URL escaped when decoding the parameter names and values + themselves. + """ + + def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: + if kwargs: + allowed = { + "scheme": str, + "username": str, + "password": str, + "userinfo": bytes, + "host": str, + "port": int, + "netloc": bytes, + "path": str, + "query": bytes, + "raw_path": bytes, + "fragment": str, + "params": object, + } + + # Perform type checking for all supported keyword arguments. + for key, value in kwargs.items(): + if key not in allowed: + message = f"{key!r} is an invalid keyword argument for URL()" + raise TypeError(message) + if value is not None and not isinstance(value, allowed[key]): + expected = allowed[key].__name__ + seen = type(value).__name__ + message = f"Argument {key!r} must be {expected} but got {seen}" + raise TypeError(message) + if isinstance(value, bytes): + kwargs[key] = value.decode("ascii") + + if "params" in kwargs: + # Replace any "params" keyword with the raw "query" instead. + # + # Ensure that empty params use `kwargs["query"] = None` rather + # than `kwargs["query"] = ""`, so that generated URLs do not + # include an empty trailing "?". + params = kwargs.pop("params") + kwargs["query"] = None if not params else str(QueryParams(params)) + + if isinstance(url, str): + self._uri_reference = urlparse(url, **kwargs) + elif isinstance(url, URL): + self._uri_reference = url._uri_reference.copy_with(**kwargs) + else: + raise TypeError( + "Invalid type for url. Expected str or httpx.URL," + f" got {type(url)}: {url!r}" + ) + + @property + def scheme(self) -> str: + """ + The URL scheme, such as "http", "https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme + + @property + def raw_scheme(self) -> bytes: + """ + The raw bytes representation of the URL scheme, such as b"http", b"https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme.encode("ascii") + + @property + def userinfo(self) -> bytes: + """ + The URL userinfo as a raw bytestring. + For example: b"jo%40email.com:a%20secret". + """ + return self._uri_reference.userinfo.encode("ascii") + + @property + def username(self) -> str: + """ + The URL username as a string, with URL decoding applied. + For example: "jo@email.com" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[0]) + + @property + def password(self) -> str: + """ + The URL password as a string, with URL decoding applied. + For example: "a secret" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[2]) + + @property + def host(self) -> str: + """ + The URL host as a string. + Always normalized to lowercase, with IDNA hosts decoded into unicode. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.host == "www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.host == "::ffff:192.168.0.1" + """ + host: str = self._uri_reference.host + + if host.startswith("xn--"): + host = idna.decode(host) + + return host + + @property + def raw_host(self) -> bytes: + """ + The raw bytes representation of the URL host. + Always normalized to lowercase, and IDNA encoded. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.raw_host == b"www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.raw_host == b"::ffff:192.168.0.1" + """ + return self._uri_reference.host.encode("ascii") + + @property + def port(self) -> int | None: + """ + The URL port as an integer. + + Note that the URL class performs port normalization as per the WHATWG spec. + Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always + treated as `None`. + + For example: + + assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") + assert httpx.URL("http://www.example.com:80").port is None + """ + return self._uri_reference.port + + @property + def netloc(self) -> bytes: + """ + Either `` or `:` as bytes. + Always normalized to lowercase, and IDNA encoded. + + This property may be used for generating the value of a request + "Host" header. + """ + return self._uri_reference.netloc.encode("ascii") + + @property + def path(self) -> str: + """ + The URL path as a string. Excluding the query string, and URL decoded. + + For example: + + url = httpx.URL("https://example.com/pa%20th") + assert url.path == "/pa th" + """ + path = self._uri_reference.path or "/" + return unquote(path) + + @property + def query(self) -> bytes: + """ + The URL query string, as raw bytes, excluding the leading b"?". + + This is necessarily a bytewise interface, because we cannot + perform URL decoding of this representation until we've parsed + the keys and values into a QueryParams instance. + + For example: + + url = httpx.URL("https://example.com/?filter=some%20search%20terms") + assert url.query == b"filter=some%20search%20terms" + """ + query = self._uri_reference.query or "" + return query.encode("ascii") + + @property + def params(self) -> QueryParams: + """ + The URL query parameters, neatly parsed and packaged into an immutable + multidict representation. + """ + return QueryParams(self._uri_reference.query) + + @property + def raw_path(self) -> bytes: + """ + The complete URL path and query string as raw bytes. + Used as the target when constructing HTTP requests. + + For example: + + GET /users?search=some%20text HTTP/1.1 + Host: www.example.org + Connection: close + """ + path = self._uri_reference.path or "/" + if self._uri_reference.query is not None: + path += "?" + self._uri_reference.query + return path.encode("ascii") + + @property + def fragment(self) -> str: + """ + The URL fragments, as used in HTML anchors. + As a string, without the leading '#'. + """ + return unquote(self._uri_reference.fragment or "") + + @property + def is_absolute_url(self) -> bool: + """ + Return `True` for absolute URLs such as 'http://example.com/path', + and `False` for relative URLs such as '/path'. + """ + # We don't use `.is_absolute` from `rfc3986` because it treats + # URLs with a fragment portion as not absolute. + # What we actually care about is if the URL provides + # a scheme and hostname to which connections should be made. + return bool(self._uri_reference.scheme and self._uri_reference.host) + + @property + def is_relative_url(self) -> bool: + """ + Return `False` for absolute URLs such as 'http://example.com/path', + and `True` for relative URLs such as '/path'. + """ + return not self.is_absolute_url + + def copy_with(self, **kwargs: typing.Any) -> URL: + """ + Copy this URL, returning a new URL with some components altered. + Accepts the same set of parameters as the components that are made + available via properties on the `URL` class. + + For example: + + url = httpx.URL("https://www.example.com").copy_with( + username="jo@gmail.com", password="a secret" + ) + assert url == "https://jo%40email.com:a%20secret@www.example.com" + """ + return URL(self, **kwargs) + + def copy_set_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.set(key, value)) + + def copy_add_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.add(key, value)) + + def copy_remove_param(self, key: str) -> URL: + return self.copy_with(params=self.params.remove(key)) + + def copy_merge_params(self, params: QueryParamTypes) -> URL: + return self.copy_with(params=self.params.merge(params)) + + def join(self, url: URL | str) -> URL: + """ + Return an absolute URL, using this URL as the base. + + Eg. + + url = httpx.URL("https://www.example.com/test") + url = url.join("/new/path") + assert url == "https://www.example.com/new/path" + """ + from urllib.parse import urljoin + + return URL(urljoin(str(self), str(URL(url)))) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, (URL, str)) and str(self) == str(URL(other)) + + def __str__(self) -> str: + return str(self._uri_reference) + + def __repr__(self) -> str: + scheme, userinfo, host, port, path, query, fragment = self._uri_reference + + if ":" in userinfo: + # Mask any password component. + userinfo = f'{userinfo.split(":")[0]}:[secure]' + + authority = "".join( + [ + f"{userinfo}@" if userinfo else "", + f"[{host}]" if ":" in host else host, + f":{port}" if port is not None else "", + ] + ) + url = "".join( + [ + f"{self.scheme}:" if scheme else "", + f"//{authority}" if authority else "", + path, + f"?{query}" if query is not None else "", + f"#{fragment}" if fragment is not None else "", + ] + ) + + return f"{self.__class__.__name__}({url!r})" + + @property + def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover + import collections + import warnings + + warnings.warn("URL.raw is deprecated.") + RawURL = collections.namedtuple( + "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] + ) + return RawURL( + raw_scheme=self.raw_scheme, + raw_host=self.raw_host, + port=self.port, + raw_path=self.raw_path, + ) + + +class QueryParams(typing.Mapping[str, str]): + """ + URL query parameters, as a multi-dict. + """ + + def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: + assert len(args) < 2, "Too many arguments." + assert not (args and kwargs), "Cannot mix named and unnamed arguments." + + value = args[0] if args else kwargs + + if value is None or isinstance(value, (str, bytes)): + value = value.decode("ascii") if isinstance(value, bytes) else value + self._dict = parse_qs(value, keep_blank_values=True) + elif isinstance(value, QueryParams): + self._dict = {k: list(v) for k, v in value._dict.items()} + else: + dict_value: dict[typing.Any, list[typing.Any]] = {} + if isinstance(value, (list, tuple)): + # Convert list inputs like: + # [("a", "123"), ("a", "456"), ("b", "789")] + # To a dict representation, like: + # {"a": ["123", "456"], "b": ["789"]} + for item in value: + dict_value.setdefault(item[0], []).append(item[1]) + else: + # Convert dict inputs like: + # {"a": "123", "b": ["456", "789"]} + # To dict inputs where values are always lists, like: + # {"a": ["123"], "b": ["456", "789"]} + dict_value = { + k: list(v) if isinstance(v, (list, tuple)) else [v] + for k, v in value.items() + } + + # Ensure that keys and values are neatly coerced to strings. + # We coerce values `True` and `False` to JSON-like "true" and "false" + # representations, and coerce `None` values to the empty string. + self._dict = { + str(k): [primitive_value_to_str(item) for item in v] + for k, v in dict_value.items() + } + + def keys(self) -> typing.KeysView[str]: + """ + Return all the keys in the query params. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.keys()) == ["a", "b"] + """ + return self._dict.keys() + + def values(self) -> typing.ValuesView[str]: + """ + Return all the values in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.values()) == ["123", "789"] + """ + return {k: v[0] for k, v in self._dict.items()}.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return all items in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.items()) == [("a", "123"), ("b", "789")] + """ + return {k: v[0] for k, v in self._dict.items()}.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return all items in the query params. Allow duplicate keys to occur. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] + """ + multi_items: list[tuple[str, str]] = [] + for k, v in self._dict.items(): + multi_items.extend([(k, i) for i in v]) + return multi_items + + def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + """ + Get a value from the query param for a given key. If the key occurs + more than once, then only the first value is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get("a") == "123" + """ + if key in self._dict: + return self._dict[str(key)][0] + return default + + def get_list(self, key: str) -> list[str]: + """ + Get all values from the query param for a given key. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get_list("a") == ["123", "456"] + """ + return list(self._dict.get(str(key), [])) + + def set(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.set("a", "456") + assert q == httpx.QueryParams("a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = [primitive_value_to_str(value)] + return q + + def add(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting or appending the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.add("a", "456") + assert q == httpx.QueryParams("a=123&a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] + return q + + def remove(self, key: str) -> QueryParams: + """ + Return a new QueryParams instance, removing the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.remove("a") + assert q == httpx.QueryParams("") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict.pop(str(key), None) + return q + + def merge(self, params: QueryParamTypes | None = None) -> QueryParams: + """ + Return a new QueryParams instance, updated with. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.merge({"b": "456"}) + assert q == httpx.QueryParams("a=123&b=456") + + q = httpx.QueryParams("a=123") + q = q.merge({"a": "456", "b": "789"}) + assert q == httpx.QueryParams("a=456&b=789") + """ + q = QueryParams(params) + q._dict = {**self._dict, **q._dict} + return q + + def __getitem__(self, key: typing.Any) -> str: + return self._dict[key][0] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __bool__(self) -> bool: + return bool(self._dict) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, self.__class__): + return False + return sorted(self.multi_items()) == sorted(other.multi_items()) + + def __str__(self) -> str: + return urlencode(self.multi_items()) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + query_string = str(self) + return f"{class_name}({query_string!r})" + + def update(self, params: QueryParamTypes | None = None) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.merge(...)` to create an updated copy." + ) + + def __setitem__(self, key: str, value: str) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.set(key, value)` to create an updated copy." + ) diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_utils.py b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe827da4d071b32ea6da44328629699d6fc88ce --- /dev/null +++ b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import ipaddress +import os +import re +import typing +from urllib.request import getproxies + +from ._types import PrimitiveData + +if typing.TYPE_CHECKING: # pragma: no cover + from ._urls import URL + + +def primitive_value_to_str(value: PrimitiveData) -> str: + """ + Coerce a primitive data type into a string value. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +def get_environment_proxies() -> dict[str, str | None]: + """Gets proxy information from the environment""" + + # urllib.request.getproxies() falls back on System + # Registry and Config for proxies on Windows and macOS. + # We don't want to propagate non-HTTP proxies into + # our configuration such as 'TRAVIS_APT_PROXY'. + proxy_info = getproxies() + mounts: dict[str, str | None] = {} + + for scheme in ("http", "https", "all"): + if proxy_info.get(scheme): + hostname = proxy_info[scheme] + mounts[f"{scheme}://"] = ( + hostname if "://" in hostname else f"http://{hostname}" + ) + + no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] + for hostname in no_proxy_hosts: + # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details + # on how names in `NO_PROXY` are handled. + if hostname == "*": + # If NO_PROXY=* is used or if "*" occurs as any one of the comma + # separated hostnames, then we should just bypass any information + # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore + # proxies. + return {} + elif hostname: + # NO_PROXY=.google.com is marked as "all://*.google.com, + # which disables "www.google.com" but not "google.com" + # NO_PROXY=google.com is marked as "all://*google.com, + # which disables "www.google.com" and "google.com". + # (But not "wwwgoogle.com") + # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" + # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 + if "://" in hostname: + mounts[hostname] = None + elif is_ipv4_hostname(hostname): + mounts[f"all://{hostname}"] = None + elif is_ipv6_hostname(hostname): + mounts[f"all://[{hostname}]"] = None + elif hostname.lower() == "localhost": + mounts[f"all://{hostname}"] = None + else: + mounts[f"all://*{hostname}"] = None + + return mounts + + +def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: + return value.encode(encoding) if isinstance(value, str) else value + + +def to_str(value: str | bytes, encoding: str = "utf-8") -> str: + return value if isinstance(value, str) else value.decode(encoding) + + +def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: + return value if isinstance(match_type_of, str) else value.encode() + + +def unquote(value: str) -> str: + return value[1:-1] if value[0] == value[-1] == '"' else value + + +def peek_filelike_length(stream: typing.Any) -> int | None: + """ + Given a file-like stream object, return its length in number of bytes + without reading it into memory. + """ + try: + # Is it an actual file? + fd = stream.fileno() + # Yup, seems to be an actual file. + length = os.fstat(fd).st_size + except (AttributeError, OSError): + # No... Maybe it's something that supports random access, like `io.BytesIO`? + try: + # Assuming so, go to end of stream to figure out its length, + # then put it back in place. + offset = stream.tell() + length = stream.seek(0, os.SEEK_END) + stream.seek(offset) + except (AttributeError, OSError): + # Not even that? Sorry, we're doomed... + return None + + return length + + +class URLPattern: + """ + A utility class currently used for making lookups against proxy keys... + + # Wildcard matching... + >>> pattern = URLPattern("all://") + >>> pattern.matches(httpx.URL("http://example.com")) + True + + # Witch scheme matching... + >>> pattern = URLPattern("https://") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + + # With domain matching... + >>> pattern = URLPattern("https://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # Wildcard scheme, with domain matching... + >>> pattern = URLPattern("all://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + True + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # With port matching... + >>> pattern = URLPattern("https://example.com:1234") + >>> pattern.matches(httpx.URL("https://example.com:1234")) + True + >>> pattern.matches(httpx.URL("https://example.com")) + False + """ + + def __init__(self, pattern: str) -> None: + from ._urls import URL + + if pattern and ":" not in pattern: + raise ValueError( + f"Proxy keys should use proper URL forms rather " + f"than plain scheme strings. " + f'Instead of "{pattern}", use "{pattern}://"' + ) + + url = URL(pattern) + self.pattern = pattern + self.scheme = "" if url.scheme == "all" else url.scheme + self.host = "" if url.host == "*" else url.host + self.port = url.port + if not url.host or url.host == "*": + self.host_regex: typing.Pattern[str] | None = None + elif url.host.startswith("*."): + # *.example.com should match "www.example.com", but not "example.com" + domain = re.escape(url.host[2:]) + self.host_regex = re.compile(f"^.+\\.{domain}$") + elif url.host.startswith("*"): + # *example.com should match "www.example.com" and "example.com" + domain = re.escape(url.host[1:]) + self.host_regex = re.compile(f"^(.+\\.)?{domain}$") + else: + # example.com should match "example.com" but not "www.example.com" + domain = re.escape(url.host) + self.host_regex = re.compile(f"^{domain}$") + + def matches(self, other: URL) -> bool: + if self.scheme and self.scheme != other.scheme: + return False + if ( + self.host + and self.host_regex is not None + and not self.host_regex.match(other.host) + ): + return False + if self.port is not None and self.port != other.port: + return False + return True + + @property + def priority(self) -> tuple[int, int, int]: + """ + The priority allows URLPattern instances to be sortable, so that + we can match from most specific to least specific. + """ + # URLs with a port should take priority over URLs without a port. + port_priority = 0 if self.port is not None else 1 + # Longer hostnames should match first. + host_priority = -len(self.host) + # Longer schemes should match first. + scheme_priority = -len(self.scheme) + return (port_priority, host_priority, scheme_priority) + + def __hash__(self) -> int: + return hash(self.pattern) + + def __lt__(self, other: URLPattern) -> bool: + return self.priority < other.priority + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, URLPattern) and self.pattern == other.pattern + + +def is_ipv4_hostname(hostname: str) -> bool: + try: + ipaddress.IPv4Address(hostname.split("/")[0]) + except Exception: + return False + return True + + +def is_ipv6_hostname(hostname: str) -> bool: + try: + ipaddress.IPv6Address(hostname.split("/")[0]) + except Exception: + return False + return True diff --git a/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/py.typed b/miniconda3/pkgs/httpx-0.28.1-py313h06a4308_1/lib/python3.13/site-packages/httpx/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/derb b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/derb new file mode 100644 index 0000000000000000000000000000000000000000..824c19b6cefdb30ef6271b4ba89936d9850ec6b8 Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/derb differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/genbrk b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/genbrk new file mode 100644 index 0000000000000000000000000000000000000000..f43555c50891f057bb625e763cf8c73e9d14dae4 Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/genbrk differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencfu b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencfu new file mode 100644 index 0000000000000000000000000000000000000000..1bfe3205a3c8ecaa2d93a4314259a7869ac6e68e Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencfu differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencnval b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencnval new file mode 100644 index 0000000000000000000000000000000000000000..33b77f834c0d5d27edcad067913c102d6dfaabdd Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gencnval differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gendict b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gendict new file mode 100644 index 0000000000000000000000000000000000000000..21bd4cfcf2f9a007514cf646647bd90d272c3d06 Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/gendict differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icu-config b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icu-config new file mode 100644 index 0000000000000000000000000000000000000000..e71884a0af2adcc7e9cbd454c370d64916c8ab79 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icu-config @@ -0,0 +1,771 @@ +#!/bin/sh +## -*-sh-*- +#set -x +# BEGIN of icu-config-top +# Copyright (C) 2016 and later: Unicode, Inc. and others. +# License & terms of use: http://www.unicode.org/copyright.html +#****************************************************************************** +# Copyright (C) 1999-2013, International Business Machines +# Corporation and others. All Rights Reserved. +#****************************************************************************** +# This script is designed to aid configuration of ICU. +# rpath links a library search path right into the binaries. +# +# Note: it's preferred to use the .pc files rather than icu-config. +# + +### END of icu-config-top + +## Zero out prefix. +execprefix= +prefix= + + +loaddefs() +{ + +# Following from icu/icu4c/source/config/Makefile.inc +# Copyright (C) 2016 and later: Unicode, Inc. and others. +# License & terms of use: http://www.unicode.org/copyright.html +## -*-makefile-*- +#****************************************************************************** +# Copyright (C) 1999-2014, International Business Machines +# Corporation and others. All Rights Reserved. +#****************************************************************************** +# This Makefile.inc is designed to be included into projects which make use +# of the ICU. + +# CONTENTS OF THIS FILE +# 1). Base configuration information and linkage +# 2). Variables giving access to ICU tools +# 3). Host information +# 4). Compiler flags and settings +# 5). Data Packaging directives +# 6). Include of platform make fragment (mh-* file) + +################################################################## +# +# *1* base configuration information and linkage +# +################################################################## +# The PREFIX is the base of where ICU is installed. +# Inside this directory you should find bin, lib, include/unicode, +# etc. If ICU is not installed in this directory, you must change the +# following line. There should exist ${prefix}/include/unicode/utypes.h +# for example. +default_prefix="/croot/icu_1692293016303/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pla" +if [ "x${prefix}" = "x" ]; then prefix="$default_prefix"; fi +exec_prefix="${prefix}" +libdir="${exec_prefix}/lib" +libexecdir="${exec_prefix}/libexec" +bindir="${exec_prefix}/bin" +datarootdir="${prefix}/share" +datadir="${datarootdir}" +sbindir="${exec_prefix}/sbin" + +# about the ICU version +VERSION="73.1" +UNICODE_VERSION="15.0" + +# The prefix for ICU libraries, normally 'icu' +ICUPREFIX="icu" +PACKAGE="icu" +LIBICU="lib${ICUPREFIX}" + +# Static library prefix and file extension +STATIC_PREFIX="s" +LIBSICU="lib${STATIC_PREFIX}${ICUPREFIX}" +A="a" + +# Suffix at the end of libraries. Usually empty. +ICULIBSUFFIX="" +# ICULIBSUFFIX_VERSION is non-empty if it is to contain a library +# version. For example, if it is 21, it means libraries are named +# libicuuc21.so for example. + +# rpath links a library search path right into the binaries. +## mh-files MUST NOT override RPATHLDFLAGS unless they provide +## equivalent '#SH#' lines for icu-config fixup +default_ENABLE_RPATH="NO" +if [ "x${ENABLE_RPATH}" = "x" ]; then ENABLE_RPATH="$default_ENABLE_RPATH"; fi +RPATHLDFLAGS="${LD_RPATH}${LD_RPATH_PRE}${libdir}" + +# icu-config version of above 'if': +case "x$ENABLE_RPATH" in +x[yY]*) + ENABLE_RPATH=YES + RPATHLDFLAGS="${LD_RPATH}${LD_RPATH_PRE}${libdir}" + ;; + +x[nN]*) + ENABLE_RPATH=NO + RPATHLDFLAGS="" + ;; + +x) + ENABLE_RPATH=NO + RPATHLDFLAGS="" + ;; + +*) + echo $0: Unknown --enable-rpath value ${ENABLE_RPATH} 1>&2 + exit 3 + ;; +esac + +# Name flexibility for the library naming scheme. Any modifications should +# be made in the mh- file for the specific platform. +DATA_STUBNAME="data" +COMMON_STUBNAME="uc" +I18N_STUBNAME="i18n" +LAYOUTEX_STUBNAME="lx" +IO_STUBNAME="io" +TOOLUTIL_STUBNAME="tu" +CTESTFW_STUBNAME="test" + + +### To link your application with ICU: +# 1. use LDFLAGS, CFLAGS, etc from above +# 2. link with ${ICULIBS} +# 3. optionally, add one or more of: +# - ${ICULIBS_I18N} - i18n library, formatting, etc. +# - ${ICULIBS_ICUIO} - ICU stdio equivalent library + +ICULIBS_COMMON="-l${ICUPREFIX}uc${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_DATA="-l${ICUPREFIX}${DATA_STUBNAME}${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_I18N="-l${ICUPREFIX}${I18N_STUBNAME}${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_TOOLUTIL="-l${ICUPREFIX}tu${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_CTESTFW="-l${ICUPREFIX}ctestfw${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_ICUIO="-l${ICUPREFIX}io${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_OBSOLETE="-l${ICUPREFIX}obsolete${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_LAYOUTEX="-l${ICUPREFIX}lx${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}" +ICULIBS_BASE="-L${libdir}" + +# for icu-config to test with +ICULIBS_COMMON_LIB_NAME="${LIBICU}${COMMON_STUBNAME}${ICULIBSUFFIX}${ICULIBSUFFIX_VERSION}.${SO}" +ICULIBS_COMMON_LIB_NAME_A="${LIBICU}${COMMON_STUBNAME}${ICULIBSUFFIX}.${A}" + +# ICULIBS is the set of libraries your application should link +# with usually. Many applications will want to add ${ICULIBS_I18N} as well. +ICULIBS="${ICULIBS_BASE} ${ICULIBS_I18N} ${ICULIBS_COMMON} ${ICULIBS_DATA} " + +# Proper echo newline handling is needed in icu-config +ECHO_N="-n" +ECHO_C="" +# Not currently being used but good to have for proper tab handling +ECHO_T="" + +################################################################## +# +# *2* access to ICU tools +# +################################################################## +# Environment variable to set a runtime search path +# (Overridden when necessary in -mh files) +LDLIBRARYPATH_ENVVAR="LD_LIBRARY_PATH" + +# Versioned target for a shared library +## FINAL_SO_TARGET = ${SO_TARGET}.${SO_TARGET_VERSION} +## MIDDLE_SO_TARGET = ${SO_TARGET}.${SO_TARGET_VERSION_MAJOR} + +# Access to important ICU tools. +# Use as follows: ${INVOKE} ${GENRB} arguments .. +INVOKE="${LDLIBRARYPATH_ENVVAR}=${libdir}:$$${LDLIBRARYPATH_ENVVAR} ${LEAK_CHECKER}" +GENCCODE="${sbindir}/genccode" +ICUPKG="${sbindir}/icupkg" +GENCMN="${sbindir}/gencmn" +GENRB="${bindir}/genrb" +PKGDATA="${bindir}/pkgdata" + +# moved here because of dependencies +pkgdatadir="${datadir}/${PACKAGE}${ICULIBSUFFIX}/${VERSION}" +pkglibdir="${libdir}/${PACKAGE}${ICULIBSUFFIX}/${VERSION}" + +################################################################## +# +# *3* Information about the host +# +################################################################## + +# Information about the host that 'configure' was run on. +host="x86_64-conda-linux-gnu" +host_alias="x86_64-conda-linux-gnu" +host_cpu="x86_64" +host_vendor="conda" +host_os="linux-gnu" +# Our platform canonical name (as determined by configure) +# this is a #define value (i.e. U_XXXX or XXXX) +platform="U_LINUX" + +################################################################## +# +# *4* compiler flags and misc. options +# +################################################################## +AR="/croot/icu_1692293016303/_build_env/bin/x86_64-conda-linux-gnu-ar" +# initial tab keeps it out of the shell version. +ARFLAGS=" ${ARFLAGS}" +CC="/croot/icu_1692293016303/_build_env/bin/x86_64-conda-linux-gnu-cc" +CPP="/croot/icu_1692293016303/_build_env/bin/x86_64-conda-linux-gnu-cpp" +CFLAGS="" +CPPFLAGS="-I${prefix}/include" +CXXFLAGS="" +CXX="/croot/icu_1692293016303/_build_env/bin/x86_64-conda-linux-gnu-c++" +DEFAULT_MODE="dll" +DEFS="-DPACKAGE_NAME=\"ICU\" -DPACKAGE_TARNAME=\"International\ Components\ for\ Unicode\" -DPACKAGE_VERSION=\"73.1\" -DPACKAGE_STRING=\"ICU\ 73.1\" -DPACKAGE_BUGREPORT=\"http://icu-project.org/bugs\" -DPACKAGE_URL=\"http://icu-project.org\" -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DSIZEOF_VOID_P=8 -DHAVE_LIBM=1 -DHAVE_ELF_H=1 -DHAVE_DLFCN_H=1 -DHAVE_DLOPEN=1 -DHAVE_GETTIMEOFDAY=1 -DHAVE_LIBPTHREAD=1 -DHAVE_INTTYPES_H=1 -DHAVE_DIRENT_H=1 -DHAVE_WCHAR_H=1 -DSIZEOF_WCHAR_T=4 " +# use a consistent INSTALL +INSTALL="${SHELL} ${pkgdatadir}/install-sh -c" +INSTALL_DATA="${INSTALL} -m 644" +INSTALL_PROGRAM="${INSTALL}" +INSTALL_SCRIPT="${INSTALL}" +LDFLAGS="${RPATHLDFLAGS}" +LIBS="-lpthread -ldl -lm " +LIB_M="" +LIB_VERSION="73.1" +LIB_VERSION_MAJOR="73" +MKINSTALLDIRS="${SHELL} ${pkgdatadir}/mkinstalldirs" +RANLIB="/croot/icu_1692293016303/_build_env/bin/x86_64-conda-linux-gnu-ranlib" +RMV="rm -rf" +SHELL="/bin/sh" +SHLIB_c="${CC} ${DEFS} ${CPPFLAGS} ${CFLAGS} ${LDFLAGS} -shared" +SHLIB_cc="${CXX} ${DEFS} ${CPPFLAGS} ${CXXFLAGS} ${LDFLAGS} -shared" +U_IS_BIG_ENDIAN="0" +includedir="${prefix}/include" +infodir="${datarootdir}/info" +localstatedir="${prefix}/var" +mandir="${datarootdir}/man" +oldincludedir="/usr/include" +program_transform_name="s,x,x," +sharedstatedir="${prefix}/com" +sysconfdir="${prefix}/etc" +INSTALL_L="${INSTALL_DATA}" + +# for derivative builds - don't bother with VERBOSE/NONVERBOSE SILENT_COMPILE + +################################################################## +# +# *5* packaging options and directories +# +################################################################## + +# The basename of the ICU data file (i.e. icudt21b ) +ICUDATA_CHAR="l" +ICUDATA_NAME="icudt73l" + +# Defaults for pkgdata's mode and directories +# The default data dir changes depending on what packaging mode +# is being used +if [ "x$PKGDATA_MODE" = "x" ]; +then +PKGDATA_MODE="dll" +fi + +case "$PKGDATA_MODE" in +common) +ICUDATA_DIR="${pkgdatadir}" +ICUPKGDATA_DIR="${ICUDATA_DIR}" +;; +dll) +ICUDATA_DIR="${pkgdatadir}" +ICUPKGDATA_DIR="${libdir}" +;; +*) +ICUDATA_DIR="${pkgdatadir}" +ICUPKGDATA_DIR="${ICUDATA_DIR}" +;; + +esac + +GENCCODE_ASSEMBLY="-a gcc" + +################################################################## +# +# *6* Inclusion of platform make fragment (mh-* file) +# +################################################################## +# The mh- file ("make fragment") for the platform is included here. +# It may override the above settings. +# It is put last so that the mh-file can override anything. +# The selfcheck is just a sanity check that this makefile is +# parseable. The mh fragment is only included if this does not occur. + +# Following from mh-linux +## -*-makefile-*- +## Copyright (C) 2016 and later: Unicode, Inc. and others. +## License & terms of use: http://www.unicode.org/copyright.html +## Linux-specific setup +## Copyright (c) 1999-2013, International Business Machines Corporation and +## others. All Rights Reserved. + +## Commands to generate dependency files +GEN_DEPS_c="${CC} -E -MM ${DEFS} ${CPPFLAGS}" +GEN_DEPS_cc="${CXX} -E -MM ${DEFS} ${CPPFLAGS} ${CXXFLAGS}" + +## Flags for position independent code +SHAREDLIBCFLAGS="-fPIC" +SHAREDLIBCXXFLAGS="-fPIC" +SHAREDLIBCPPFLAGS="-DPIC" + +## Additional flags when building libraries and with threads +THREADSCPPFLAGS="-D_REENTRANT" +LIBCPPFLAGS="" + +## Compiler switch to embed a runtime search path +LD_RPATH="-Wl,-zorigin,-rpath,\$\$ORIGIN " +LD_RPATH_PRE="-Wl,-rpath," + +## These are the library specific LDFLAGS +LDFLAGSICUDT="-nodefaultlibs -nostdlib" + +## Compiler switch to embed a library name +# The initial tab in the next line is to prevent icu-config from reading it. +# We can't depend on MIDDLE_SO_TARGET being set. +LD_SONAME= + +## Shared library options +LD_SOOPTIONS="-Wl,-Bsymbolic" + +## Shared object suffix +SO="so" +## Non-shared intermediate object suffix +STATIC_O="ao" + +## Compilation rules + +## Dependency rules + +## Versioned libraries rules + +## Bind internal references + +# LDflags that pkgdata will use +BIR_LDFLAGS="-Wl,-Bsymbolic" + +# Dependencies [i.e. map files] for the final library +BIR_DEPS="" + +## Remove shared library 's' +STATIC_PREFIX_WHEN_USED="" +STATIC_PREFIX="" + +## End Linux-specific setup + +## -*-sh-*- +## BEGIN of icu-config-bottom. +## Copyright (C) 2016 and later: Unicode, Inc. and others. +## License & terms of use: http://www.unicode.org/copyright.html +## Copyright (c) 2002-2013, International Business Machines Corporation and +## others. All Rights Reserved. + +# For MinGW do we want the common DLL to go into the bin location? +if [ "$MINGW_MOVEDLLSTOBINDIR" = "YES" ]; then + ICUUC_FILE="${bindir}/${ICULIBS_COMMON_LIB_NAME}" +else + ICUUC_FILE="${libdir}/${ICULIBS_COMMON_LIB_NAME}" +fi + +ICUUC_FILE_A="${libdir}/${ICULIBS_COMMON_LIB_NAME_A}" + +# echo ENABLE RPATH $ENABLE_RPATH and RPATHLDFLAGS=${RPATH_LDFLAGS} +if [ "x$PKGDATA_MODE" = "x" ]; then + PKGDATA_MODE=dll +fi + +} + +## The actual code of icu-config goes here. + +ME=`basename "$0"` + +allflags() +{ + echo " --noverify Don't verify that ICU is actually installed." + echo " --bindir Print binary directory path (bin)" + echo " --cc Print C compiler used [CC]" + echo " --cflags Print C compiler flags [CFLAGS]" + echo " --cflags-dynamic Print additional C flags for" + echo " building shared libraries." + echo " --cppflags Print C Preprocessor flags [CPPFLAGS]" + echo " --cppflags-dynamic Print additional C Preprocessor flags for" + echo " building shared libraries." + echo " --cppflags-searchpath Print only -I include directives (-Iinclude)" + echo " --cxx Print C++ compiler used [CXX]" + echo " --cxxflags Print C++ compiler flags [CXXFLAGS]" + echo " --cxxflags-dynamic Print additional C++ flags for" + echo " building shared libraries." + echo " --detect-prefix Attempt to detect prefix based on PATH" + echo " --exec-prefix Print prefix for executables (/bin)" + echo " --exists Return with 0 status if ICU exists else fail" + echo " --help, -?, --usage Print this message" + echo " --icudata Print shortname of ICU data file (icudt21l)" + echo " --icudata-install-dir Print path to install data to - use as --install option to pkgdata(1)" + echo " --icudata-mode Print default ICU pkgdata mode (dll) - use as --mode option to pkgdata(1)." + echo " --icudatadir Print path to packaged archive data. Can set as [ICU_DATA]" + echo " --invoke Print commands to invoke an ICU program" + echo " --invoke= Print commands to invoke an ICU program named (ex: genrb)" + echo " --ldflags Print -L search path and -l libraries to link with ICU [LDFLAGS]. This is for the data, uc (common), and i18n libraries only. " + echo " --ldflags-libsonly Same as --ldflags, but only the -l directives" + echo " --ldflags-searchpath Print only -L (search path) directive" + echo " --ldflags-system Print only system libs ICU links with (-lpthread, -lm)" + echo " --ldflags-icuio Print ICU icuio link directive. Use in addition to --ldflags " + echo " --ldflags-obsolete Print ICU obsolete link directive. Use in addition to --ldflags. (requires icuapps/obsolete to be built and installed.) " + echo " --mandir Print manpage (man) path" + echo " --prefix Print PREFIX to icu install (/usr/local)" + echo " --prefix=XXX Set prefix to XXX for remainder of command" + echo " --sbindir Print system binary path (sbin) " + echo " --shared-datadir Print shared data (share) path. This is NOT the ICU data dir." + echo " --shlib-c Print the command to compile and build C shared libraries with ICU" + echo " --shlib-cc Print the command to compile and build C++ shared libraries with ICU" + echo " --sysconfdir Print system config (etc) path" + echo " --unicode-version Print version of Unicode data used in ICU ($UNICODE_VERSION)" + echo " --version Print ICU version ($VERSION)" + echo " --incfile Print path to Makefile.inc" + echo " --incpkgdatafile Print path to pkgdata.inc (for -O option of pkgdata)" + echo " --install Print path to install-sh" + echo " --mkinstalldirs Print path to mkinstalldirs" +} + +## Print the normal usage message +shortusage() +{ + echo "usage: ${ME} " `allflags | cut -c-25 | sed -e 's%.*%[ & ]%'` +} + + +usage() +{ + echo "${ME}: icu-config: ICU configuration helper script" + echo + echo "The most commonly used options will be --cflags, --cxxflags, --cppflags, and --ldflags." + echo 'Example (in make): CPFLAGS=$(shell icu-config --cppflags)' + echo ' LDFLAGS=$(shell icu-config --ldflags)' + echo " (etc).." + echo + echo "Usage:" + allflags + + echo + echo " [Brackets] show MAKE variable equivalents, (parenthesis) show example output" + echo + echo "Copyright (c) 2002-2013, International Business Machines Corporation and others. All Rights Reserved." + echo + echo "NOTE: Please consider using the pkg-config (.pc) files instead of icu-config." + echo " See: " +} + +## Check the sanity of current variables +sanity() +{ + if [ ! -f "${ICUUC_FILE}" -a ! -f "${ICUUC_FILE_A}" ] && [ ${IGNORE_ICUUC_FILE_CHECK} = "no" ] && [ ${SANITY} = "sane" ]; + then + echo "### $ME: Can't find ${ICUUC_FILE} - ICU prefix is wrong." 1>&2 + echo "### Try the --prefix= option " 1>&2 + echo "### or --detect-prefix" 1>&2 + echo "### (If you want to disable this check, use the --noverify option)" 1>&2 + echo "### $ME: Exitting." 1>&2 + exit 2 + fi +} + +## Main starts here. + +if [ $# -lt 1 ]; then + shortusage + exit 1 +fi + +# For certain options (e.g. --detect-prefix) don't check for icuuc library file. + +IGNORE_ICUUC_FILE_CHECK="no"; + +SANITY="sane" + +case "$1" in +--noverify) + SANITY="nosanity" + shift + ;; +esac + +case "$1" in +*prefix*) + IGNORE_ICUUC_FILE_CHECK="yes" + ;; +esac + +# Load our variables from autoconf +# ALWAYS load twice because of dependencies +loaddefs +loaddefs + +if [ $# -gt 0 -a $1 = "--selfcheck" ]; +then + echo "passed" + exit + # EXIT for self check +fi + +sanity + +while [ $# -gt 0 ]; +do + arg="$1" + var=`echo $arg | sed -e 's/^[^=]*=//'` +# echo "### processing $arg" 1>&2 + case "$arg" in + + # undocumented. + --debug) + set -x + ;; + + --noverify) + echo "### $ME: Error: --noverify must be the first argument." 1>&2 + exit 1 + ;; + + --so) + echo $SO + ;; + + --bindir) + echo $bindir + ;; + + --libdir) + echo $libdir + ;; + + --exists) + sanity + ;; + + --sbindir) + echo $sbindir + ;; + + --mkinstalldirs) + echo ${MKINSTALLDIRS} + ;; + + --install) + echo ${INSTALL} + ;; + + --invoke=*) + QUOT="\"" + CMD="${var}" + + # If it's not a locally executable command (1st choice) then + # search for it in the ICU directories. + if [ ! -x ${CMD} ]; then + if [ -x ${bindir}/${var} ]; then + CMD="${bindir}/${var}" + fi + if [ -x ${sbindir}/${var} ]; then + CMD="${sbindir}/${var}" + fi + fi + + echo "env ${QUOT}${LDLIBRARYPATH_ENVVAR}=${libdir}:"'${'"${LDLIBRARYPATH_ENVVAR}"'}'${QUOT} ${CMD} + ;; + + --invoke) + QUOT="\"" + echo "env ${QUOT}${LDLIBRARYPATH_ENVVAR}=${libdir}:"'${'"${LDLIBRARYPATH_ENVVAR}"'}'${QUOT} + ;; + + --cflags) + echo $ECHO_N "${CFLAGS} ${ECHO_C}" + ;; + + --cc) + echo $ECHO_N "${CC} ${ECHO_C}" + ;; + + --cxx) + echo $ECHO_N "${CXX} ${ECHO_C}" + ;; + + --cxxflags) + echo $ECHO_N "${CXXFLAGS} ${ECHO_C}" + ;; + + --cppflags) + # Don't echo the -I. - it's unneeded. + echo $ECHO_N "${CPPFLAGS} ${ECHO_C}" | sed -e 's/-I. //' + ;; + + --cppflags-searchpath) + echo $ECHO_N "-I${prefix}/include ${ECHO_C}" + ;; + + --cppflags-dynamic) + echo $ECHO_N "${SHAREDLIBCPPFLAGS} ${ECHO_C}" + ;; + + --cxxflags-dynamic) + echo $ECHO_N "${SHAREDLIBCXXFLAGS} ${ECHO_C}" + ;; + + --cflags-dynamic) + echo $ECHO_N "${SHAREDLIBCFLAGS} ${ECHO_C}" + ;; + + --ldflags-system) + echo $ECHO_N "${LIBS} ${ECHO_C}" + ;; + + --ldflags) + echo $ECHO_N "${LDFLAGS} ${ICULIBS} ${ECHO_C}" +# $RPATH_LDFLAGS + ;; + + --ldflags-libsonly) + echo $ECHO_N "${ICULIBS_I18N} ${ICULIBS_COMMON} ${ICULIBS_DATA} ${ECHO_C}" + ;; + + --ldflags-icuio) + echo $ECHO_N " ${ICULIBS_ICUIO} ${ECHO_C}" + ;; + + --ldflags-obsolete) + echo $ECHO_N "${ICULIBS_OBSOLETE} ${ECHO_C}" + ;; + + --ldflags-toolutil) + echo $ECHO_N " ${ICULIBS_TOOLUTIL} ${ECHO_C}" + ;; + + --ldflags-layout) + echo ${ME}: ERROR: the old layout engine has been removed. use HarfBuzz. + exit 1 + ;; + + --ldflags-searchpath) + echo $ECHO_N "-L${libdir} ${ECHO_C}" + ;; + + --detect-prefix) + HERE=`echo $0 | sed -e "s/$ME//g"` + if [ -f "${HERE}/../lib/${ICULIBS_COMMON_LIB_NAME}" -o -f "${HERE}/../lib/${ICULIBS_COMMON_LIB_NAME_A}" ]; then + prefix="${HERE}/.." + echo "## Using --prefix=${prefix}" 1>&2 + fi + loaddefs + loaddefs + ;; + + --exec-prefix) + echo $exec_prefix + ;; + + --prefix) + echo $prefix + ;; + + --prefix=*) + prefix=$var + loaddefs + loaddefs + ;; + + --sysconfdir) + echo $sysconfdir + ;; + + --mandir) + echo $mandir + ;; + + --shared-datadir) + echo $ECHO_N "${datadir} ${ECHO_C}" + ;; + + --incfile) + echo $ECHO_N "${pkglibdir}/Makefile.inc ${ECHO_C}" + ;; + + --incpkgdatafile) + echo $ECHO_N "${pkglibdir}/pkgdata.inc ${ECHO_C}" + ;; + + --icudata) + echo $ECHO_N "${ICUDATA_NAME} ${ECHO_C}" + ;; + + --icudata-mode) + echo $ECHO_N "${PKGDATA_MODE} ${ECHO_C}" + ;; + + --icudata-install-dir) + echo $ECHO_N "${ICUPKGDATA_DIR} ${ECHO_C}" + ;; + + --icudatadir) + echo $ECHO_N "${ICUDATA_DIR} ${ECHO_C}" + ;; + + --shlib-c) + echo $ECHO_N "${SHLIB_c} ${ECHO_C}" + ;; + + --shlib-cc) + echo $ECHO_N "${SHLIB_cc} ${ECHO_C}" + ;; + + --version) + echo $ECHO_N $VERSION + ;; + + --unicode-version) + echo $ECHO_N $UNICODE_VERSION + ;; + + --host) + echo $host + exit 0 + ;; + + --help) + usage + exit 0 + ;; + + --usage) + usage + exit 0 + ;; + +# --enable-rpath=*) +# ENABLE_RPATH=$var +# loaddefs +# ;; + + -?) + usage + exit 0 + ;; + + *) + echo ${ME}: ERROR Unknown Option $arg 1>&2 + echo 1>&2 + shortusage 1>&2 + echo "### $ME: Exitting." 1>&2 + exit 1; + ;; + esac + shift + + # Reset the ignore icuuc file check flag + if [ $IGNORE_ICUUC_FILE_CHECK = "yes" ]; then + IGNORE_ICUUC_FILE_CHECK="no" + sanity + fi +done +echo +# Check once before we quit (will check last used prefix) +sanity +## END of icu-config-bottom + +exit 0 diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuexportdata b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuexportdata new file mode 100644 index 0000000000000000000000000000000000000000..5102f69543793605c942d6c03e056f6eb6fcfe84 Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuexportdata differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuinfo b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuinfo new file mode 100644 index 0000000000000000000000000000000000000000..da9f50404fc8b7374e957d1ffc3c26b9c8967e9a Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/icuinfo differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/makeconv b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/makeconv new file mode 100644 index 0000000000000000000000000000000000000000..a905f80313f988e0b7dbdbc33f97a7efebbdf97e Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/makeconv differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/pkgdata b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/pkgdata new file mode 100644 index 0000000000000000000000000000000000000000..6d3d740f7d421d6c24dd0669d9a5de4921a98665 Binary files /dev/null and b/miniconda3/pkgs/icu-73.1-h6a678d5_0/bin/pkgdata differ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/alphaindex.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/alphaindex.h new file mode 100644 index 0000000000000000000000000000000000000000..cbce21271767561f93131956bc792db24c149b18 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/alphaindex.h @@ -0,0 +1,766 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2011-2014 International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +*/ + +#ifndef INDEXCHARS_H +#define INDEXCHARS_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/locid.h" +#include "unicode/unistr.h" + +#if !UCONFIG_NO_COLLATION + +/** + * \file + * \brief C++ API: Index Characters + */ + +U_CDECL_BEGIN + +/** + * Constants for Alphabetic Index Label Types. + * The form of these enum constants anticipates having a plain C API + * for Alphabetic Indexes that will also use them. + * @stable ICU 4.8 + */ +typedef enum UAlphabeticIndexLabelType { + /** + * Normal Label, typically the starting letter of the names + * in the bucket with this label. + * @stable ICU 4.8 + */ + U_ALPHAINDEX_NORMAL = 0, + + /** + * Underflow Label. The bucket with this label contains names + * in scripts that sort before any of the bucket labels in this index. + * @stable ICU 4.8 + */ + U_ALPHAINDEX_UNDERFLOW = 1, + + /** + * Inflow Label. The bucket with this label contains names + * in scripts that sort between two of the bucket labels in this index. + * Inflow labels are created when an index contains normal labels for + * multiple scripts, and skips other scripts that sort between some of the + * included scripts. + * @stable ICU 4.8 + */ + U_ALPHAINDEX_INFLOW = 2, + + /** + * Overflow Label. The bucket with this label contains names in scripts + * that sort after all of the bucket labels in this index. + * @stable ICU 4.8 + */ + U_ALPHAINDEX_OVERFLOW = 3 +} UAlphabeticIndexLabelType; + + +struct UHashtable; +U_CDECL_END + +U_NAMESPACE_BEGIN + +// Forward Declarations + +class BucketList; +class Collator; +class RuleBasedCollator; +class StringEnumeration; +class UnicodeSet; +class UVector; + +/** + * AlphabeticIndex supports the creation of a UI index appropriate for a given language. + * It can support either direct use, or use with a client that doesn't support localized collation. + * The following is an example of what an index might look like in a UI: + * + *
+ *  ... A B C D E F G H I J K L M N O P Q R S T U V W X Y Z  ...
+ *
+ *  A
+ *     Addison
+ *     Albertson
+ *     Azensky
+ *  B
+ *     Baker
+ *  ...
+ * 
+ * + * The class can generate a list of labels for use as a UI "index", that is, a list of + * clickable characters (or character sequences) that allow the user to see a segment + * (bucket) of a larger "target" list. That is, each label corresponds to a bucket in + * the target list, where everything in the bucket is greater than or equal to the character + * (according to the locale's collation). Strings can be added to the index; + * they will be in sorted order in the right bucket. + *

+ * The class also supports having buckets for strings before the first (underflow), + * after the last (overflow), and between scripts (inflow). For example, if the index + * is constructed with labels for Russian and English, Greek characters would fall + * into an inflow bucket between the other two scripts. + *

+ * The AlphabeticIndex class is not intended for public subclassing. + * + *

Note: If you expect to have a lot of ASCII or Latin characters + * as well as characters from the user's language, + * then it is a good idea to call addLabels(Locale::getEnglish(), status).

+ * + *

Direct Use

+ *

The following shows an example of building an index directly. + * The "show..." methods below are just to illustrate usage. + * + *

+ * // Create a simple index.  "Item" is assumed to be an application
+ * // defined type that the application's UI and other processing knows about,
+ * //  and that has a name.
+ *
+ * UErrorCode status = U_ZERO_ERROR;
+ * AlphabeticIndex index = new AlphabeticIndex(desiredLocale, status);
+ * index->addLabels(additionalLocale, status);
+ * for (Item *item in some source of Items ) {
+ *     index->addRecord(item->name(), item, status);
+ * }
+ * ...
+ * // Show index at top. We could skip or gray out empty buckets
+ *
+ * while (index->nextBucket(status)) {
+ *     if (showAll || index->getBucketRecordCount() != 0) {
+ *         showLabelAtTop(UI, index->getBucketLabel());
+ *     }
+ * }
+ *  ...
+ * // Show the buckets with their contents, skipping empty buckets
+ *
+ * index->resetBucketIterator(status);
+ * while (index->nextBucket(status)) {
+ *    if (index->getBucketRecordCount() != 0) {
+ *        showLabelInList(UI, index->getBucketLabel());
+ *        while (index->nextRecord(status)) {
+ *            showIndexedItem(UI, static_cast(index->getRecordData()))
+ * 
+ * + * The caller can build different UIs using this class. + * For example, an index character could be omitted or grayed-out + * if its bucket is empty. Small buckets could also be combined based on size, such as: + * + *
+ * ... A-F G-N O-Z ...
+ * 
+ * + *

Client Support

+ *

Callers can also use the AlphabeticIndex::ImmutableIndex, or the AlphabeticIndex itself, + * to support sorting on a client that doesn't support AlphabeticIndex functionality. + * + *

The ImmutableIndex is both immutable and thread-safe. + * The corresponding AlphabeticIndex methods are not thread-safe because + * they "lazily" build the index buckets. + *

    + *
  • ImmutableIndex.getBucket(index) provides random access to all + * buckets and their labels and label types. + *
  • The AlphabeticIndex bucket iterator or ImmutableIndex.getBucket(0..getBucketCount-1) + * can be used to get a list of the labels, + * such as "...", "A", "B",..., and send that list to the client. + *
  • When the client has a new name, it sends that name to the server. + * The server needs to call the following methods, + * and communicate the bucketIndex and collationKey back to the client. + * + *
    + * int32_t bucketIndex = index.getBucketIndex(name, status);
    + * const UnicodeString &label = immutableIndex.getBucket(bucketIndex)->getLabel();  // optional
    + * int32_t skLength = collator.getSortKey(name, sk, skCapacity);
    + * 
    + * + *
  • The client would put the name (and associated information) into its bucket for bucketIndex. The sort key sk is a + * sequence of bytes that can be compared with a binary compare, and produce the right localized result.
  • + *
+ * + * @stable ICU 4.8 + */ +class U_I18N_API AlphabeticIndex: public UObject { +public: + /** + * An index "bucket" with a label string and type. + * It is referenced by getBucketIndex(), + * and returned by ImmutableIndex.getBucket(). + * + * The Bucket class is not intended for public subclassing. + * @stable ICU 51 + */ + class U_I18N_API Bucket : public UObject { + public: + /** + * Destructor. + * @stable ICU 51 + */ + virtual ~Bucket(); + + /** + * Returns the label string. + * + * @return the label string for the bucket + * @stable ICU 51 + */ + const UnicodeString &getLabel() const { return label_; } + /** + * Returns whether this bucket is a normal, underflow, overflow, or inflow bucket. + * + * @return the bucket label type + * @stable ICU 51 + */ + UAlphabeticIndexLabelType getLabelType() const { return labelType_; } + + private: + friend class AlphabeticIndex; + friend class BucketList; + + UnicodeString label_; + UnicodeString lowerBoundary_; + UAlphabeticIndexLabelType labelType_; + Bucket *displayBucket_; + int32_t displayIndex_; + UVector *records_; // Records are owned by the inputList_ vector. + + Bucket(const UnicodeString &label, // Parameter strings are copied. + const UnicodeString &lowerBoundary, + UAlphabeticIndexLabelType type); + }; + + /** + * Immutable, thread-safe version of AlphabeticIndex. + * This class provides thread-safe methods for bucketing, + * and random access to buckets and their properties, + * but does not offer adding records to the index. + * + * The ImmutableIndex class is not intended for public subclassing. + * + * @stable ICU 51 + */ + class U_I18N_API ImmutableIndex : public UObject { + public: + /** + * Destructor. + * @stable ICU 51 + */ + virtual ~ImmutableIndex(); + + /** + * Returns the number of index buckets and labels, including underflow/inflow/overflow. + * + * @return the number of index buckets + * @stable ICU 51 + */ + int32_t getBucketCount() const; + + /** + * Finds the index bucket for the given name and returns the number of that bucket. + * Use getBucket() to get the bucket's properties. + * + * @param name the string to be sorted into an index bucket + * @param errorCode Error code, will be set with the reason if the + * operation fails. + * @return the bucket number for the name + * @stable ICU 51 + */ + int32_t getBucketIndex(const UnicodeString &name, UErrorCode &errorCode) const; + + /** + * Returns the index-th bucket. Returns nullptr if the index is out of range. + * + * @param index bucket number + * @return the index-th bucket + * @stable ICU 51 + */ + const Bucket *getBucket(int32_t index) const; + + private: + friend class AlphabeticIndex; + + ImmutableIndex(BucketList *bucketList, Collator *collatorPrimaryOnly) + : buckets_(bucketList), collatorPrimaryOnly_(collatorPrimaryOnly) {} + + BucketList *buckets_; + Collator *collatorPrimaryOnly_; + }; + + /** + * Construct an AlphabeticIndex object for the specified locale. If the locale's + * data does not include index characters, a set of them will be + * synthesized based on the locale's exemplar characters. The locale + * determines the sorting order for both the index characters and the + * user item names appearing under each Index character. + * + * @param locale the desired locale. + * @param status Error code, will be set with the reason if the construction + * of the AlphabeticIndex object fails. + * @stable ICU 4.8 + */ + AlphabeticIndex(const Locale &locale, UErrorCode &status); + + /** + * Construct an AlphabeticIndex that uses a specific collator. + * + * The index will be created with no labels; the addLabels() function must be called + * after creation to add the desired labels to the index. + * + * The index adopts the collator, and is responsible for deleting it. + * The caller should make no further use of the collator after creating the index. + * + * @param collator The collator to use to order the contents of this index. + * @param status Error code, will be set with the reason if the + * operation fails. + * @stable ICU 51 + */ + AlphabeticIndex(RuleBasedCollator *collator, UErrorCode &status); + + /** + * Add Labels to this Index. The labels are additions to those + * that are already in the index; they do not replace the existing + * ones. + * @param additions The additional characters to add to the index, such as A-Z. + * @param status Error code, will be set with the reason if the + * operation fails. + * @return this, for chaining + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &addLabels(const UnicodeSet &additions, UErrorCode &status); + + /** + * Add the index characters from a Locale to the index. The labels + * are added to those that are already in the index; they do not replace the + * existing index characters. The collation order for this index is not + * changed; it remains that of the locale that was originally specified + * when creating this Index. + * + * @param locale The locale whose index characters are to be added. + * @param status Error code, will be set with the reason if the + * operation fails. + * @return this, for chaining + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &addLabels(const Locale &locale, UErrorCode &status); + + /** + * Destructor + * @stable ICU 4.8 + */ + virtual ~AlphabeticIndex(); + + /** + * Builds an immutable, thread-safe version of this instance, without data records. + * + * @return an immutable index instance + * @stable ICU 51 + */ + ImmutableIndex *buildImmutableIndex(UErrorCode &errorCode); + + /** + * Get the Collator that establishes the ordering of the items in this index. + * Ownership of the collator remains with the AlphabeticIndex instance. + * + * The returned collator is a reference to the internal collator used by this + * index. It may be safely used to compare the names of items or to get + * sort keys for names. However if any settings need to be changed, + * or other non-const methods called, a cloned copy must be made first. + * + * @return The collator + * @stable ICU 4.8 + */ + virtual const RuleBasedCollator &getCollator() const; + + + /** + * Get the default label used for abbreviated buckets *between* other index characters. + * For example, consider the labels when Latin (X Y Z) and Greek (Α Β Γ) are used: + * + * X Y Z ... Α Β Γ. + * + * @return inflow label + * @stable ICU 4.8 + */ + virtual const UnicodeString &getInflowLabel() const; + + /** + * Set the default label used for abbreviated buckets between other index characters. + * An inflow label will be automatically inserted if two otherwise-adjacent label characters + * are from different scripts, e.g. Latin and Cyrillic, and a third script, e.g. Greek, + * sorts between the two. The default inflow character is an ellipsis (...) + * + * @param inflowLabel the new Inflow label. + * @param status Error code, will be set with the reason if the operation fails. + * @return this + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &setInflowLabel(const UnicodeString &inflowLabel, UErrorCode &status); + + + /** + * Get the special label used for items that sort after the last normal label, + * and that would not otherwise have an appropriate label. + * + * @return the overflow label + * @stable ICU 4.8 + */ + virtual const UnicodeString &getOverflowLabel() const; + + + /** + * Set the label used for items that sort after the last normal label, + * and that would not otherwise have an appropriate label. + * + * @param overflowLabel the new overflow label. + * @param status Error code, will be set with the reason if the operation fails. + * @return this + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &setOverflowLabel(const UnicodeString &overflowLabel, UErrorCode &status); + + /** + * Get the special label used for items that sort before the first normal label, + * and that would not otherwise have an appropriate label. + * + * @return underflow label + * @stable ICU 4.8 + */ + virtual const UnicodeString &getUnderflowLabel() const; + + /** + * Set the label used for items that sort before the first normal label, + * and that would not otherwise have an appropriate label. + * + * @param underflowLabel the new underflow label. + * @param status Error code, will be set with the reason if the operation fails. + * @return this + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &setUnderflowLabel(const UnicodeString &underflowLabel, UErrorCode &status); + + + /** + * Get the limit on the number of labels permitted in the index. + * The number does not include over, under and inflow labels. + * + * @return maxLabelCount maximum number of labels. + * @stable ICU 4.8 + */ + virtual int32_t getMaxLabelCount() const; + + /** + * Set a limit on the number of labels permitted in the index. + * The number does not include over, under and inflow labels. + * Currently, if the number is exceeded, then every + * nth item is removed to bring the count down. + * A more sophisticated mechanism may be available in the future. + * + * @param maxLabelCount the maximum number of labels. + * @param status error code + * @return This, for chaining + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &setMaxLabelCount(int32_t maxLabelCount, UErrorCode &status); + + + /** + * Add a record to the index. Each record will be associated with an index Bucket + * based on the record's name. The list of records for each bucket will be sorted + * based on the collation ordering of the names in the index's locale. + * Records with duplicate names are permitted; they will be kept in the order + * that they were added. + * + * @param name The display name for the Record. The Record will be placed in + * a bucket based on this name. + * @param data An optional pointer to user data associated with this + * item. When iterating the contents of a bucket, both the + * data pointer the name will be available for each Record. + * @param status Error code, will be set with the reason if the operation fails. + * @return This, for chaining. + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &addRecord(const UnicodeString &name, const void *data, UErrorCode &status); + + /** + * Remove all Records from the Index. The set of Buckets, which define the headings under + * which records are classified, is not altered. + * + * @param status Error code, will be set with the reason if the operation fails. + * @return This, for chaining. + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &clearRecords(UErrorCode &status); + + + /** Get the number of labels in this index. + * Note: may trigger lazy index construction. + * + * @param status Error code, will be set with the reason if the operation fails. + * @return The number of labels in this index, including any under, over or + * in-flow labels. + * @stable ICU 4.8 + */ + virtual int32_t getBucketCount(UErrorCode &status); + + + /** Get the total number of Records in this index, that is, the number + * of pairs added. + * + * @param status Error code, will be set with the reason if the operation fails. + * @return The number of records in this index, that is, the total number + * of (name, data) items added with addRecord(). + * @stable ICU 4.8 + */ + virtual int32_t getRecordCount(UErrorCode &status); + + + + /** + * Given the name of a record, return the zero-based index of the Bucket + * in which the item should appear. The name need not be in the index. + * A Record will not be added to the index by this function. + * Bucket numbers are zero-based, in Bucket iteration order. + * + * @param itemName The name whose bucket position in the index is to be determined. + * @param status Error code, will be set with the reason if the operation fails. + * @return The bucket number for this name. + * @stable ICU 4.8 + * + */ + virtual int32_t getBucketIndex(const UnicodeString &itemName, UErrorCode &status); + + + /** + * Get the zero based index of the current Bucket from an iteration + * over the Buckets of this index. Return -1 if no iteration is in process. + * @return the index of the current Bucket + * @stable ICU 4.8 + */ + virtual int32_t getBucketIndex() const; + + + /** + * Advance the iteration over the Buckets of this index. Return false if + * there are no more Buckets. + * + * @param status Error code, will be set with the reason if the operation fails. + * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while + * an enumeration of its contents are in process. + * + * @return true if success, false if at end of iteration + * @stable ICU 4.8 + */ + virtual UBool nextBucket(UErrorCode &status); + + /** + * Return the name of the Label of the current bucket from an iteration over the buckets. + * If the iteration is before the first Bucket (nextBucket() has not been called), + * or after the last, return an empty string. + * + * @return the bucket label. + * @stable ICU 4.8 + */ + virtual const UnicodeString &getBucketLabel() const; + + /** + * Return the type of the label for the current Bucket (selected by the + * iteration over Buckets.) + * + * @return the label type. + * @stable ICU 4.8 + */ + virtual UAlphabeticIndexLabelType getBucketLabelType() const; + + /** + * Get the number of Records in the current Bucket. + * If the current bucket iteration position is before the first label or after the + * last, return 0. + * + * @return the number of Records. + * @stable ICU 4.8 + */ + virtual int32_t getBucketRecordCount() const; + + + /** + * Reset the Bucket iteration for this index. The next call to nextBucket() + * will restart the iteration at the first label. + * + * @param status Error code, will be set with the reason if the operation fails. + * @return this, for chaining. + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &resetBucketIterator(UErrorCode &status); + + /** + * Advance to the next record in the current Bucket. + * When nextBucket() is called, Record iteration is reset to just before the + * first Record in the new Bucket. + * + * @param status Error code, will be set with the reason if the operation fails. + * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while + * an enumeration of its contents are in process. + * @return true if successful, false when the iteration advances past the last item. + * @stable ICU 4.8 + */ + virtual UBool nextRecord(UErrorCode &status); + + /** + * Get the name of the current Record. + * Return an empty string if the Record iteration position is before first + * or after the last. + * + * @return The name of the current index item. + * @stable ICU 4.8 + */ + virtual const UnicodeString &getRecordName() const; + + + /** + * Return the data pointer of the Record currently being iterated over. + * Return nullptr if the current iteration position before the first item in this Bucket, + * or after the last. + * + * @return The current Record's data pointer. + * @stable ICU 4.8 + */ + virtual const void *getRecordData() const; + + + /** + * Reset the Record iterator position to before the first Record in the current Bucket. + * + * @return This, for chaining. + * @stable ICU 4.8 + */ + virtual AlphabeticIndex &resetRecordIterator(); + +private: + /** + * No Copy constructor. + * @internal (private) + */ + AlphabeticIndex(const AlphabeticIndex &other) = delete; + + /** + * No assignment. + */ + AlphabeticIndex &operator =(const AlphabeticIndex & /*other*/) { return *this;} + + /** + * No Equality operators. + * @internal (private) + */ + virtual bool operator==(const AlphabeticIndex& other) const; + + /** + * Inequality operator. + * @internal (private) + */ + virtual bool operator!=(const AlphabeticIndex& other) const; + + // Common initialization, for use from all constructors. + void init(const Locale *locale, UErrorCode &status); + + /** + * This method is called to get the index exemplars. Normally these come from the locale directly, + * but if they aren't available, we have to synthesize them. + */ + void addIndexExemplars(const Locale &locale, UErrorCode &status); + /** + * Add Chinese index characters from the tailoring. + */ + UBool addChineseIndexCharacters(UErrorCode &errorCode); + + UVector *firstStringsInScript(UErrorCode &status); + + static UnicodeString separated(const UnicodeString &item); + + /** + * Determine the best labels to use. + * This is based on the exemplars, but we also process to make sure that they are unique, + * and sort differently, and that the overall list is small enough. + */ + void initLabels(UVector &indexCharacters, UErrorCode &errorCode) const; + BucketList *createBucketList(UErrorCode &errorCode) const; + void initBuckets(UErrorCode &errorCode); + void clearBuckets(); + void internalResetBucketIterator(); + +public: + + // The Record is declared public only to allow access from + // implementation code written in plain C. + // It is not intended for public use. + +#ifndef U_HIDE_INTERNAL_API + /** + * A (name, data) pair, to be sorted by name into one of the index buckets. + * The user data is not used by the index implementation. + * \cond + * @internal + */ + struct Record: public UMemory { + const UnicodeString name_; + const void *data_; + Record(const UnicodeString &name, const void *data); + ~Record(); + }; + /** \endcond */ +#endif /* U_HIDE_INTERNAL_API */ + +private: + + /** + * Holds all user records before they are distributed into buckets. + * Type of contents is (Record *) + * @internal (private) + */ + UVector *inputList_; + + int32_t labelsIterIndex_; // Index of next item to return. + int32_t itemsIterIndex_; + Bucket *currentBucket_; // While an iteration of the index in underway, + // point to the bucket for the current label. + // nullptr when no iteration underway. + + int32_t maxLabelCount_; // Limit on # of labels permitted in the index. + + UnicodeSet *initialLabels_; // Initial (unprocessed) set of Labels. Union + // of those explicitly set by the user plus + // those from locales. Raw values, before + // crunching into bucket labels. + + UVector *firstCharsInScripts_; // The first character from each script, + // in collation order. + + RuleBasedCollator *collator_; + RuleBasedCollator *collatorPrimaryOnly_; + + // Lazy evaluated: null means that we have not built yet. + BucketList *buckets_; + + UnicodeString inflowLabel_; + UnicodeString overflowLabel_; + UnicodeString underflowLabel_; + UnicodeString overflowComparisonString_; + + UnicodeString emptyString_; +}; + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_COLLATION + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/appendable.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/appendable.h new file mode 100644 index 0000000000000000000000000000000000000000..0e37f4562a58390f8d7553b2d019c6edea5ee026 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/appendable.h @@ -0,0 +1,239 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2011-2012, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: appendable.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010dec07 +* created by: Markus W. Scherer +*/ + +#ifndef __APPENDABLE_H__ +#define __APPENDABLE_H__ + +/** + * \file + * \brief C++ API: Appendable class: Sink for Unicode code points and 16-bit code units (char16_ts). + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN + +class UnicodeString; + +/** + * Base class for objects to which Unicode characters and strings can be appended. + * Combines elements of Java Appendable and ICU4C ByteSink. + * + * This class can be used in APIs where it does not matter whether the actual destination is + * a UnicodeString, a char16_t[] array, a UnicodeSet, or any other object + * that receives and processes characters and/or strings. + * + * Implementation classes must implement at least appendCodeUnit(char16_t). + * The base class provides default implementations for the other methods. + * + * The methods do not take UErrorCode parameters. + * If an error occurs (e.g., out-of-memory), + * in addition to returning false from failing operations, + * the implementation must prevent unexpected behavior (e.g., crashes) + * from further calls and should make the error condition available separately + * (e.g., store a UErrorCode, make/keep a UnicodeString bogus). + * @stable ICU 4.8 + */ +class U_COMMON_API Appendable : public UObject { +public: + /** + * Destructor. + * @stable ICU 4.8 + */ + ~Appendable(); + + /** + * Appends a 16-bit code unit. + * @param c code unit + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendCodeUnit(char16_t c) = 0; + + /** + * Appends a code point. + * The default implementation calls appendCodeUnit(char16_t) once or twice. + * @param c code point 0..0x10ffff + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendCodePoint(UChar32 c); + + /** + * Appends a string. + * The default implementation calls appendCodeUnit(char16_t) for each code unit. + * @param s string, must not be nullptr if length!=0 + * @param length string length, or -1 if NUL-terminated + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendString(const char16_t *s, int32_t length); + + /** + * Tells the object that the caller is going to append roughly + * appendCapacity char16_ts. A subclass might use this to pre-allocate + * a larger buffer if necessary. + * The default implementation does nothing. (It always returns true.) + * @param appendCapacity estimated number of char16_ts that will be appended + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool reserveAppendCapacity(int32_t appendCapacity); + + /** + * Returns a writable buffer for appending and writes the buffer's capacity to + * *resultCapacity. Guarantees *resultCapacity>=minCapacity. + * May return a pointer to the caller-owned scratch buffer which must have + * scratchCapacity>=minCapacity. + * The returned buffer is only valid until the next operation + * on this Appendable. + * + * After writing at most *resultCapacity char16_ts, call appendString() with the + * pointer returned from this function and the number of char16_ts written. + * Many appendString() implementations will avoid copying char16_ts if this function + * returned an internal buffer. + * + * Partial usage example: + * \code + * int32_t capacity; + * char16_t* buffer = app.getAppendBuffer(..., &capacity); + * ... Write n char16_ts into buffer, with n <= capacity. + * app.appendString(buffer, n); + * \endcode + * In many implementations, that call to append will avoid copying char16_ts. + * + * If the Appendable allocates or reallocates an internal buffer, it should use + * the desiredCapacityHint if appropriate. + * If a caller cannot provide a reasonable guess at the desired capacity, + * it should pass desiredCapacityHint=0. + * + * If a non-scratch buffer is returned, the caller may only pass + * a prefix to it to appendString(). + * That is, it is not correct to pass an interior pointer to appendString(). + * + * The default implementation always returns the scratch buffer. + * + * @param minCapacity required minimum capacity of the returned buffer; + * must be non-negative + * @param desiredCapacityHint desired capacity of the returned buffer; + * must be non-negative + * @param scratch default caller-owned buffer + * @param scratchCapacity capacity of the scratch buffer + * @param resultCapacity pointer to an integer which will be set to the + * capacity of the returned buffer + * @return a buffer with *resultCapacity>=minCapacity + * @stable ICU 4.8 + */ + virtual char16_t *getAppendBuffer(int32_t minCapacity, + int32_t desiredCapacityHint, + char16_t *scratch, int32_t scratchCapacity, + int32_t *resultCapacity); +}; + +/** + * An Appendable implementation which writes to a UnicodeString. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API UnicodeStringAppendable : public Appendable { +public: + /** + * Aliases the UnicodeString (keeps its reference) for writing. + * @param s The UnicodeString to which this Appendable will write. + * @stable ICU 4.8 + */ + explicit UnicodeStringAppendable(UnicodeString &s) : str(s) {} + + /** + * Destructor. + * @stable ICU 4.8 + */ + ~UnicodeStringAppendable(); + + /** + * Appends a 16-bit code unit to the string. + * @param c code unit + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendCodeUnit(char16_t c) override; + + /** + * Appends a code point to the string. + * @param c code point 0..0x10ffff + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendCodePoint(UChar32 c) override; + + /** + * Appends a string to the UnicodeString. + * @param s string, must not be nullptr if length!=0 + * @param length string length, or -1 if NUL-terminated + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool appendString(const char16_t *s, int32_t length) override; + + /** + * Tells the UnicodeString that the caller is going to append roughly + * appendCapacity char16_ts. + * @param appendCapacity estimated number of char16_ts that will be appended + * @return true if the operation succeeded + * @stable ICU 4.8 + */ + virtual UBool reserveAppendCapacity(int32_t appendCapacity) override; + + /** + * Returns a writable buffer for appending and writes the buffer's capacity to + * *resultCapacity. Guarantees *resultCapacity>=minCapacity. + * May return a pointer to the caller-owned scratch buffer which must have + * scratchCapacity>=minCapacity. + * The returned buffer is only valid until the next write operation + * on the UnicodeString. + * + * For details see Appendable::getAppendBuffer(). + * + * @param minCapacity required minimum capacity of the returned buffer; + * must be non-negative + * @param desiredCapacityHint desired capacity of the returned buffer; + * must be non-negative + * @param scratch default caller-owned buffer + * @param scratchCapacity capacity of the scratch buffer + * @param resultCapacity pointer to an integer which will be set to the + * capacity of the returned buffer + * @return a buffer with *resultCapacity>=minCapacity + * @stable ICU 4.8 + */ + virtual char16_t *getAppendBuffer(int32_t minCapacity, + int32_t desiredCapacityHint, + char16_t *scratch, int32_t scratchCapacity, + int32_t *resultCapacity) override; + +private: + UnicodeString &str; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __APPENDABLE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/basictz.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/basictz.h new file mode 100644 index 0000000000000000000000000000000000000000..4f8e4cacb1423c65e591dde09b434be41646a947 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/basictz.h @@ -0,0 +1,248 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2013, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +*/ +#ifndef BASICTZ_H +#define BASICTZ_H + +/** + * \file + * \brief C++ API: ICU TimeZone base class + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/timezone.h" +#include "unicode/tzrule.h" +#include "unicode/tztrans.h" + +U_NAMESPACE_BEGIN + +// forward declarations +class UVector; + +/** + * BasicTimeZone is an abstract class extending TimeZone. + * This class provides some additional methods to access time zone transitions and rules. + * All ICU TimeZone concrete subclasses extend this class. + * @stable ICU 3.8 + */ +class U_I18N_API BasicTimeZone: public TimeZone { +public: + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~BasicTimeZone(); + + /** + * Clones this object polymorphically. + * The caller owns the result and should delete it when done. + * @return clone, or nullptr if an error occurred + * @stable ICU 3.8 + */ + virtual BasicTimeZone* clone() const override = 0; + + /** + * Gets the first time zone transition after the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the first transition after the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0; + + /** + * Gets the most recent time zone transition before the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the most recent transition before the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0; + + /** + * Checks if the time zone has equivalent transitions in the time range. + * This method returns true when all of transition times, from/to standard + * offsets and DST savings used by this time zone match the other in the + * time range. + * @param tz The BasicTimeZone object to be compared with. + * @param start The start time of the evaluated time range (inclusive) + * @param end The end time of the evaluated time range (inclusive) + * @param ignoreDstAmount + * When true, any transitions with only daylight saving amount + * changes will be ignored, except either of them is zero. + * For example, a transition from rawoffset 3:00/dstsavings 1:00 + * to rawoffset 2:00/dstsavings 2:00 is excluded from the comparison, + * but a transition from rawoffset 2:00/dstsavings 1:00 to + * rawoffset 3:00/dstsavings 0:00 is included. + * @param ec Output param to filled in with a success or an error. + * @return true if the other time zone has the equivalent transitions in the + * time range. + * @stable ICU 3.8 + */ + virtual UBool hasEquivalentTransitions(const BasicTimeZone& tz, UDate start, UDate end, + UBool ignoreDstAmount, UErrorCode& ec) const; + + /** + * Returns the number of TimeZoneRules which represents time transitions, + * for this time zone, that is, all TimeZoneRules for this time zone except + * InitialTimeZoneRule. The return value range is 0 or any positive value. + * @param status Receives error status code. + * @return The number of TimeZoneRules representing time transitions. + * @stable ICU 3.8 + */ + virtual int32_t countTransitionRules(UErrorCode& status) const = 0; + + /** + * Gets the InitialTimeZoneRule and the set of TimeZoneRule + * which represent time transitions for this time zone. On successful return, + * the argument initial points to non-nullptr InitialTimeZoneRule and + * the array trsrules is filled with 0 or multiple TimeZoneRule + * instances up to the size specified by trscount. The results are referencing the + * rule instance held by this time zone instance. Therefore, after this time zone + * is destructed, they are no longer available. + * @param initial Receives the initial timezone rule + * @param trsrules Receives the timezone transition rules + * @param trscount On input, specify the size of the array 'transitions' receiving + * the timezone transition rules. On output, actual number of + * rules filled in the array will be set. + * @param status Receives error status code. + * @stable ICU 3.8 + */ + virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, + const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const = 0; + + /** + * Gets the set of time zone rules valid at the specified time. Some known external time zone + * implementations are not capable to handle historic time zone rule changes. Also some + * implementations can only handle certain type of rule definitions. + * If this time zone does not use any daylight saving time within about 1 year from the specified + * time, only the InitialTimeZone is returned. Otherwise, the rule for standard + * time and daylight saving time transitions are returned in addition to the + * InitialTimeZoneRule. The standard and daylight saving time transition rules are + * represented by AnnualTimeZoneRule with DateTimeRule::DOW for its date + * rule and DateTimeRule::WALL_TIME for its time rule. Because daylight saving time + * rule is changing time to time in many time zones and also mapping a transition time rule to + * different type is lossy transformation, the set of rules returned by this method may be valid + * for short period of time. + * The time zone rule objects returned by this method is owned by the caller, so the caller is + * responsible for deleting them after use. + * @param date The date used for extracting time zone rules. + * @param initial Receives the InitialTimeZone, always not nullptr. + * @param std Receives the AnnualTimeZoneRule for standard time transitions. + * When this time time zone does not observe daylight saving times around the + * specified date, nullptr is set. + * @param dst Receives the AnnualTimeZoneRule for daylight saving time + * transitions. When this time zone does not observer daylight saving times + * around the specified date, nullptr is set. + * @param status Receives error status code. + * @stable ICU 3.8 + */ + virtual void getSimpleRulesNear(UDate date, InitialTimeZoneRule*& initial, + AnnualTimeZoneRule*& std, AnnualTimeZoneRule*& dst, UErrorCode& status) const; + + /** + * Get time zone offsets from local wall time. + * @stable ICU 69 + */ + virtual void getOffsetFromLocal( + UDate date, UTimeZoneLocalOption nonExistingTimeOpt, + UTimeZoneLocalOption duplicatedTimeOpt, int32_t& rawOffset, + int32_t& dstOffset, UErrorCode& status) const; + + +#ifndef U_HIDE_INTERNAL_API + /** + * The time type option bit flags used by getOffsetFromLocal + * @internal + */ + enum { + kStandard = 0x01, + kDaylight = 0x03, + kFormer = 0x04, /* UCAL_TZ_LOCAL_FORMER */ + kLatter = 0x0C /* UCAL_TZ_LOCAL_LATTER */ + }; + + /** + * Get time zone offsets from local wall time. + * @internal + */ + void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt, + int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const; +#endif /* U_HIDE_INTERNAL_API */ + +protected: + +#ifndef U_HIDE_INTERNAL_API + /** + * A time type option bit mask used by getOffsetFromLocal. + * @internal + */ + static constexpr int32_t kStdDstMask = kDaylight; + /** + * A time type option bit mask used by getOffsetFromLocal. + * @internal + */ + static constexpr int32_t kFormerLatterMask = kLatter; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Default constructor. + * @stable ICU 3.8 + */ + BasicTimeZone(); + + /** + * Construct a timezone with a given ID. + * @param id a system time zone ID + * @stable ICU 3.8 + */ + BasicTimeZone(const UnicodeString &id); + + /** + * Copy constructor. + * @param source the object to be copied. + * @stable ICU 3.8 + */ + BasicTimeZone(const BasicTimeZone& source); + + /** + * Copy assignment. + * @stable ICU 3.8 + */ + BasicTimeZone& operator=(const BasicTimeZone&) = default; + + /** + * Gets the set of TimeZoneRule instances applicable to the specified time and after. + * @param start The start date used for extracting time zone rules + * @param initial Output parameter, receives the InitialTimeZone. + * Always not nullptr (except in case of error) + * @param transitionRules Output parameter, a UVector of transition rules. + * May be nullptr, if there are no transition rules. + * The caller owns the returned vector; the UVector owns the rules. + * @param status Receives error status code + */ + void getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, UVector*& transitionRules, + UErrorCode& status) const; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // BASICTZ_H + +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/brkiter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/brkiter.h new file mode 100644 index 0000000000000000000000000000000000000000..108652799e692fb6dfec1db7e88e94e77007c81c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/brkiter.h @@ -0,0 +1,670 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File brkiter.h +* +* Modification History: +* +* Date Name Description +* 02/18/97 aliu Added typedef for TextCount. Made DONE const. +* 05/07/97 aliu Fixed DLL declaration. +* 07/09/97 jfitz Renamed BreakIterator and interface synced with JDK +* 08/11/98 helena Sync-up JDK1.2. +* 01/13/2000 helena Added UErrorCode parameter to createXXXInstance methods. +******************************************************************************** +*/ + +#ifndef BRKITER_H +#define BRKITER_H + +#include "unicode/utypes.h" + +/** + * \file + * \brief C++ API: Break Iterator. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if UCONFIG_NO_BREAK_ITERATION + +U_NAMESPACE_BEGIN + +/* + * Allow the declaration of APIs with pointers to BreakIterator + * even when break iteration is removed from the build. + */ +class BreakIterator; + +U_NAMESPACE_END + +#else + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/chariter.h" +#include "unicode/locid.h" +#include "unicode/ubrk.h" +#include "unicode/strenum.h" +#include "unicode/utext.h" +#include "unicode/umisc.h" + +U_NAMESPACE_BEGIN + +/** + * The BreakIterator class implements methods for finding the location + * of boundaries in text. BreakIterator is an abstract base class. + * Instances of BreakIterator maintain a current position and scan over + * text returning the index of characters where boundaries occur. + *

+ * Line boundary analysis determines where a text string can be broken + * when line-wrapping. The mechanism correctly handles punctuation and + * hyphenated words. + *

+ * Sentence boundary analysis allows selection with correct + * interpretation of periods within numbers and abbreviations, and + * trailing punctuation marks such as quotation marks and parentheses. + *

+ * Word boundary analysis is used by search and replace functions, as + * well as within text editing applications that allow the user to + * select words with a double click. Word selection provides correct + * interpretation of punctuation marks within and following + * words. Characters that are not part of a word, such as symbols or + * punctuation marks, have word-breaks on both sides. + *

+ * Character boundary analysis allows users to interact with + * characters as they expect to, for example, when moving the cursor + * through a text string. Character boundary analysis provides correct + * navigation of through character strings, regardless of how the + * character is stored. For example, an accented character might be + * stored as a base character and a diacritical mark. What users + * consider to be a character can differ between languages. + *

+ * The text boundary positions are found according to the rules + * described in Unicode Standard Annex #29, Text Boundaries, and + * Unicode Standard Annex #14, Line Breaking Properties. These + * are available at http://www.unicode.org/reports/tr14/ and + * http://www.unicode.org/reports/tr29/. + *

+ * In addition to the C++ API defined in this header file, a + * plain C API with equivalent functionality is defined in the + * file ubrk.h + *

+ * Code snippets illustrating the use of the Break Iterator APIs + * are available in the ICU User Guide, + * https://unicode-org.github.io/icu/userguide/boundaryanalysis/ + * and in the sample program icu/source/samples/break/break.cpp + * + */ +class U_COMMON_API BreakIterator : public UObject { +public: + /** + * destructor + * @stable ICU 2.0 + */ + virtual ~BreakIterator(); + + /** + * Return true if another object is semantically equal to this + * one. The other object should be an instance of the same subclass of + * BreakIterator. Objects of different subclasses are considered + * unequal. + *

+ * Return true if this BreakIterator is at the same position in the + * same text, and is the same class and type (word, line, etc.) of + * BreakIterator, as the argument. Text is considered the same if + * it contains the same characters, it need not be the same + * object, and styles are not considered. + * @stable ICU 2.0 + */ + virtual bool operator==(const BreakIterator&) const = 0; + + /** + * Returns the complement of the result of operator== + * @param rhs The BreakIterator to be compared for inequality + * @return the complement of the result of operator== + * @stable ICU 2.0 + */ + bool operator!=(const BreakIterator& rhs) const { return !operator==(rhs); } + + /** + * Return a polymorphic copy of this object. This is an abstract + * method which subclasses implement. + * @stable ICU 2.0 + */ + virtual BreakIterator* clone() const = 0; + + /** + * Return a polymorphic class ID for this object. Different subclasses + * will return distinct unequal values. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Return a CharacterIterator over the text being analyzed. + * @stable ICU 2.0 + */ + virtual CharacterIterator& getText(void) const = 0; + + + /** + * Get a UText for the text being analyzed. + * The returned UText is a shallow clone of the UText used internally + * by the break iterator implementation. It can safely be used to + * access the text without impacting any break iterator operations, + * but the underlying text itself must not be altered. + * + * @param fillIn A UText to be filled in. If nullptr, a new UText will be + * allocated to hold the result. + * @param status receives any error codes. + * @return The current UText for this break iterator. If an input + * UText was provided, it will always be returned. + * @stable ICU 3.4 + */ + virtual UText *getUText(UText *fillIn, UErrorCode &status) const = 0; + + /** + * Change the text over which this operates. The text boundary is + * reset to the start. + * + * The BreakIterator will retain a reference to the supplied string. + * The caller must not modify or delete the text while the BreakIterator + * retains the reference. + * + * @param text The UnicodeString used to change the text. + * @stable ICU 2.0 + */ + virtual void setText(const UnicodeString &text) = 0; + + /** + * Reset the break iterator to operate over the text represented by + * the UText. The iterator position is reset to the start. + * + * This function makes a shallow clone of the supplied UText. This means + * that the caller is free to immediately close or otherwise reuse the + * Utext that was passed as a parameter, but that the underlying text itself + * must not be altered while being referenced by the break iterator. + * + * All index positions returned by break iterator functions are + * native indices from the UText. For example, when breaking UTF-8 + * encoded text, the break positions returned by next(), previous(), etc. + * will be UTF-8 string indices, not UTF-16 positions. + * + * @param text The UText used to change the text. + * @param status receives any error codes. + * @stable ICU 3.4 + */ + virtual void setText(UText *text, UErrorCode &status) = 0; + + /** + * Change the text over which this operates. The text boundary is + * reset to the start. + * Note that setText(UText *) provides similar functionality to this function, + * and is more efficient. + * @param it The CharacterIterator used to change the text. + * @stable ICU 2.0 + */ + virtual void adoptText(CharacterIterator* it) = 0; + + enum { + /** + * DONE is returned by previous() and next() after all valid + * boundaries have been returned. + * @stable ICU 2.0 + */ + DONE = (int32_t)-1 + }; + + /** + * Sets the current iteration position to the beginning of the text, position zero. + * @return The offset of the beginning of the text, zero. + * @stable ICU 2.0 + */ + virtual int32_t first(void) = 0; + + /** + * Set the iterator position to the index immediately BEYOND the last character in the text being scanned. + * @return The index immediately BEYOND the last character in the text being scanned. + * @stable ICU 2.0 + */ + virtual int32_t last(void) = 0; + + /** + * Set the iterator position to the boundary preceding the current boundary. + * @return The character index of the previous text boundary or DONE if all + * boundaries have been returned. + * @stable ICU 2.0 + */ + virtual int32_t previous(void) = 0; + + /** + * Advance the iterator to the boundary following the current boundary. + * @return The character index of the next text boundary or DONE if all + * boundaries have been returned. + * @stable ICU 2.0 + */ + virtual int32_t next(void) = 0; + + /** + * Return character index of the current iterator position within the text. + * @return The boundary most recently returned. + * @stable ICU 2.0 + */ + virtual int32_t current(void) const = 0; + + /** + * Advance the iterator to the first boundary following the specified offset. + * The value returned is always greater than the offset or + * the value BreakIterator.DONE + * @param offset the offset to begin scanning. + * @return The first boundary after the specified offset. + * @stable ICU 2.0 + */ + virtual int32_t following(int32_t offset) = 0; + + /** + * Set the iterator position to the first boundary preceding the specified offset. + * The value returned is always smaller than the offset or + * the value BreakIterator.DONE + * @param offset the offset to begin scanning. + * @return The first boundary before the specified offset. + * @stable ICU 2.0 + */ + virtual int32_t preceding(int32_t offset) = 0; + + /** + * Return true if the specified position is a boundary position. + * As a side effect, the current position of the iterator is set + * to the first boundary position at or following the specified offset. + * @param offset the offset to check. + * @return True if "offset" is a boundary position. + * @stable ICU 2.0 + */ + virtual UBool isBoundary(int32_t offset) = 0; + + /** + * Set the iterator position to the nth boundary from the current boundary + * @param n the number of boundaries to move by. A value of 0 + * does nothing. Negative values move to previous boundaries + * and positive values move to later boundaries. + * @return The new iterator position, or + * DONE if there are fewer than |n| boundaries in the specified direction. + * @stable ICU 2.0 + */ + virtual int32_t next(int32_t n) = 0; + + /** + * For RuleBasedBreakIterators, return the status tag from the break rule + * that determined the boundary at the current iteration position. + *

+ * For break iterator types that do not support a rule status, + * a default value of 0 is returned. + *

+ * @return the status from the break rule that determined the boundary at + * the current iteration position. + * @see RuleBaseBreakIterator::getRuleStatus() + * @see UWordBreak + * @stable ICU 52 + */ + virtual int32_t getRuleStatus() const; + + /** + * For RuleBasedBreakIterators, get the status (tag) values from the break rule(s) + * that determined the boundary at the current iteration position. + *

+ * For break iterator types that do not support rule status, + * no values are returned. + *

+ * The returned status value(s) are stored into an array provided by the caller. + * The values are stored in sorted (ascending) order. + * If the capacity of the output array is insufficient to hold the data, + * the output will be truncated to the available length, and a + * U_BUFFER_OVERFLOW_ERROR will be signaled. + *

+ * @see RuleBaseBreakIterator::getRuleStatusVec + * + * @param fillInVec an array to be filled in with the status values. + * @param capacity the length of the supplied vector. A length of zero causes + * the function to return the number of status values, in the + * normal way, without attempting to store any values. + * @param status receives error codes. + * @return The number of rule status values from rules that determined + * the boundary at the current iteration position. + * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value + * is the total number of status values that were available, + * not the reduced number that were actually returned. + * @see getRuleStatus + * @stable ICU 52 + */ + virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status); + + /** + * Create BreakIterator for word-breaks using the given locale. + * Returns an instance of a BreakIterator implementing word breaks. + * WordBreak is useful for word selection (ex. double click) + * @param where the locale. + * @param status the error code + * @return A BreakIterator for word-breaks. The UErrorCode& status + * parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_WARNING indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * @stable ICU 2.0 + */ + static BreakIterator* U_EXPORT2 + createWordInstance(const Locale& where, UErrorCode& status); + + /** + * Create BreakIterator for line-breaks using specified locale. + * Returns an instance of a BreakIterator implementing line breaks. Line + * breaks are logically possible line breaks, actual line breaks are + * usually determined based on display width. + * LineBreak is useful for word wrapping text. + * @param where the locale. + * @param status The error code. + * @return A BreakIterator for line-breaks. The UErrorCode& status + * parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_WARNING indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * @stable ICU 2.0 + */ + static BreakIterator* U_EXPORT2 + createLineInstance(const Locale& where, UErrorCode& status); + + /** + * Create BreakIterator for character-breaks using specified locale + * Returns an instance of a BreakIterator implementing character breaks. + * Character breaks are boundaries of combining character sequences. + * @param where the locale. + * @param status The error code. + * @return A BreakIterator for character-breaks. The UErrorCode& status + * parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_WARNING indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * @stable ICU 2.0 + */ + static BreakIterator* U_EXPORT2 + createCharacterInstance(const Locale& where, UErrorCode& status); + + /** + * Create BreakIterator for sentence-breaks using specified locale + * Returns an instance of a BreakIterator implementing sentence breaks. + * @param where the locale. + * @param status The error code. + * @return A BreakIterator for sentence-breaks. The UErrorCode& status + * parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_WARNING indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * @stable ICU 2.0 + */ + static BreakIterator* U_EXPORT2 + createSentenceInstance(const Locale& where, UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Create BreakIterator for title-casing breaks using the specified locale + * Returns an instance of a BreakIterator implementing title breaks. + * The iterator returned locates title boundaries as described for + * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration, + * please use a word boundary iterator. See {@link #createWordInstance }. + * + * @param where the locale. + * @param status The error code. + * @return A BreakIterator for title-breaks. The UErrorCode& status + * parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_WARNING indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * @deprecated ICU 64 Use createWordInstance instead. + */ + static BreakIterator* U_EXPORT2 + createTitleInstance(const Locale& where, UErrorCode& status); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Get the set of Locales for which TextBoundaries are installed. + *

Note: this will not return locales added through the register + * call. To see the registered locales too, use the getAvailableLocales + * function that returns a StringEnumeration object

+ * @param count the output parameter of number of elements in the locale list + * @return available locales + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + /** + * Get name of the object for the desired Locale, in the desired language. + * @param objectLocale must be from getAvailableLocales. + * @param displayLocale specifies the desired locale for output. + * @param name the fill-in parameter of the return value + * Uses best match. + * @return user-displayable name + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, + const Locale& displayLocale, + UnicodeString& name); + + /** + * Get name of the object for the desired Locale, in the language of the + * default locale. + * @param objectLocale must be from getMatchingLocales + * @param name the fill-in parameter of the return value + * @return user-displayable name + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, + UnicodeString& name); + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Deprecated functionality. Use clone() instead. + * + * Thread safe client-buffer-based cloning operation + * Do NOT call delete on a safeclone, since 'new' is not used to create it. + * @param stackBuffer user allocated space for the new clone. If nullptr new memory will be allocated. + * If buffer is not large enough, new memory will be allocated. + * @param BufferSize reference to size of allocated space. + * If BufferSize == 0, a sufficient size for use in cloning will + * be returned ('pre-flighting') + * If BufferSize is not enough for a stack-based safe clone, + * new memory will be allocated. + * @param status to indicate whether the operation went on smoothly or there were errors + * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were + * necessary. + * @return pointer to the new clone + * + * @deprecated ICU 52. Use clone() instead. + */ + virtual BreakIterator * createBufferClone(void *stackBuffer, + int32_t &BufferSize, + UErrorCode &status) = 0; +#endif // U_FORCE_HIDE_DEPRECATED_API + +#ifndef U_HIDE_DEPRECATED_API + + /** + * Determine whether the BreakIterator was created in user memory by + * createBufferClone(), and thus should not be deleted. Such objects + * must be closed by an explicit call to the destructor (not delete). + * @deprecated ICU 52. Always delete the BreakIterator. + */ + inline UBool isBufferClone(void); + +#endif /* U_HIDE_DEPRECATED_API */ + +#if !UCONFIG_NO_SERVICE + /** + * Register a new break iterator of the indicated kind, to use in the given locale. + * The break iterator will be adopted. Clones of the iterator will be returned + * if a request for a break iterator of the given kind matches or falls back to + * this locale. + * Because ICU may choose to cache BreakIterators internally, this must + * be called at application startup, prior to any calls to + * BreakIterator::createXXXInstance to avoid undefined behavior. + * @param toAdopt the BreakIterator instance to be adopted + * @param locale the Locale for which this instance is to be registered + * @param kind the type of iterator for which this instance is to be registered + * @param status the in/out status code, no special meanings are assigned + * @return a registry key that can be used to unregister this instance + * @stable ICU 2.4 + */ + static URegistryKey U_EXPORT2 registerInstance(BreakIterator* toAdopt, + const Locale& locale, + UBreakIteratorType kind, + UErrorCode& status); + + /** + * Unregister a previously-registered BreakIterator using the key returned from the + * register call. Key becomes invalid after a successful call and should not be used again. + * The BreakIterator corresponding to the key will be deleted. + * Because ICU may choose to cache BreakIterators internally, this should + * be called during application shutdown, after all calls to + * BreakIterator::createXXXInstance to avoid undefined behavior. + * @param key the registry key returned by a previous call to registerInstance + * @param status the in/out status code, no special meanings are assigned + * @return true if the iterator for the key was successfully unregistered + * @stable ICU 2.4 + */ + static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); + + /** + * Return a StringEnumeration over the locales available at the time of the call, + * including registered locales. + * @return a StringEnumeration over the locales available at the time of the call + * @stable ICU 2.4 + */ + static StringEnumeration* U_EXPORT2 getAvailableLocales(void); +#endif + + /** + * Returns the locale for this break iterator. Two flavors are available: valid and + * actual locale. + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; + +#ifndef U_HIDE_INTERNAL_API + /** Get the locale for this break iterator object. You can choose between valid and actual locale. + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale + * @internal + */ + const char *getLocaleID(ULocDataLocaleType type, UErrorCode& status) const; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Set the subject text string upon which the break iterator is operating + * without changing any other aspect of the matching state. + * The new and previous text strings must have the same content. + * + * This function is intended for use in environments where ICU is operating on + * strings that may move around in memory. It provides a mechanism for notifying + * ICU that the string has been relocated, and providing a new UText to access the + * string in its new position. + * + * Note that the break iterator implementation never copies the underlying text + * of a string being processed, but always operates directly on the original text + * provided by the user. Refreshing simply drops the references to the old text + * and replaces them with references to the new. + * + * Caution: this function is normally used only by very specialized, + * system-level code. One example use case is with garbage collection that moves + * the text in memory. + * + * @param input The new (moved) text string. + * @param status Receives errors detected by this function. + * @return *this + * + * @stable ICU 49 + */ + virtual BreakIterator &refreshInputText(UText *input, UErrorCode &status) = 0; + + private: + static BreakIterator* buildInstance(const Locale& loc, const char *type, UErrorCode& status); + static BreakIterator* createInstance(const Locale& loc, int32_t kind, UErrorCode& status); + static BreakIterator* makeInstance(const Locale& loc, int32_t kind, UErrorCode& status); + + friend class ICUBreakIteratorFactory; + friend class ICUBreakIteratorService; + +protected: + // Do not enclose protected default/copy constructors with #ifndef U_HIDE_INTERNAL_API + // or else the compiler will create a public ones. + /** @internal */ + BreakIterator(); + /** @internal */ + BreakIterator (const BreakIterator &other); +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + BreakIterator (const Locale& valid, const Locale &actual); + /** @internal. Assignment Operator, used by RuleBasedBreakIterator. */ + BreakIterator &operator = (const BreakIterator &other); +#endif /* U_HIDE_INTERNAL_API */ + +private: + + /** @internal (private) */ + char actualLocale[ULOC_FULLNAME_CAPACITY]; + char validLocale[ULOC_FULLNAME_CAPACITY]; +}; + +#ifndef U_HIDE_DEPRECATED_API + +inline UBool BreakIterator::isBufferClone() +{ + return false; +} + +#endif /* U_HIDE_DEPRECATED_API */ + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // BRKITER_H +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestream.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestream.h new file mode 100644 index 0000000000000000000000000000000000000000..997746e428040ff138be81b5974699a4248296a1 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestream.h @@ -0,0 +1,307 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +// Copyright (C) 2009-2012, International Business Machines +// Corporation and others. All Rights Reserved. +// +// Copyright 2007 Google Inc. All Rights Reserved. +// Author: sanjay@google.com (Sanjay Ghemawat) +// +// Abstract interface that consumes a sequence of bytes (ByteSink). +// +// Used so that we can write a single piece of code that can operate +// on a variety of output string types. +// +// Various implementations of this interface are provided: +// ByteSink: +// CheckedArrayByteSink Write to a flat array, with bounds checking +// StringByteSink Write to an STL string + +// This code is a contribution of Google code, and the style used here is +// a compromise between the original Google code and the ICU coding guidelines. +// For example, data types are ICU-ified (size_t,int->int32_t), +// and API comments doxygen-ified, but function names and behavior are +// as in the original, if possible. +// Assertion-style error handling, not available in ICU, was changed to +// parameter "pinning" similar to UnicodeString. +// +// In addition, this is only a partial port of the original Google code, +// limited to what was needed so far. The (nearly) complete original code +// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib +// (see ICU ticket 6765, r25517). + +#ifndef __BYTESTREAM_H__ +#define __BYTESTREAM_H__ + +/** + * \file + * \brief C++ API: Interface for writing bytes, and implementation classes. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/std_string.h" + +U_NAMESPACE_BEGIN + +/** + * A ByteSink can be filled with bytes. + * @stable ICU 4.2 + */ +class U_COMMON_API ByteSink : public UMemory { +public: + /** + * Default constructor. + * @stable ICU 4.2 + */ + ByteSink() { } + /** + * Virtual destructor. + * @stable ICU 4.2 + */ + virtual ~ByteSink(); + + /** + * Append "bytes[0,n-1]" to this. + * @param bytes the pointer to the bytes + * @param n the number of bytes; must be non-negative + * @stable ICU 4.2 + */ + virtual void Append(const char* bytes, int32_t n) = 0; + + /** + * Appends n bytes to this. Same as Append(). + * Call AppendU8() with u8"string literals" which are const char * in C++11 + * but const char8_t * in C++20. + * If the compiler does support char8_t as a distinct type, + * then an AppendU8() overload for that is defined and will be chosen. + * + * @param bytes the pointer to the bytes + * @param n the number of bytes; must be non-negative + * @stable ICU 67 + */ + inline void AppendU8(const char* bytes, int32_t n) { + Append(bytes, n); + } + +#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN) + /** + * Appends n bytes to this. Same as Append() but for a const char8_t * pointer. + * Call AppendU8() with u8"string literals" which are const char * in C++11 + * but const char8_t * in C++20. + * If the compiler does support char8_t as a distinct type, + * then this AppendU8() overload for that is defined and will be chosen. + * + * @param bytes the pointer to the bytes + * @param n the number of bytes; must be non-negative + * @stable ICU 67 + */ + inline void AppendU8(const char8_t* bytes, int32_t n) { + Append(reinterpret_cast(bytes), n); + } +#endif + + /** + * Returns a writable buffer for appending and writes the buffer's capacity to + * *result_capacity. Guarantees *result_capacity>=min_capacity. + * May return a pointer to the caller-owned scratch buffer which must have + * scratch_capacity>=min_capacity. + * The returned buffer is only valid until the next operation + * on this ByteSink. + * + * After writing at most *result_capacity bytes, call Append() with the + * pointer returned from this function and the number of bytes written. + * Many Append() implementations will avoid copying bytes if this function + * returned an internal buffer. + * + * Partial usage example: + * int32_t capacity; + * char* buffer = sink->GetAppendBuffer(..., &capacity); + * ... Write n bytes into buffer, with n <= capacity. + * sink->Append(buffer, n); + * In many implementations, that call to Append will avoid copying bytes. + * + * If the ByteSink allocates or reallocates an internal buffer, it should use + * the desired_capacity_hint if appropriate. + * If a caller cannot provide a reasonable guess at the desired capacity, + * it should pass desired_capacity_hint=0. + * + * If a non-scratch buffer is returned, the caller may only pass + * a prefix to it to Append(). + * That is, it is not correct to pass an interior pointer to Append(). + * + * The default implementation always returns the scratch buffer. + * + * @param min_capacity required minimum capacity of the returned buffer; + * must be non-negative + * @param desired_capacity_hint desired capacity of the returned buffer; + * must be non-negative + * @param scratch default caller-owned buffer + * @param scratch_capacity capacity of the scratch buffer + * @param result_capacity pointer to an integer which will be set to the + * capacity of the returned buffer + * @return a buffer with *result_capacity>=min_capacity + * @stable ICU 4.2 + */ + virtual char* GetAppendBuffer(int32_t min_capacity, + int32_t desired_capacity_hint, + char* scratch, int32_t scratch_capacity, + int32_t* result_capacity); + + /** + * Flush internal buffers. + * Some byte sinks use internal buffers or provide buffering + * and require calling Flush() at the end of the stream. + * The ByteSink should be ready for further Append() calls after Flush(). + * The default implementation of Flush() does nothing. + * @stable ICU 4.2 + */ + virtual void Flush(); + +private: + ByteSink(const ByteSink &) = delete; + ByteSink &operator=(const ByteSink &) = delete; +}; + +// ------------------------------------------------------------- +// Some standard implementations + +/** + * Implementation of ByteSink that writes to a flat byte array, + * with bounds-checking: + * This sink will not write more than capacity bytes to outbuf. + * If more than capacity bytes are Append()ed, then excess bytes are ignored, + * and Overflowed() will return true. + * Overflow does not cause a runtime error. + * @stable ICU 4.2 + */ +class U_COMMON_API CheckedArrayByteSink : public ByteSink { +public: + /** + * Constructs a ByteSink that will write to outbuf[0..capacity-1]. + * @param outbuf buffer to write to + * @param capacity size of the buffer + * @stable ICU 4.2 + */ + CheckedArrayByteSink(char* outbuf, int32_t capacity); + /** + * Destructor. + * @stable ICU 4.2 + */ + virtual ~CheckedArrayByteSink(); + /** + * Returns the sink to its original state, without modifying the buffer. + * Useful for reusing both the buffer and the sink for multiple streams. + * Resets the state to NumberOfBytesWritten()=NumberOfBytesAppended()=0 + * and Overflowed()=false. + * @return *this + * @stable ICU 4.6 + */ + virtual CheckedArrayByteSink& Reset(); + /** + * Append "bytes[0,n-1]" to this. + * @param bytes the pointer to the bytes + * @param n the number of bytes; must be non-negative + * @stable ICU 4.2 + */ + virtual void Append(const char* bytes, int32_t n) override; + /** + * Returns a writable buffer for appending and writes the buffer's capacity to + * *result_capacity. For details see the base class documentation. + * @param min_capacity required minimum capacity of the returned buffer; + * must be non-negative + * @param desired_capacity_hint desired capacity of the returned buffer; + * must be non-negative + * @param scratch default caller-owned buffer + * @param scratch_capacity capacity of the scratch buffer + * @param result_capacity pointer to an integer which will be set to the + * capacity of the returned buffer + * @return a buffer with *result_capacity>=min_capacity + * @stable ICU 4.2 + */ + virtual char* GetAppendBuffer(int32_t min_capacity, + int32_t desired_capacity_hint, + char* scratch, int32_t scratch_capacity, + int32_t* result_capacity) override; + /** + * Returns the number of bytes actually written to the sink. + * @return number of bytes written to the buffer + * @stable ICU 4.2 + */ + int32_t NumberOfBytesWritten() const { return size_; } + /** + * Returns true if any bytes were discarded, i.e., if there was an + * attempt to write more than 'capacity' bytes. + * @return true if more than 'capacity' bytes were Append()ed + * @stable ICU 4.2 + */ + UBool Overflowed() const { return overflowed_; } + /** + * Returns the number of bytes appended to the sink. + * If Overflowed() then NumberOfBytesAppended()>NumberOfBytesWritten() + * else they return the same number. + * @return number of bytes written to the buffer + * @stable ICU 4.6 + */ + int32_t NumberOfBytesAppended() const { return appended_; } +private: + char* outbuf_; + const int32_t capacity_; + int32_t size_; + int32_t appended_; + UBool overflowed_; + + CheckedArrayByteSink() = delete; + CheckedArrayByteSink(const CheckedArrayByteSink &) = delete; + CheckedArrayByteSink &operator=(const CheckedArrayByteSink &) = delete; +}; + +/** + * Implementation of ByteSink that writes to a "string". + * The StringClass is usually instantiated with a std::string. + * @stable ICU 4.2 + */ +template +class StringByteSink : public ByteSink { + public: + /** + * Constructs a ByteSink that will append bytes to the dest string. + * @param dest pointer to string object to append to + * @stable ICU 4.2 + */ + StringByteSink(StringClass* dest) : dest_(dest) { } + /** + * Constructs a ByteSink that reserves append capacity and will append bytes to the dest string. + * + * @param dest pointer to string object to append to + * @param initialAppendCapacity capacity beyond dest->length() to be reserve()d + * @stable ICU 60 + */ + StringByteSink(StringClass* dest, int32_t initialAppendCapacity) : dest_(dest) { + if (initialAppendCapacity > 0 && + (uint32_t)initialAppendCapacity > (dest->capacity() - dest->length())) { + dest->reserve(dest->length() + initialAppendCapacity); + } + } + /** + * Append "bytes[0,n-1]" to this. + * @param data the pointer to the bytes + * @param n the number of bytes; must be non-negative + * @stable ICU 4.2 + */ + virtual void Append(const char* data, int32_t n) override { dest_->append(data, n); } + private: + StringClass* dest_; + + StringByteSink() = delete; + StringByteSink(const StringByteSink &) = delete; + StringByteSink &operator=(const StringByteSink &) = delete; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __BYTESTREAM_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestrie.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestrie.h new file mode 100644 index 0000000000000000000000000000000000000000..1719a6bb83edc97987308e45a0a9c1be98c6f96f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestrie.h @@ -0,0 +1,568 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2012, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: bytestrie.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010sep25 +* created by: Markus W. Scherer +*/ + +#ifndef __BYTESTRIE_H__ +#define __BYTESTRIE_H__ + +/** + * \file + * \brief C++ API: Trie for mapping byte sequences to integer values. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/stringpiece.h" +#include "unicode/uobject.h" +#include "unicode/ustringtrie.h" + +class BytesTrieTest; + +U_NAMESPACE_BEGIN + +class ByteSink; +class BytesTrieBuilder; +class CharString; +class UVector32; + +/** + * Light-weight, non-const reader class for a BytesTrie. + * Traverses a byte-serialized data structure with minimal state, + * for mapping byte sequences to non-negative integer values. + * + * This class owns the serialized trie data only if it was constructed by + * the builder's build() method. + * The public constructor and the copy constructor only alias the data (only copy the pointer). + * There is no assignment operator. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API BytesTrie : public UMemory { +public: + /** + * Constructs a BytesTrie reader instance. + * + * The trieBytes must contain a copy of a byte sequence from the BytesTrieBuilder, + * starting with the first byte of that sequence. + * The BytesTrie object will not read more bytes than + * the BytesTrieBuilder generated in the corresponding build() call. + * + * The array is not copied/cloned and must not be modified while + * the BytesTrie object is in use. + * + * @param trieBytes The byte array that contains the serialized trie. + * @stable ICU 4.8 + */ + BytesTrie(const void *trieBytes) + : ownedArray_(nullptr), bytes_(static_cast(trieBytes)), + pos_(bytes_), remainingMatchLength_(-1) {} + + /** + * Destructor. + * @stable ICU 4.8 + */ + ~BytesTrie(); + + /** + * Copy constructor, copies the other trie reader object and its state, + * but not the byte array which will be shared. (Shallow copy.) + * @param other Another BytesTrie object. + * @stable ICU 4.8 + */ + BytesTrie(const BytesTrie &other) + : ownedArray_(nullptr), bytes_(other.bytes_), + pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {} + + /** + * Resets this trie to its initial state. + * @return *this + * @stable ICU 4.8 + */ + BytesTrie &reset() { + pos_=bytes_; + remainingMatchLength_=-1; + return *this; + } + + /** + * Returns the state of this trie as a 64-bit integer. + * The state value is never 0. + * + * @return opaque state value + * @see resetToState64 + * @stable ICU 65 + */ + uint64_t getState64() const { + return (static_cast(remainingMatchLength_ + 2) << kState64RemainingShift) | + (uint64_t)(pos_ - bytes_); + } + + /** + * Resets this trie to the saved state. + * Unlike resetToState(State), the 64-bit state value + * must be from getState64() from the same trie object or + * from one initialized the exact same way. + * Because of no validation, this method is faster. + * + * @param state The opaque trie state value from getState64(). + * @return *this + * @see getState64 + * @see resetToState + * @see reset + * @stable ICU 65 + */ + BytesTrie &resetToState64(uint64_t state) { + remainingMatchLength_ = static_cast(state >> kState64RemainingShift) - 2; + pos_ = bytes_ + (state & kState64PosMask); + return *this; + } + + /** + * BytesTrie state object, for saving a trie's current state + * and resetting the trie back to this state later. + * @stable ICU 4.8 + */ + class State : public UMemory { + public: + /** + * Constructs an empty State. + * @stable ICU 4.8 + */ + State() { bytes=nullptr; } + private: + friend class BytesTrie; + + const uint8_t *bytes; + const uint8_t *pos; + int32_t remainingMatchLength; + }; + + /** + * Saves the state of this trie. + * @param state The State object to hold the trie's state. + * @return *this + * @see resetToState + * @stable ICU 4.8 + */ + const BytesTrie &saveState(State &state) const { + state.bytes=bytes_; + state.pos=pos_; + state.remainingMatchLength=remainingMatchLength_; + return *this; + } + + /** + * Resets this trie to the saved state. + * If the state object contains no state, or the state of a different trie, + * then this trie remains unchanged. + * @param state The State object which holds a saved trie state. + * @return *this + * @see saveState + * @see reset + * @stable ICU 4.8 + */ + BytesTrie &resetToState(const State &state) { + if(bytes_==state.bytes && bytes_!=nullptr) { + pos_=state.pos; + remainingMatchLength_=state.remainingMatchLength; + } + return *this; + } + + /** + * Determines whether the byte sequence so far matches, whether it has a value, + * and whether another input byte can continue a matching byte sequence. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult current() const; + + /** + * Traverses the trie from the initial state for this input byte. + * Equivalent to reset().next(inByte). + * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff. + * Values below -0x100 and above 0xff will never match. + * @return The match/value Result. + * @stable ICU 4.8 + */ + inline UStringTrieResult first(int32_t inByte) { + remainingMatchLength_=-1; + if(inByte<0) { + inByte+=0x100; + } + return nextImpl(bytes_, inByte); + } + + /** + * Traverses the trie from the current state for this input byte. + * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff. + * Values below -0x100 and above 0xff will never match. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult next(int32_t inByte); + + /** + * Traverses the trie from the current state for this byte sequence. + * Equivalent to + * \code + * Result result=current(); + * for(each c in s) + * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH; + * result=next(c); + * return result; + * \endcode + * @param s A string or byte sequence. Can be nullptr if length is 0. + * @param length The length of the byte sequence. Can be -1 if NUL-terminated. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult next(const char *s, int32_t length); + + /** + * Returns a matching byte sequence's value if called immediately after + * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE. + * getValue() can be called multiple times. + * + * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE! + * @return The value for the byte sequence so far. + * @stable ICU 4.8 + */ + inline int32_t getValue() const { + const uint8_t *pos=pos_; + int32_t leadByte=*pos++; + // U_ASSERT(leadByte>=kMinValueLead); + return readValue(pos, leadByte>>1); + } + + /** + * Determines whether all byte sequences reachable from the current state + * map to the same value. + * @param uniqueValue Receives the unique value, if this function returns true. + * (output-only) + * @return true if all byte sequences reachable from the current state + * map to the same value. + * @stable ICU 4.8 + */ + inline UBool hasUniqueValue(int32_t &uniqueValue) const { + const uint8_t *pos=pos_; + // Skip the rest of a pending linear-match node. + return pos!=nullptr && findUniqueValue(pos+remainingMatchLength_+1, false, uniqueValue); + } + + /** + * Finds each byte which continues the byte sequence from the current state. + * That is, each byte b for which it would be next(b)!=USTRINGTRIE_NO_MATCH now. + * @param out Each next byte is appended to this object. + * (Only uses the out.Append(s, length) method.) + * @return the number of bytes which continue the byte sequence from here + * @stable ICU 4.8 + */ + int32_t getNextBytes(ByteSink &out) const; + + /** + * Iterator for all of the (byte sequence, value) pairs in a BytesTrie. + * @stable ICU 4.8 + */ + class U_COMMON_API Iterator : public UMemory { + public: + /** + * Iterates from the root of a byte-serialized BytesTrie. + * @param trieBytes The trie bytes. + * @param maxStringLength If 0, the iterator returns full strings/byte sequences. + * Otherwise, the iterator returns strings with this maximum length. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode); + + /** + * Iterates from the current state of the specified BytesTrie. + * @param trie The trie whose state will be copied for iteration. + * @param maxStringLength If 0, the iterator returns full strings/byte sequences. + * Otherwise, the iterator returns strings with this maximum length. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode); + + /** + * Destructor. + * @stable ICU 4.8 + */ + ~Iterator(); + + /** + * Resets this iterator to its initial state. + * @return *this + * @stable ICU 4.8 + */ + Iterator &reset(); + + /** + * @return true if there are more elements. + * @stable ICU 4.8 + */ + UBool hasNext() const; + + /** + * Finds the next (byte sequence, value) pair if there is one. + * + * If the byte sequence is truncated to the maximum length and does not + * have a real value, then the value is set to -1. + * In this case, this "not a real value" is indistinguishable from + * a real value of -1. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if there is another element. + * @stable ICU 4.8 + */ + UBool next(UErrorCode &errorCode); + + /** + * @return The NUL-terminated byte sequence for the last successful next(). + * @stable ICU 4.8 + */ + StringPiece getString() const; + /** + * @return The value for the last successful next(). + * @stable ICU 4.8 + */ + int32_t getValue() const { return value_; } + + private: + UBool truncateAndStop(); + + const uint8_t *branchNext(const uint8_t *pos, int32_t length, UErrorCode &errorCode); + + const uint8_t *bytes_; + const uint8_t *pos_; + const uint8_t *initialPos_; + int32_t remainingMatchLength_; + int32_t initialRemainingMatchLength_; + + CharString *str_; + int32_t maxLength_; + int32_t value_; + + // The stack stores pairs of integers for backtracking to another + // outbound edge of a branch node. + // The first integer is an offset from bytes_. + // The second integer has the str_->length() from before the node in bits 15..0, + // and the remaining branch length in bits 24..16. (Bits 31..25 are unused.) + // (We could store the remaining branch length minus 1 in bits 23..16 and not use bits 31..24, + // but the code looks more confusing that way.) + UVector32 *stack_; + }; + +private: + friend class BytesTrieBuilder; + friend class ::BytesTrieTest; + + /** + * Constructs a BytesTrie reader instance. + * Unlike the public constructor which just aliases an array, + * this constructor adopts the builder's array. + * This constructor is only called by the builder. + */ + BytesTrie(void *adoptBytes, const void *trieBytes) + : ownedArray_(static_cast(adoptBytes)), + bytes_(static_cast(trieBytes)), + pos_(bytes_), remainingMatchLength_(-1) {} + + // No assignment operator. + BytesTrie &operator=(const BytesTrie &other) = delete; + + inline void stop() { + pos_=nullptr; + } + + // Reads a compact 32-bit integer. + // pos is already after the leadByte, and the lead byte is already shifted right by 1. + static int32_t readValue(const uint8_t *pos, int32_t leadByte); + static inline const uint8_t *skipValue(const uint8_t *pos, int32_t leadByte) { + // U_ASSERT(leadByte>=kMinValueLead); + if(leadByte>=(kMinTwoByteValueLead<<1)) { + if(leadByte<(kMinThreeByteValueLead<<1)) { + ++pos; + } else if(leadByte<(kFourByteValueLead<<1)) { + pos+=2; + } else { + pos+=3+((leadByte>>1)&1); + } + } + return pos; + } + static inline const uint8_t *skipValue(const uint8_t *pos) { + int32_t leadByte=*pos++; + return skipValue(pos, leadByte); + } + + // Reads a jump delta and jumps. + static const uint8_t *jumpByDelta(const uint8_t *pos); + + static inline const uint8_t *skipDelta(const uint8_t *pos) { + int32_t delta=*pos++; + if(delta>=kMinTwoByteDeltaLead) { + if(delta>8)+1; // 0x6c + static const int32_t kFourByteValueLead=0x7e; + + // A little more than Unicode code points. (0x11ffff) + static const int32_t kMaxThreeByteValue=((kFourByteValueLead-kMinThreeByteValueLead)<<16)-1; + + static const int32_t kFiveByteValueLead=0x7f; + + // Compact delta integers. + static const int32_t kMaxOneByteDelta=0xbf; + static const int32_t kMinTwoByteDeltaLead=kMaxOneByteDelta+1; // 0xc0 + static const int32_t kMinThreeByteDeltaLead=0xf0; + static const int32_t kFourByteDeltaLead=0xfe; + static const int32_t kFiveByteDeltaLead=0xff; + + static const int32_t kMaxTwoByteDelta=((kMinThreeByteDeltaLead-kMinTwoByteDeltaLead)<<8)-1; // 0x2fff + static const int32_t kMaxThreeByteDelta=((kFourByteDeltaLead-kMinThreeByteDeltaLead)<<16)-1; // 0xdffff + + // For getState64(): + // The remainingMatchLength_ is -1..14=(kMaxLinearMatchLength=0x10)-2 + // so we need at least 5 bits for that. + // We add 2 to store it as a positive value 1..16=kMaxLinearMatchLength. + static constexpr int32_t kState64RemainingShift = 59; + static constexpr uint64_t kState64PosMask = (UINT64_C(1) << kState64RemainingShift) - 1; + + uint8_t *ownedArray_; + + // Fixed value referencing the BytesTrie bytes. + const uint8_t *bytes_; + + // Iterator variables. + + // Pointer to next trie byte to read. nullptr if no more matches. + const uint8_t *pos_; + // Remaining length of a linear-match node, minus 1. Negative if not in such a node. + int32_t remainingMatchLength_; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __BYTESTRIE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestriebuilder.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestriebuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..ec9c625473d4f52ba202e5a3e42c6709ce37fb21 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/bytestriebuilder.h @@ -0,0 +1,193 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: bytestriebuilder.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010sep25 +* created by: Markus W. Scherer +*/ + +/** + * \file + * \brief C++ API: Builder for icu::BytesTrie + */ + +#ifndef __BYTESTRIEBUILDER_H__ +#define __BYTESTRIEBUILDER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/bytestrie.h" +#include "unicode/stringpiece.h" +#include "unicode/stringtriebuilder.h" + +class BytesTrieTest; + +U_NAMESPACE_BEGIN + +class BytesTrieElement; +class CharString; +/** + * Builder class for BytesTrie. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API BytesTrieBuilder : public StringTrieBuilder { +public: + /** + * Constructs an empty builder. + * @param errorCode Standard ICU error code. + * @stable ICU 4.8 + */ + BytesTrieBuilder(UErrorCode &errorCode); + + /** + * Destructor. + * @stable ICU 4.8 + */ + virtual ~BytesTrieBuilder(); + + /** + * Adds a (byte sequence, value) pair. + * The byte sequence must be unique. + * The bytes will be copied; the builder does not keep + * a reference to the input StringPiece or its data(). + * @param s The input byte sequence. + * @param value The value associated with this byte sequence. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @stable ICU 4.8 + */ + BytesTrieBuilder &add(StringPiece s, int32_t value, UErrorCode &errorCode); + + /** + * Builds a BytesTrie for the add()ed data. + * Once built, no further data can be add()ed until clear() is called. + * + * A BytesTrie cannot be empty. At least one (byte sequence, value) pair + * must have been add()ed. + * + * This method passes ownership of the builder's internal result array to the new trie object. + * Another call to any build() variant will re-serialize the trie. + * After clear() has been called, a new array will be used as well. + * @param buildOption Build option, see UStringTrieBuildOption. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return A new BytesTrie for the add()ed data. + * @stable ICU 4.8 + */ + BytesTrie *build(UStringTrieBuildOption buildOption, UErrorCode &errorCode); + + /** + * Builds a BytesTrie for the add()ed data and byte-serializes it. + * Once built, no further data can be add()ed until clear() is called. + * + * A BytesTrie cannot be empty. At least one (byte sequence, value) pair + * must have been add()ed. + * + * Multiple calls to buildStringPiece() return StringPieces referring to the + * builder's same byte array, without rebuilding. + * If buildStringPiece() is called after build(), the trie will be + * re-serialized into a new array (because build() passes on ownership). + * If build() is called after buildStringPiece(), the trie object returned + * by build() will become the owner of the underlying string for the + * previously returned StringPiece. + * After clear() has been called, a new array will be used as well. + * @param buildOption Build option, see UStringTrieBuildOption. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return A StringPiece which refers to the byte-serialized BytesTrie for the add()ed data. + * @stable ICU 4.8 + */ + StringPiece buildStringPiece(UStringTrieBuildOption buildOption, UErrorCode &errorCode); + + /** + * Removes all (byte sequence, value) pairs. + * New data can then be add()ed and a new trie can be built. + * @return *this + * @stable ICU 4.8 + */ + BytesTrieBuilder &clear(); + +private: + friend class ::BytesTrieTest; + + BytesTrieBuilder(const BytesTrieBuilder &other) = delete; // no copy constructor + BytesTrieBuilder &operator=(const BytesTrieBuilder &other) = delete; // no assignment operator + + void buildBytes(UStringTrieBuildOption buildOption, UErrorCode &errorCode); + + virtual int32_t getElementStringLength(int32_t i) const override; + virtual char16_t getElementUnit(int32_t i, int32_t byteIndex) const override; + virtual int32_t getElementValue(int32_t i) const override; + + virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t byteIndex) const override; + + virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t byteIndex) const override; + virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t byteIndex, int32_t count) const override; + virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t byteIndex, char16_t byte) const override; + + virtual UBool matchNodesCanHaveValues() const override { return false; } + + virtual int32_t getMaxBranchLinearSubNodeLength() const override { return BytesTrie::kMaxBranchLinearSubNodeLength; } + virtual int32_t getMinLinearMatch() const override { return BytesTrie::kMinLinearMatch; } + virtual int32_t getMaxLinearMatchLength() const override { return BytesTrie::kMaxLinearMatchLength; } + + /** + * @internal (private) + */ + class BTLinearMatchNode : public LinearMatchNode { + public: + BTLinearMatchNode(const char *units, int32_t len, Node *nextNode); + virtual bool operator==(const Node &other) const override; + virtual void write(StringTrieBuilder &builder) override; + private: + const char *s; + }; + + virtual Node *createLinearMatchNode(int32_t i, int32_t byteIndex, int32_t length, + Node *nextNode) const override; + + UBool ensureCapacity(int32_t length); + virtual int32_t write(int32_t byte) override; + int32_t write(const char *b, int32_t length); + virtual int32_t writeElementUnits(int32_t i, int32_t byteIndex, int32_t length) override; + virtual int32_t writeValueAndFinal(int32_t i, UBool isFinal) override; + virtual int32_t writeValueAndType(UBool hasValue, int32_t value, int32_t node) override; + virtual int32_t writeDeltaTo(int32_t jumpTarget) override; + static int32_t internalEncodeDelta(int32_t i, char intBytes[]); + + CharString *strings; // Pointer not object so we need not #include internal charstr.h. + BytesTrieElement *elements; + int32_t elementsCapacity; + int32_t elementsLength; + + // Byte serialization of the trie. + // Grows from the back: bytesLength measures from the end of the buffer! + char *bytes; + int32_t bytesCapacity; + int32_t bytesLength; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __BYTESTRIEBUILDER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/calendar.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/calendar.h new file mode 100644 index 0000000000000000000000000000000000000000..aa83866ac9cc824c2aeab0d1d86a62f74668eba9 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/calendar.h @@ -0,0 +1,2567 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2014, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File CALENDAR.H +* +* Modification History: +* +* Date Name Description +* 04/22/97 aliu Expanded and corrected comments and other header +* contents. +* 05/01/97 aliu Made equals(), before(), after() arguments const. +* 05/20/97 aliu Replaced fAreFieldsSet with fAreFieldsInSync and +* fAreAllFieldsSet. +* 07/27/98 stephen Sync up with JDK 1.2 +* 11/15/99 weiv added YEAR_WOY and DOW_LOCAL +* to EDateFields +* 8/19/2002 srl Removed Javaisms +* 11/07/2003 srl Update, clean up documentation. +******************************************************************************** +*/ + +#ifndef CALENDAR_H +#define CALENDAR_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Calendar object + */ +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" +#include "unicode/locid.h" +#include "unicode/timezone.h" +#include "unicode/ucal.h" +#include "unicode/umisc.h" + +U_NAMESPACE_BEGIN + +class ICUServiceFactory; + +// Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API, +// it is a return type for a virtual method (@internal) +/** + * @internal + */ +typedef int32_t UFieldResolutionTable[12][8]; + +class BasicTimeZone; +/** + * `Calendar` is an abstract base class for converting between + * a `UDate` object and a set of integer fields such as + * `YEAR`, `MONTH`, `DAY`, `HOUR`, and so on. + * (A `UDate` object represents a specific instant in + * time with millisecond precision. See UDate + * for information about the `UDate` class.) + * + * Subclasses of `Calendar` interpret a `UDate` + * according to the rules of a specific calendar system. + * The most commonly used subclass of `Calendar` is + * `GregorianCalendar`. Other subclasses could represent + * the various types of lunar calendars in use in many parts of the world. + * + * **NOTE**: (ICU 2.6) The subclass interface should be considered unstable - + * it WILL change. + * + * Like other locale-sensitive classes, `Calendar` provides a + * static method, `createInstance`, for getting a generally useful + * object of this type. `Calendar`'s `createInstance` method + * returns the appropriate `Calendar` subclass whose + * time fields have been initialized with the current date and time: + * + * Calendar *rightNow = Calendar::createInstance(errCode); + * + * A `Calendar` object can produce all the time field values + * needed to implement the date-time formatting for a particular language + * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). + * + * When computing a `UDate` from time fields, some special circumstances + * may arise: there may be insufficient information to compute the + * `UDate` (such as only year and month but no day in the month), + * there may be inconsistent information (such as "Tuesday, July 15, 1996" + * -- July 15, 1996 is actually a Monday), or the input time might be ambiguous + * because of time zone transition. + * + * **Insufficient information.** The calendar will use default + * information to specify the missing fields. This may vary by calendar; for + * the Gregorian calendar, the default for a field is the same as that of the + * start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc. + * + * **Inconsistent information.** If fields conflict, the calendar + * will give preference to fields set more recently. For example, when + * determining the day, the calendar will look for one of the following + * combinations of fields. The most recent combination, as determined by the + * most recently set single field, will be used. + * + * MONTH + DAY_OF_MONTH + * MONTH + WEEK_OF_MONTH + DAY_OF_WEEK + * MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK + * DAY_OF_YEAR + * DAY_OF_WEEK + WEEK_OF_YEAR + * + * For the time of day: + * + * HOUR_OF_DAY + * AM_PM + HOUR + * + * **Ambiguous Wall Clock Time.** When time offset from UTC has + * changed, it produces an ambiguous time slot around the transition. For example, + * many US locations observe daylight saving time. On the date switching to daylight + * saving time in US, wall clock time jumps from 12:59 AM (standard) to 2:00 AM + * (daylight). Therefore, wall clock time from 1:00 AM to 1:59 AM do not exist on + * the date. When the input wall time fall into this missing time slot, the ICU + * Calendar resolves the time using the UTC offset before the transition by default. + * In this example, 1:30 AM is interpreted as 1:30 AM standard time (non-exist), + * so the final result will be 2:30 AM daylight time. + * + * On the date switching back to standard time, wall clock time is moved back one + * hour at 2:00 AM. So wall clock time from 1:00 AM to 1:59 AM occur twice. In this + * case, the ICU Calendar resolves the time using the UTC offset after the transition + * by default. For example, 1:30 AM on the date is resolved as 1:30 AM standard time. + * + * Ambiguous wall clock time resolution behaviors can be customized by Calendar APIs + * {@link #setRepeatedWallTimeOption} and {@link #setSkippedWallTimeOption}. + * These methods are available in ICU 49 or later versions. + * + * **Note:** for some non-Gregorian calendars, different + * fields may be necessary for complete disambiguation. For example, a full + * specification of the historical Arabic astronomical calendar requires year, + * month, day-of-month *and* day-of-week in some cases. + * + * **Note:** There are certain possible ambiguities in + * interpretation of certain singular times, which are resolved in the + * following ways: + * + * 1. 24:00:00 "belongs" to the following day. That is, + * 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970 + * 2. Although historically not precise, midnight also belongs to "am", + * and noon belongs to "pm", so on the same day, + * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm + * + * The date or time format strings are not part of the definition of a + * calendar, as those must be modifiable or overridable by the user at + * runtime. Use `DateFormat` to format dates. + * + * `Calendar` provides an API for field "rolling", where fields + * can be incremented or decremented, but wrap around. For example, rolling the + * month up in the date December 12, **1996** results in + * January 12, **1996**. + * + * `Calendar` also provides a date arithmetic function for + * adding the specified (signed) amount of time to a particular time field. + * For example, subtracting 5 days from the date `September 12, 1996` + * results in `September 7, 1996`. + * + * ***Supported range*** + * + * The allowable range of `Calendar` has been narrowed. `GregorianCalendar` used + * to attempt to support the range of dates with millisecond values from + * `Long.MIN_VALUE` to `Long.MAX_VALUE`. The new `Calendar` protocol specifies the + * maximum range of supportable dates as those having Julian day numbers + * of `-0x7F000000` to `+0x7F000000`. This corresponds to years from ~5,800,000 BCE + * to ~5,800,000 CE. Programmers should use the protected constants in `Calendar` to + * specify an extremely early or extremely late date. + * + *

+ * The Japanese calendar uses a combination of era name and year number. + * When an emperor of Japan abdicates and a new emperor ascends the throne, + * a new era is declared and year number is reset to 1. Even if the date of + * abdication is scheduled ahead of time, the new era name might not be + * announced until just before the date. In such case, ICU4C may include + * a start date of future era without actual era name, but not enabled + * by default. ICU4C users who want to test the behavior of the future era + * can enable the tentative era by: + *

    + *
  • Environment variable ICU_ENABLE_TENTATIVE_ERA=true.
  • + *
+ * + * @stable ICU 2.0 + */ +class U_I18N_API Calendar : public UObject { +public: +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Field IDs for date and time. Used to specify date/time fields. ERA is calendar + * specific. Example ranges given are for illustration only; see specific Calendar + * subclasses for actual ranges. + * @deprecated ICU 2.6. Use C enum UCalendarDateFields defined in ucal.h + */ + enum EDateFields { +#ifndef U_HIDE_DEPRECATED_API +/* + * ERA may be defined on other platforms. To avoid any potential problems undefined it here. + */ +#ifdef ERA +#undef ERA +#endif + ERA, // Example: 0..1 + YEAR, // Example: 1..big number + MONTH, // Example: 0..11 + WEEK_OF_YEAR, // Example: 1..53 + WEEK_OF_MONTH, // Example: 1..4 + DATE, // Example: 1..31 + DAY_OF_YEAR, // Example: 1..365 + DAY_OF_WEEK, // Example: 1..7 + DAY_OF_WEEK_IN_MONTH, // Example: 1..4, may be specified as -1 + AM_PM, // Example: 0..1 + HOUR, // Example: 0..11 + HOUR_OF_DAY, // Example: 0..23 + MINUTE, // Example: 0..59 + SECOND, // Example: 0..59 + MILLISECOND, // Example: 0..999 + ZONE_OFFSET, // Example: -12*U_MILLIS_PER_HOUR..12*U_MILLIS_PER_HOUR + DST_OFFSET, // Example: 0 or U_MILLIS_PER_HOUR + YEAR_WOY, // 'Y' Example: 1..big number - Year of Week of Year + DOW_LOCAL, // 'e' Example: 1..7 - Day of Week / Localized + + EXTENDED_YEAR, + JULIAN_DAY, + MILLISECONDS_IN_DAY, + IS_LEAP_MONTH, + + FIELD_COUNT = UCAL_FIELD_COUNT // See ucal.h for other fields. +#endif /* U_HIDE_DEPRECATED_API */ + }; +#endif // U_FORCE_HIDE_DEPRECATED_API + +#ifndef U_HIDE_DEPRECATED_API + /** + * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients + * who create locale resources for the field of first-day-of-week should be aware of + * this. For instance, in US locale, first-day-of-week is set to 1, i.e., SUNDAY. + * @deprecated ICU 2.6. Use C enum UCalendarDaysOfWeek defined in ucal.h + */ + enum EDaysOfWeek { + SUNDAY = 1, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY + }; + + /** + * Useful constants for month. Note: Calendar month is 0-based. + * @deprecated ICU 2.6. Use C enum UCalendarMonths defined in ucal.h + */ + enum EMonths { + JANUARY, + FEBRUARY, + MARCH, + APRIL, + MAY, + JUNE, + JULY, + AUGUST, + SEPTEMBER, + OCTOBER, + NOVEMBER, + DECEMBER, + UNDECIMBER + }; + + /** + * Useful constants for hour in 12-hour clock. Used in GregorianCalendar. + * @deprecated ICU 2.6. Use C enum UCalendarAMPMs defined in ucal.h + */ + enum EAmpm { + AM, + PM + }; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * destructor + * @stable ICU 2.0 + */ + virtual ~Calendar(); + + /** + * Create and return a polymorphic copy of this calendar. + * + * @return a polymorphic copy of this calendar. + * @stable ICU 2.0 + */ + virtual Calendar* clone() const = 0; + + /** + * Creates a Calendar using the default timezone and locale. Clients are responsible + * for deleting the object returned. + * + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. U_MISSING_RESOURCE_ERROR will be returned if the resource data + * requests a calendar type which has not been installed. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(UErrorCode& success); + + /** + * Creates a Calendar using the given timezone and the default locale. + * The Calendar takes ownership of zoneToAdopt; the + * client must not delete it. + * + * @param zoneToAdopt The given timezone to be adopted. + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, UErrorCode& success); + + /** + * Creates a Calendar using the given timezone and the default locale. The TimeZone + * is _not_ adopted; the client is still responsible for deleting it. + * + * @param zone The timezone. + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(const TimeZone& zone, UErrorCode& success); + + /** + * Creates a Calendar using the default timezone and the given locale. + * + * @param aLocale The given locale. + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(const Locale& aLocale, UErrorCode& success); + + /** + * Creates a Calendar using the given timezone and given locale. + * The Calendar takes ownership of zoneToAdopt; the + * client must not delete it. + * + * @param zoneToAdopt The given timezone to be adopted. + * @param aLocale The given locale. + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success); + + /** + * Gets a Calendar using the given timezone and given locale. The TimeZone + * is _not_ adopted; the client is still responsible for deleting it. + * + * @param zone The given timezone. + * @param aLocale The given locale. + * @param success Indicates the success/failure of Calendar creation. Filled in + * with U_ZERO_ERROR if created successfully, set to a failure result + * otherwise. + * @return A Calendar if created successfully. nullptr otherwise. + * @stable ICU 2.0 + */ + static Calendar* U_EXPORT2 createInstance(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); + + /** + * Returns a list of the locales for which Calendars are installed. + * + * @param count Number of locales returned. + * @return An array of Locale objects representing the set of locales for which + * Calendars are installed. The system retains ownership of this list; + * the caller must NOT delete it. Does not include user-registered Calendars. + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + + /** + * Given a key and a locale, returns an array of string values in a preferred + * order that would make a difference. These are all and only those values where + * the open (creation) of the service with the locale formed from the input locale + * plus input keyword and that value has different behavior than creation with the + * input locale alone. + * @param key one of the keys supported by this service. For now, only + * "calendar" is supported. + * @param locale the locale + * @param commonlyUsed if set to true it will return only commonly used values + * with the given locale in preferred order. Otherwise, + * it will return all the available values for the locale. + * @param status ICU Error Code + * @return a string enumeration over keyword values for the given key and the locale. + * @stable ICU 4.2 + */ + static StringEnumeration* U_EXPORT2 getKeywordValuesForLocale(const char* key, + const Locale& locale, UBool commonlyUsed, UErrorCode& status); + + /** + * Returns the current UTC (GMT) time measured in milliseconds since 0:00:00 on 1/1/70 + * (derived from the system time). + * + * @return The current UTC time in milliseconds. + * @stable ICU 2.0 + */ + static UDate U_EXPORT2 getNow(void); + + /** + * Gets this Calendar's time as milliseconds. May involve recalculation of time due + * to previous calls to set time field values. The time specified is non-local UTC + * (GMT) time. Although this method is const, this object may actually be changed + * (semantically const). + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @return The current time in UTC (GMT) time, or zero if the operation + * failed. + * @stable ICU 2.0 + */ + inline UDate getTime(UErrorCode& status) const { return getTimeInMillis(status); } + + /** + * Sets this Calendar's current time with the given UDate. The time specified should + * be in non-local UTC (GMT) time. + * + * @param date The given UDate in UTC (GMT) time. + * @param status Output param set to success/failure code on exit. If any value + * set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.0 + */ + inline void setTime(UDate date, UErrorCode& status) { setTimeInMillis(date, status); } + + /** + * Compares the equality of two Calendar objects. Objects of different subclasses + * are considered unequal. This comparison is very exacting; two Calendar objects + * must be in exactly the same state to be considered equal. To compare based on the + * represented time, use equals() instead. + * + * @param that The Calendar object to be compared with. + * @return true if the given Calendar is the same as this Calendar; false + * otherwise. + * @stable ICU 2.0 + */ + virtual bool operator==(const Calendar& that) const; + + /** + * Compares the inequality of two Calendar objects. + * + * @param that The Calendar object to be compared with. + * @return true if the given Calendar is not the same as this Calendar; false + * otherwise. + * @stable ICU 2.0 + */ + bool operator!=(const Calendar& that) const {return !operator==(that);} + + /** + * Returns true if the given Calendar object is equivalent to this + * one. An equivalent Calendar will behave exactly as this one + * does, but it may be set to a different time. By contrast, for + * the operator==() method to return true, the other Calendar must + * be set to the same time. + * + * @param other the Calendar to be compared with this Calendar + * @stable ICU 2.4 + */ + virtual UBool isEquivalentTo(const Calendar& other) const; + + /** + * Compares the Calendar time, whereas Calendar::operator== compares the equality of + * Calendar objects. + * + * @param when The Calendar to be compared with this Calendar. Although this is a + * const parameter, the object may be modified physically + * (semantically const). + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @return True if the current time of this Calendar is equal to the time of + * Calendar when; false otherwise. + * @stable ICU 2.0 + */ + UBool equals(const Calendar& when, UErrorCode& status) const; + + /** + * Returns true if this Calendar's current time is before "when"'s current time. + * + * @param when The Calendar to be compared with this Calendar. Although this is a + * const parameter, the object may be modified physically + * (semantically const). + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @return True if the current time of this Calendar is before the time of + * Calendar when; false otherwise. + * @stable ICU 2.0 + */ + UBool before(const Calendar& when, UErrorCode& status) const; + + /** + * Returns true if this Calendar's current time is after "when"'s current time. + * + * @param when The Calendar to be compared with this Calendar. Although this is a + * const parameter, the object may be modified physically + * (semantically const). + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @return True if the current time of this Calendar is after the time of + * Calendar when; false otherwise. + * @stable ICU 2.0 + */ + UBool after(const Calendar& when, UErrorCode& status) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * UDate Arithmetic function. Adds the specified (signed) amount of time to the given + * time field, based on the calendar's rules. For example, to subtract 5 days from + * the current time of the calendar, call add(Calendar::DATE, -5). When adding on + * the month or Calendar::MONTH field, other fields like date might conflict and + * need to be changed. For instance, adding 1 month on the date 01/31/96 will result + * in 02/29/96. + * Adding a positive value always means moving forward in time, so for the Gregorian calendar, + * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces + * the numeric value of the field itself). + * + * @param field Specifies which date field to modify. + * @param amount The amount of time to be added to the field, in the natural unit + * for that field (e.g., days for the day fields, hours for the hour + * field.) + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @deprecated ICU 2.6. use add(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. + */ + virtual void add(EDateFields field, int32_t amount, UErrorCode& status); +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * UDate Arithmetic function. Adds the specified (signed) amount of time to the given + * time field, based on the calendar's rules. For example, to subtract 5 days from + * the current time of the calendar, call add(Calendar::DATE, -5). When adding on + * the month or Calendar::MONTH field, other fields like date might conflict and + * need to be changed. For instance, adding 1 month on the date 01/31/96 will result + * in 02/29/96. + * Adding a positive value always means moving forward in time, so for the Gregorian calendar, + * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces + * the numeric value of the field itself). + * + * @param field Specifies which date field to modify. + * @param amount The amount of time to be added to the field, in the natural unit + * for that field (e.g., days for the day fields, hours for the hour + * field.) + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.6. + */ + virtual void add(UCalendarDateFields field, int32_t amount, UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Time Field Rolling function. Rolls (up/down) a single unit of time on the given + * time field. For example, to roll the current date up by one day, call + * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it + * will roll the year value in the range between getMinimum(Calendar::YEAR) and the + * value returned by getMaximum(Calendar::YEAR). When rolling on the month or + * Calendar::MONTH field, other fields like date might conflict and, need to be + * changed. For instance, rolling the month up on the date 01/31/96 will result in + * 02/29/96. Rolling up always means rolling forward in time (unless the limit of the + * field is reached, in which case it may pin or wrap), so for Gregorian calendar, + * starting with 100 BC and rolling the year up results in 99 BC. + * When eras have a definite beginning and end (as in the Chinese calendar, or as in + * most eras in the Japanese calendar) then rolling the year past either limit of the + * era will cause the year to wrap around. When eras only have a limit at one end, + * then attempting to roll the year past that limit will result in pinning the year + * at that limit. Note that for most calendars in which era 0 years move forward in + * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to + * result in negative years for era 0 (that is the only way to represent years before + * the calendar epoch). + * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the + * hour value in the range between 0 and 23, which is zero-based. + *

+ * NOTE: Do not use this method -- use roll(EDateFields, int, UErrorCode&) instead. + * + * @param field The time field. + * @param up Indicates if the value of the specified time field is to be rolled + * up or rolled down. Use true if rolling up, false otherwise. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, UBool up, UErrorCode& status) instead. + */ + inline void roll(EDateFields field, UBool up, UErrorCode& status); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Time Field Rolling function. Rolls (up/down) a single unit of time on the given + * time field. For example, to roll the current date up by one day, call + * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it + * will roll the year value in the range between getMinimum(Calendar::YEAR) and the + * value returned by getMaximum(Calendar::YEAR). When rolling on the month or + * Calendar::MONTH field, other fields like date might conflict and, need to be + * changed. For instance, rolling the month up on the date 01/31/96 will result in + * 02/29/96. Rolling up always means rolling forward in time (unless the limit of the + * field is reached, in which case it may pin or wrap), so for Gregorian calendar, + * starting with 100 BC and rolling the year up results in 99 BC. + * When eras have a definite beginning and end (as in the Chinese calendar, or as in + * most eras in the Japanese calendar) then rolling the year past either limit of the + * era will cause the year to wrap around. When eras only have a limit at one end, + * then attempting to roll the year past that limit will result in pinning the year + * at that limit. Note that for most calendars in which era 0 years move forward in + * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to + * result in negative years for era 0 (that is the only way to represent years before + * the calendar epoch). + * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the + * hour value in the range between 0 and 23, which is zero-based. + *

+ * NOTE: Do not use this method -- use roll(UCalendarDateFields, int, UErrorCode&) instead. + * + * @param field The time field. + * @param up Indicates if the value of the specified time field is to be rolled + * up or rolled down. Use true if rolling up, false otherwise. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.6. + */ + inline void roll(UCalendarDateFields field, UBool up, UErrorCode& status); + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Time Field Rolling function. Rolls by the given amount on the given + * time field. For example, to roll the current date up by one day, call + * roll(Calendar::DATE, +1, status). When rolling on the month or + * Calendar::MONTH field, other fields like date might conflict and, need to be + * changed. For instance, rolling the month up on the date 01/31/96 will result in + * 02/29/96. Rolling by a positive value always means rolling forward in time (unless + * the limit of the field is reached, in which case it may pin or wrap), so for + * Gregorian calendar, starting with 100 BC and rolling the year by + 1 results in 99 BC. + * When eras have a definite beginning and end (as in the Chinese calendar, or as in + * most eras in the Japanese calendar) then rolling the year past either limit of the + * era will cause the year to wrap around. When eras only have a limit at one end, + * then attempting to roll the year past that limit will result in pinning the year + * at that limit. Note that for most calendars in which era 0 years move forward in + * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to + * result in negative years for era 0 (that is the only way to represent years before + * the calendar epoch). + * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the + * hour value in the range between 0 and 23, which is zero-based. + *

+ * The only difference between roll() and add() is that roll() does not change + * the value of more significant fields when it reaches the minimum or maximum + * of its range, whereas add() does. + * + * @param field The time field. + * @param amount Indicates amount to roll. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. + */ + virtual void roll(EDateFields field, int32_t amount, UErrorCode& status); +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Time Field Rolling function. Rolls by the given amount on the given + * time field. For example, to roll the current date up by one day, call + * roll(Calendar::DATE, +1, status). When rolling on the month or + * Calendar::MONTH field, other fields like date might conflict and, need to be + * changed. For instance, rolling the month up on the date 01/31/96 will result in + * 02/29/96. Rolling by a positive value always means rolling forward in time (unless + * the limit of the field is reached, in which case it may pin or wrap), so for + * Gregorian calendar, starting with 100 BC and rolling the year by + 1 results in 99 BC. + * When eras have a definite beginning and end (as in the Chinese calendar, or as in + * most eras in the Japanese calendar) then rolling the year past either limit of the + * era will cause the year to wrap around. When eras only have a limit at one end, + * then attempting to roll the year past that limit will result in pinning the year + * at that limit. Note that for most calendars in which era 0 years move forward in + * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to + * result in negative years for era 0 (that is the only way to represent years before + * the calendar epoch). + * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the + * hour value in the range between 0 and 23, which is zero-based. + *

+ * The only difference between roll() and add() is that roll() does not change + * the value of more significant fields when it reaches the minimum or maximum + * of its range, whereas add() does. + * + * @param field The time field. + * @param amount Indicates amount to roll. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @stable ICU 2.6. + */ + virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status); + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Return the difference between the given time and the time this + * calendar object is set to. If this calendar is set + * before the given time, the returned value will be + * positive. If this calendar is set after the given + * time, the returned value will be negative. The + * field parameter specifies the units of the return + * value. For example, if fieldDifference(when, + * Calendar::MONTH) returns 3, then this calendar is set to + * 3 months before when, and possibly some addition + * time less than one month. + * + *

As a side effect of this call, this calendar is advanced + * toward when by the given amount. That is, calling + * this method has the side effect of calling add(field, + * n), where n is the return value. + * + *

Usage: To use this method, call it first with the largest + * field of interest, then with progressively smaller fields. For + * example: + * + *

+     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
+     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
+     * int d = cal->fieldDifference(when, Calendar::DATE, err);
+ * + * computes the difference between cal and + * when in years, months, and days. + * + *

Note: fieldDifference() is + * asymmetrical. That is, in the following code: + * + *

+     * cal->setTime(date1, err);
+     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
+     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
+     * cal->setTime(date2, err);
+     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
+     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);
+ * + * one might expect that m1 == -m2 && d1 == -d2. + * However, this is not generally the case, because of + * irregularities in the underlying calendar system (e.g., the + * Gregorian calendar has a varying number of days per month). + * + * @param when the date to compare this calendar's time to + * @param field the field in which to compute the result + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @return the difference, either positive or negative, between + * this calendar's time and when, in terms of + * field. + * @deprecated ICU 2.6. Use fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status). + */ + virtual int32_t fieldDifference(UDate when, EDateFields field, UErrorCode& status); +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Return the difference between the given time and the time this + * calendar object is set to. If this calendar is set + * before the given time, the returned value will be + * positive. If this calendar is set after the given + * time, the returned value will be negative. The + * field parameter specifies the units of the return + * value. For example, if fieldDifference(when, + * Calendar::MONTH) returns 3, then this calendar is set to + * 3 months before when, and possibly some addition + * time less than one month. + * + *

As a side effect of this call, this calendar is advanced + * toward when by the given amount. That is, calling + * this method has the side effect of calling add(field, + * n), where n is the return value. + * + *

Usage: To use this method, call it first with the largest + * field of interest, then with progressively smaller fields. For + * example: + * + *

+     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
+     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
+     * int d = cal->fieldDifference(when, Calendar::DATE, err);
+ * + * computes the difference between cal and + * when in years, months, and days. + * + *

Note: fieldDifference() is + * asymmetrical. That is, in the following code: + * + *

+     * cal->setTime(date1, err);
+     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
+     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
+     * cal->setTime(date2, err);
+     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
+     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);
+ * + * one might expect that m1 == -m2 && d1 == -d2. + * However, this is not generally the case, because of + * irregularities in the underlying calendar system (e.g., the + * Gregorian calendar has a varying number of days per month). + * + * @param when the date to compare this calendar's time to + * @param field the field in which to compute the result + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @return the difference, either positive or negative, between + * this calendar's time and when, in terms of + * field. + * @stable ICU 2.6. + */ + virtual int32_t fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status); + + /** + * Sets the calendar's time zone to be the one passed in. The Calendar takes ownership + * of the TimeZone; the caller is no longer responsible for deleting it. If the + * given time zone is nullptr, this function has no effect. + * + * @param value The given time zone. + * @stable ICU 2.0 + */ + void adoptTimeZone(TimeZone* value); + + /** + * Sets the calendar's time zone to be the same as the one passed in. The TimeZone + * passed in is _not_ adopted; the client is still responsible for deleting it. + * + * @param zone The given time zone. + * @stable ICU 2.0 + */ + void setTimeZone(const TimeZone& zone); + + /** + * Returns a reference to the time zone owned by this calendar. The returned reference + * is only valid until clients make another call to adoptTimeZone or setTimeZone, + * or this Calendar is destroyed. + * + * @return The time zone object associated with this calendar. + * @stable ICU 2.0 + */ + const TimeZone& getTimeZone(void) const; + + /** + * Returns the time zone owned by this calendar. The caller owns the returned object + * and must delete it when done. After this call, the new time zone associated + * with this Calendar is the default TimeZone as returned by TimeZone::createDefault(). + * + * @return The time zone object which was associated with this calendar. + * @stable ICU 2.0 + */ + TimeZone* orphanTimeZone(void); + + /** + * Queries if the current date for this Calendar is in Daylight Savings Time. + * + * @param status Fill-in parameter which receives the status of this operation. + * @return True if the current date for this Calendar is in Daylight Savings Time, + * false, otherwise. + * @stable ICU 2.0 + */ + virtual UBool inDaylightTime(UErrorCode& status) const; + + /** + * Specifies whether or not date/time interpretation is to be lenient. With lenient + * interpretation, a date such as "February 942, 1996" will be treated as being + * equivalent to the 941st day after February 1, 1996. With strict interpretation, + * such dates will cause an error when computing time from the time field values + * representing the dates. + * + * @param lenient True specifies date/time interpretation to be lenient. + * + * @see DateFormat#setLenient + * @stable ICU 2.0 + */ + void setLenient(UBool lenient); + + /** + * Tells whether date/time interpretation is to be lenient. + * + * @return True tells that date/time interpretation is to be lenient. + * @stable ICU 2.0 + */ + UBool isLenient(void) const; + + /** + * Sets the behavior for handling wall time repeating multiple times + * at negative time zone offset transitions. For example, 1:30 AM on + * November 6, 2011 in US Eastern time (America/New_York) occurs twice; + * 1:30 AM EDT, then 1:30 AM EST one hour later. When UCAL_WALLTIME_FIRST + * is used, the wall time 1:30AM in this example will be interpreted as 1:30 AM EDT + * (first occurrence). When UCAL_WALLTIME_LAST is used, it will be + * interpreted as 1:30 AM EST (last occurrence). The default value is + * UCAL_WALLTIME_LAST. + *

+ * Note:When UCAL_WALLTIME_NEXT_VALID is not a valid + * option for this. When the argument is neither UCAL_WALLTIME_FIRST + * nor UCAL_WALLTIME_LAST, this method has no effect and will keep + * the current setting. + * + * @param option the behavior for handling repeating wall time, either + * UCAL_WALLTIME_FIRST or UCAL_WALLTIME_LAST. + * @see #getRepeatedWallTimeOption + * @stable ICU 49 + */ + void setRepeatedWallTimeOption(UCalendarWallTimeOption option); + + /** + * Gets the behavior for handling wall time repeating multiple times + * at negative time zone offset transitions. + * + * @return the behavior for handling repeating wall time, either + * UCAL_WALLTIME_FIRST or UCAL_WALLTIME_LAST. + * @see #setRepeatedWallTimeOption + * @stable ICU 49 + */ + UCalendarWallTimeOption getRepeatedWallTimeOption(void) const; + + /** + * Sets the behavior for handling skipped wall time at positive time zone offset + * transitions. For example, 2:30 AM on March 13, 2011 in US Eastern time (America/New_York) + * does not exist because the wall time jump from 1:59 AM EST to 3:00 AM EDT. When + * UCAL_WALLTIME_FIRST is used, 2:30 AM is interpreted as 30 minutes before 3:00 AM + * EDT, therefore, it will be resolved as 1:30 AM EST. When UCAL_WALLTIME_LAST + * is used, 2:30 AM is interpreted as 31 minutes after 1:59 AM EST, therefore, it will be + * resolved as 3:30 AM EDT. When UCAL_WALLTIME_NEXT_VALID is used, 2:30 AM will + * be resolved as next valid wall time, that is 3:00 AM EDT. The default value is + * UCAL_WALLTIME_LAST. + *

+ * Note:This option is effective only when this calendar is lenient. + * When the calendar is strict, such non-existing wall time will cause an error. + * + * @param option the behavior for handling skipped wall time at positive time zone + * offset transitions, one of UCAL_WALLTIME_FIRST, UCAL_WALLTIME_LAST and + * UCAL_WALLTIME_NEXT_VALID. + * @see #getSkippedWallTimeOption + * + * @stable ICU 49 + */ + void setSkippedWallTimeOption(UCalendarWallTimeOption option); + + /** + * Gets the behavior for handling skipped wall time at positive time zone offset + * transitions. + * + * @return the behavior for handling skipped wall time, one of + * UCAL_WALLTIME_FIRST, UCAL_WALLTIME_LAST + * and UCAL_WALLTIME_NEXT_VALID. + * @see #setSkippedWallTimeOption + * @stable ICU 49 + */ + UCalendarWallTimeOption getSkippedWallTimeOption(void) const; + + /** + * Sets what the first day of the week is; e.g., Sunday in US, Monday in France. + * + * @param value The given first day of the week. + * @stable ICU 2.6. + */ + void setFirstDayOfWeek(UCalendarDaysOfWeek value); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Gets what the first day of the week is; e.g., Sunday in US, Monday in France. + * + * @return The first day of the week. + * @deprecated ICU 2.6 use the overload with error code + */ + EDaysOfWeek getFirstDayOfWeek(void) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Gets what the first day of the week is; e.g., Sunday in US, Monday in France. + * + * @param status error code + * @return The first day of the week. + * @stable ICU 2.6 + */ + UCalendarDaysOfWeek getFirstDayOfWeek(UErrorCode &status) const; + + /** + * Sets what the minimal days required in the first week of the year are; For + * example, if the first week is defined as one that contains the first day of the + * first month of a year, call the method with value 1. If it must be a full week, + * use value 7. + * + * @param value The given minimal days required in the first week of the year. + * @stable ICU 2.0 + */ + void setMinimalDaysInFirstWeek(uint8_t value); + + /** + * Gets what the minimal days required in the first week of the year are; e.g., if + * the first week is defined as one that contains the first day of the first month + * of a year, getMinimalDaysInFirstWeek returns 1. If the minimal days required must + * be a full week, getMinimalDaysInFirstWeek returns 7. + * + * @return The minimal days required in the first week of the year. + * @stable ICU 2.0 + */ + uint8_t getMinimalDaysInFirstWeek(void) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the minimum value for the given time field. e.g., for Gregorian + * DAY_OF_MONTH, 1. + * + * @param field The given time field. + * @return The minimum value for the given time field. + * @deprecated ICU 2.6. Use getMinimum(UCalendarDateFields field) instead. + */ + virtual int32_t getMinimum(EDateFields field) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the minimum value for the given time field. e.g., for Gregorian + * DAY_OF_MONTH, 1. + * + * @param field The given time field. + * @return The minimum value for the given time field. + * @stable ICU 2.6. + */ + virtual int32_t getMinimum(UCalendarDateFields field) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, + * 31. + * + * @param field The given time field. + * @return The maximum value for the given time field. + * @deprecated ICU 2.6. Use getMaximum(UCalendarDateFields field) instead. + */ + virtual int32_t getMaximum(EDateFields field) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, + * 31. + * + * @param field The given time field. + * @return The maximum value for the given time field. + * @stable ICU 2.6. + */ + virtual int32_t getMaximum(UCalendarDateFields field) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the highest minimum value for the given field if varies. Otherwise same as + * getMinimum(). For Gregorian, no difference. + * + * @param field The given time field. + * @return The highest minimum value for the given time field. + * @deprecated ICU 2.6. Use getGreatestMinimum(UCalendarDateFields field) instead. + */ + virtual int32_t getGreatestMinimum(EDateFields field) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the highest minimum value for the given field if varies. Otherwise same as + * getMinimum(). For Gregorian, no difference. + * + * @param field The given time field. + * @return The highest minimum value for the given time field. + * @stable ICU 2.6. + */ + virtual int32_t getGreatestMinimum(UCalendarDateFields field) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the lowest maximum value for the given field if varies. Otherwise same as + * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28. + * + * @param field The given time field. + * @return The lowest maximum value for the given time field. + * @deprecated ICU 2.6. Use getLeastMaximum(UCalendarDateFields field) instead. + */ + virtual int32_t getLeastMaximum(EDateFields field) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the lowest maximum value for the given field if varies. Otherwise same as + * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28. + * + * @param field The given time field. + * @return The lowest maximum value for the given time field. + * @stable ICU 2.6. + */ + virtual int32_t getLeastMaximum(UCalendarDateFields field) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Return the minimum value that this field could have, given the current date. + * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). + * + * The version of this function on Calendar uses an iterative algorithm to determine the + * actual minimum value for the field. There is almost always a more efficient way to + * accomplish this (in most cases, you can simply return getMinimum()). GregorianCalendar + * overrides this function with a more efficient implementation. + * + * @param field the field to determine the minimum of + * @param status Fill-in parameter which receives the status of this operation. + * @return the minimum of the given field for the current date of this Calendar + * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field, UErrorCode& status) instead. + */ + int32_t getActualMinimum(EDateFields field, UErrorCode& status) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Return the minimum value that this field could have, given the current date. + * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). + * + * The version of this function on Calendar uses an iterative algorithm to determine the + * actual minimum value for the field. There is almost always a more efficient way to + * accomplish this (in most cases, you can simply return getMinimum()). GregorianCalendar + * overrides this function with a more efficient implementation. + * + * @param field the field to determine the minimum of + * @param status Fill-in parameter which receives the status of this operation. + * @return the minimum of the given field for the current date of this Calendar + * @stable ICU 2.6. + */ + virtual int32_t getActualMinimum(UCalendarDateFields field, UErrorCode& status) const; + + /** + * Return the maximum value that this field could have, given the current date. + * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual + * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, + * for some years the actual maximum for MONTH is 12, and for others 13. + * + * The version of this function on Calendar uses an iterative algorithm to determine the + * actual maximum value for the field. There is almost always a more efficient way to + * accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar + * overrides this function with a more efficient implementation. + * + * @param field the field to determine the maximum of + * @param status Fill-in parameter which receives the status of this operation. + * @return the maximum of the given field for the current date of this Calendar + * @stable ICU 2.6. + */ + virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const; + + /** + * Gets the value for a given time field. Recalculate the current time field values + * if the time value has been changed by a call to setTime(). Return zero for unset + * fields if any fields have been explicitly set by a call to set(). To force a + * recomputation of all fields regardless of the previous state, call complete(). + * This method is semantically const, but may alter the object in memory. + * + * @param field The given time field. + * @param status Fill-in parameter which receives the status of the operation. + * @return The value for the given time field, or zero if the field is unset, + * and set() has been called for any other field. + * @stable ICU 2.6. + */ + int32_t get(UCalendarDateFields field, UErrorCode& status) const; + + /** + * Determines if the given time field has a value set. This can affect in the + * resolving of time in Calendar. Unset fields have a value of zero, by definition. + * + * @param field The given time field. + * @return True if the given time field has a value set; false otherwise. + * @stable ICU 2.6. + */ + UBool isSet(UCalendarDateFields field) const; + + /** + * Sets the given time field with the given value. + * + * @param field The given time field. + * @param value The value to be set for the given time field. + * @stable ICU 2.6. + */ + void set(UCalendarDateFields field, int32_t value); + + /** + * Sets the values for the fields YEAR, MONTH, and DATE. Other field values are + * retained; call clear() first if this is not desired. + * + * @param year The value used to set the YEAR time field. + * @param month The value used to set the MONTH time field. Month value is 0-based. + * e.g., 0 for January. + * @param date The value used to set the DATE time field. + * @stable ICU 2.0 + */ + void set(int32_t year, int32_t month, int32_t date); + + /** + * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, and MINUTE. Other + * field values are retained; call clear() first if this is not desired. + * + * @param year The value used to set the YEAR time field. + * @param month The value used to set the MONTH time field. Month value is + * 0-based. E.g., 0 for January. + * @param date The value used to set the DATE time field. + * @param hour The value used to set the HOUR_OF_DAY time field. + * @param minute The value used to set the MINUTE time field. + * @stable ICU 2.0 + */ + void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute); + + /** + * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, MINUTE, and SECOND. + * Other field values are retained; call clear() first if this is not desired. + * + * @param year The value used to set the YEAR time field. + * @param month The value used to set the MONTH time field. Month value is + * 0-based. E.g., 0 for January. + * @param date The value used to set the DATE time field. + * @param hour The value used to set the HOUR_OF_DAY time field. + * @param minute The value used to set the MINUTE time field. + * @param second The value used to set the SECOND time field. + * @stable ICU 2.0 + */ + void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second); + + /** + * Clears the values of all the time fields, making them both unset and assigning + * them a value of zero. The field values will be determined during the next + * resolving of time into time fields. + * @stable ICU 2.0 + */ + void clear(void); + + /** + * Clears the value in the given time field, both making it unset and assigning it a + * value of zero. This field value will be determined during the next resolving of + * time into time fields. + * + * @param field The time field to be cleared. + * @stable ICU 2.6. + */ + void clear(UCalendarDateFields field); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual method. This method is to + * implement a simple version of RTTI, since not all C++ compilers support genuine + * RTTI. Polymorphic operator==() and clone() methods call this method. + *

+ * Concrete subclasses of Calendar must implement getDynamicClassID() and also a + * static method and data member: + * + * static UClassID getStaticClassID() { return (UClassID)&fgClassID; } + * static char fgClassID; + * + * @return The class ID for this object. All objects of a given class have the + * same class ID. Objects of other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Returns the calendar type name string for this Calendar object. + * The returned string is the legacy ICU calendar attribute value, + * for example, "gregorian" or "japanese". + * + * See type="old type name" for the calendar attribute of locale IDs + * at http://www.unicode.org/reports/tr35/#Key_Type_Definitions + * + * Sample code for getting the LDML/BCP 47 calendar key value: + * \code + * const char *calType = cal->getType(); + * if (0 == strcmp(calType, "unknown")) { + * // deal with unknown calendar type + * } else { + * string localeID("root@calendar="); + * localeID.append(calType); + * char langTag[100]; + * UErrorCode errorCode = U_ZERO_ERROR; + * int32_t length = uloc_toLanguageTag(localeID.c_str(), langTag, (int32_t)sizeof(langTag), true, &errorCode); + * if (U_FAILURE(errorCode)) { + * // deal with errors & overflow + * } + * string lang(langTag, length); + * size_t caPos = lang.find("-ca-"); + * lang.erase(0, caPos + 4); + * // lang now contains the LDML calendar type + * } + * \endcode + * + * @return legacy calendar type name string + * @stable ICU 49 + */ + virtual const char * getType() const = 0; + + /** + * Returns whether the given day of the week is a weekday, a weekend day, + * or a day that transitions from one to the other, for the locale and + * calendar system associated with this Calendar (the locale's region is + * often the most determinant factor). If a transition occurs at midnight, + * then the days before and after the transition will have the + * type UCAL_WEEKDAY or UCAL_WEEKEND. If a transition occurs at a time + * other than midnight, then the day of the transition will have + * the type UCAL_WEEKEND_ONSET or UCAL_WEEKEND_CEASE. In this case, the + * method getWeekendTransition() will return the point of + * transition. + * @param dayOfWeek The day of the week whose type is desired (UCAL_SUNDAY..UCAL_SATURDAY). + * @param status The error code for the operation. + * @return The UCalendarWeekdayType for the day of the week. + * @stable ICU 4.4 + */ + virtual UCalendarWeekdayType getDayOfWeekType(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const; + + /** + * Returns the time during the day at which the weekend begins or ends in + * this calendar system. If getDayOfWeekType() returns UCAL_WEEKEND_ONSET + * for the specified dayOfWeek, return the time at which the weekend begins. + * If getDayOfWeekType() returns UCAL_WEEKEND_CEASE for the specified dayOfWeek, + * return the time at which the weekend ends. If getDayOfWeekType() returns + * some other UCalendarWeekdayType for the specified dayOfWeek, is it an error condition + * (U_ILLEGAL_ARGUMENT_ERROR). + * @param dayOfWeek The day of the week for which the weekend transition time is + * desired (UCAL_SUNDAY..UCAL_SATURDAY). + * @param status The error code for the operation. + * @return The milliseconds after midnight at which the weekend begins or ends. + * @stable ICU 4.4 + */ + virtual int32_t getWeekendTransition(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const; + + /** + * Returns true if the given UDate is in the weekend in + * this calendar system. + * @param date The UDate in question. + * @param status The error code for the operation. + * @return true if the given UDate is in the weekend in + * this calendar system, false otherwise. + * @stable ICU 4.4 + */ + virtual UBool isWeekend(UDate date, UErrorCode &status) const; + + /** + * Returns true if this Calendar's current date-time is in the weekend in + * this calendar system. + * @return true if this Calendar's current date-time is in the weekend in + * this calendar system, false otherwise. + * @stable ICU 4.4 + */ + virtual UBool isWeekend(void) const; + +#ifndef U_FORCE_HIDE_DRAFT_API + /** + * Returns true if the date is in a leap year. Recalculate the current time + * field values if the time value has been changed by a call to * setTime(). + * This method is semantically const, but may alter the object in memory. + * A "leap year" is a year that contains more days than other years (for + * solar or lunar calendars) or more months than other years (for lunisolar + * calendars like Hebrew or Chinese), as defined in the ECMAScript Temporal + * proposal. + * + * @param status ICU Error Code + * @return True if the date in the fields is in a Temporal proposal + * defined leap year. False otherwise. + * @draft ICU 73 + */ + virtual bool inTemporalLeapYear(UErrorCode& status) const; + + /** + * Gets The Temporal monthCode value corresponding to the month for the date. + * The value is a string identifier that starts with the literal grapheme + * "M" followed by two graphemes representing the zero-padded month number + * of the current month in a normal (non-leap) year and suffixed by an + * optional literal grapheme "L" if this is a leap month in a lunisolar + * calendar. The 25 possible values are "M01" .. "M13" and "M01L" .. "M12L". + * For the Hebrew calendar, the values are "M01" .. "M12" for non-leap year, and + * "M01" .. "M05", "M05L", "M06" .. "M12" for leap year. + * For the Chinese calendar, the values are "M01" .. "M12" for non-leap year and + * in leap year with another monthCode in "M01L" .. "M12L". + * For Coptic and Ethiopian calendar, the Temporal monthCode values for any + * years are "M01" to "M13". + * + * @param status ICU Error Code + * @return One of 25 possible strings in {"M01".."M13", "M01L".."M12L"}. + * @draft ICU 73 + */ + virtual const char* getTemporalMonthCode(UErrorCode& status) const; + + /** + * Sets The Temporal monthCode which is a string identifier that starts + * with the literal grapheme "M" followed by two graphemes representing + * the zero-padded month number of the current month in a normal + * (non-leap) year and suffixed by an optional literal grapheme "L" if this + * is a leap month in a lunisolar calendar. The 25 possible values are + * "M01" .. "M13" and "M01L" .. "M12L". For Hebrew calendar, the values are + * "M01" .. "M12" for non-leap years, and "M01" .. "M05", "M05L", "M06" + * .. "M12" for leap year. + * For the Chinese calendar, the values are "M01" .. "M12" for non-leap year and + * in leap year with another monthCode in "M01L" .. "M12L". + * For Coptic and Ethiopian calendar, the Temporal monthCode values for any + * years are "M01" to "M13". + * + * @param temporalMonth The value to be set for temporal monthCode. + * @param status ICU Error Code + * + * @draft ICU 73 + */ + virtual void setTemporalMonthCode(const char* temporalMonth, UErrorCode& status); + +#endif // U_FORCE_HIDE_DRAFT_API + +protected: + + /** + * Constructs a Calendar with the default time zone as returned by + * TimeZone::createInstance(), and the default locale. + * + * @param success Indicates the status of Calendar object construction. Returns + * U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + Calendar(UErrorCode& success); + + /** + * Copy constructor + * + * @param source Calendar object to be copied from + * @stable ICU 2.0 + */ + Calendar(const Calendar& source); + + /** + * Default assignment operator + * + * @param right Calendar object to be copied + * @stable ICU 2.0 + */ + Calendar& operator=(const Calendar& right); + + /** + * Constructs a Calendar with the given time zone and locale. Clients are no longer + * responsible for deleting the given time zone object after it's adopted. + * + * @param zone The given time zone. + * @param aLocale The given locale. + * @param success Indicates the status of Calendar object construction. Returns + * U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success); + + /** + * Constructs a Calendar with the given time zone and locale. + * + * @param zone The given time zone. + * @param aLocale The given locale. + * @param success Indicates the status of Calendar object construction. Returns + * U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); + + /** + * Converts Calendar's time field values to GMT as milliseconds. + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.0 + */ + virtual void computeTime(UErrorCode& status); + + /** + * Converts GMT as milliseconds to time field values. This allows you to sync up the + * time field values with a new time that is set for the calendar. This method + * does NOT recompute the time first; to recompute the time, then the fields, use + * the method complete(). + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.0 + */ + virtual void computeFields(UErrorCode& status); + + /** + * Gets this Calendar's current time as a long. + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @return the current time as UTC milliseconds from the epoch. + * @stable ICU 2.0 + */ + double getTimeInMillis(UErrorCode& status) const; + + /** + * Sets this Calendar's current time from the given long value. + * @param millis the new time in UTC milliseconds from the epoch. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.0 + */ + void setTimeInMillis( double millis, UErrorCode& status ); + + /** + * Recomputes the current time from currently set fields, and then fills in any + * unset fields in the time field list. + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + * @stable ICU 2.0 + */ + void complete(UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Gets the value for a given time field. Subclasses can use this function to get + * field values without forcing recomputation of time. + * + * @param field The given time field. + * @return The value for the given time field. + * @deprecated ICU 2.6. Use internalGet(UCalendarDateFields field) instead. + */ + inline int32_t internalGet(EDateFields field) const {return fFields[field];} +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_HIDE_INTERNAL_API + /** + * Gets the value for a given time field. Subclasses can use this function to get + * field values without forcing recomputation of time. If the field's stamp is UNSET, + * the defaultValue is used. + * + * @param field The given time field. + * @param defaultValue a default value used if the field is unset. + * @return The value for the given time field. + * @internal + */ + inline int32_t internalGet(UCalendarDateFields field, int32_t defaultValue) const {return fStamp[field]>kUnset ? fFields[field] : defaultValue;} + + /** + * Gets the value for a given time field. Subclasses can use this function to get + * field values without forcing recomputation of time. + * + * @param field The given time field. + * @return The value for the given time field. + * @internal + */ + inline int32_t internalGet(UCalendarDateFields field) const {return fFields[field];} +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Use this function instead of internalGet(UCAL_MONTH). The implementation + * check the timestamp of UCAL_MONTH and UCAL_ORDINAL_MONTH and use the + * one set later. The subclass should override it to conver the value of UCAL_ORDINAL_MONTH + * to UCAL_MONTH correctly if UCAL_ORDINAL_MONTH has higher priority. + * + * @return The value for the UCAL_MONTH. + * @internal + */ + virtual int32_t internalGetMonth() const; + + /** + * Use this function instead of internalGet(UCAL_MONTH, defaultValue). The implementation + * check the timestamp of UCAL_MONTH and UCAL_ORDINAL_MONTH and use the + * one set later. The subclass should override it to conver the value of UCAL_ORDINAL_MONTH + * to UCAL_MONTH correctly if UCAL_ORDINAL_MONTH has higher priority. + * + * @param defaultValue a default value used if the UCAL_MONTH and + * UCAL_ORDINAL are both unset. + * @return The value for the UCAL_MONTH. + * @internal + */ + virtual int32_t internalGetMonth(int32_t defaultValue) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Sets the value for a given time field. This is a fast internal method for + * subclasses. It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet + * flags. + * + * @param field The given time field. + * @param value The value for the given time field. + * @deprecated ICU 2.6. Use internalSet(UCalendarDateFields field, int32_t value) instead. + */ + void internalSet(EDateFields field, int32_t value); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Sets the value for a given time field. This is a fast internal method for + * subclasses. It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet + * flags. + * + * @param field The given time field. + * @param value The value for the given time field. + * @stable ICU 2.6. + */ + inline void internalSet(UCalendarDateFields field, int32_t value); + + /** + * Prepare this calendar for computing the actual minimum or maximum. + * This method modifies this calendar's fields; it is called on a + * temporary calendar. + * @internal + */ + virtual void prepareGetActual(UCalendarDateFields field, UBool isMinimum, UErrorCode &status); + + /** + * Limit enums. Not in sync with UCalendarLimitType (refers to internal fields). + * @internal + */ + enum ELimitType { +#ifndef U_HIDE_INTERNAL_API + UCAL_LIMIT_MINIMUM = 0, + UCAL_LIMIT_GREATEST_MINIMUM, + UCAL_LIMIT_LEAST_MAXIMUM, + UCAL_LIMIT_MAXIMUM, + UCAL_LIMIT_COUNT +#endif /* U_HIDE_INTERNAL_API */ + }; + + /** + * Subclass API for defining limits of different types. + * Subclasses must implement this method to return limits for the + * following fields: + * + *

UCAL_ERA
+     * UCAL_YEAR
+     * UCAL_MONTH
+     * UCAL_WEEK_OF_YEAR
+     * UCAL_WEEK_OF_MONTH
+     * UCAL_DATE (DAY_OF_MONTH on Java)
+     * UCAL_DAY_OF_YEAR
+     * UCAL_DAY_OF_WEEK_IN_MONTH
+     * UCAL_YEAR_WOY
+     * UCAL_EXTENDED_YEAR
+ * + * @param field one of the above field numbers + * @param limitType one of MINIMUM, GREATEST_MINIMUM, + * LEAST_MAXIMUM, or MAXIMUM + * @internal + */ + virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const = 0; + + /** + * Return a limit for a field. + * @param field the field, from 0..UCAL_MAX_FIELD + * @param limitType the type specifier for the limit + * @see #ELimitType + * @internal + */ + virtual int32_t getLimit(UCalendarDateFields field, ELimitType limitType) const; + + /** + * Return the Julian day number of day before the first day of the + * given month in the given extended year. Subclasses should override + * this method to implement their calendar system. + * @param eyear the extended year + * @param month the zero-based month, or 0 if useMonth is false + * @param useMonth if false, compute the day before the first day of + * the given year, otherwise, compute the day before the first day of + * the given month + * @return the Julian day number of the day before the first + * day of the given month and year + * @internal + */ + virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, + UBool useMonth) const = 0; + + /** + * Return the number of days in the given month of the given extended + * year of this calendar system. Subclasses should override this + * method if they can provide a more correct or more efficient + * implementation than the default implementation in Calendar. + * @internal + */ + virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const ; + + /** + * Return the number of days in the given extended year of this + * calendar system. Subclasses should override this method if they can + * provide a more correct or more efficient implementation than the + * default implementation in Calendar. + * @stable ICU 2.0 + */ + virtual int32_t handleGetYearLength(int32_t eyear) const; + + + /** + * Return the extended year defined by the current fields. This will + * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such + * as UCAL_ERA) specific to the calendar system, depending on which set of + * fields is newer. + * @return the extended year + * @internal + */ + virtual int32_t handleGetExtendedYear() = 0; + + /** + * Subclasses may override this. This method calls + * handleGetMonthLength() to obtain the calendar-specific month + * length. + * @param bestField which field to use to calculate the date + * @return julian day specified by calendar fields. + * @internal + */ + virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField); + + /** + * Subclasses must override this to convert from week fields + * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case + * where YEAR, EXTENDED_YEAR are not set. + * The Calendar implementation assumes yearWoy is in extended gregorian form + * @return the extended year, UCAL_EXTENDED_YEAR + * @internal + */ + virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy); + + /** + * Validate a single field of this calendar. Subclasses should + * override this method to validate any calendar-specific fields. + * Generic fields can be handled by `Calendar::validateField()`. + * @internal + */ + virtual void validateField(UCalendarDateFields field, UErrorCode &status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Compute the Julian day from fields. Will determine whether to use + * the JULIAN_DAY field directly, or other fields. + * @return the julian day + * @internal + */ + int32_t computeJulianDay(); + + /** + * Compute the milliseconds in the day from the fields. This is a + * value from 0 to 23:59:59.999 inclusive, unless fields are out of + * range, in which case it can be an arbitrary value. This value + * reflects local zone wall time. + * @internal + */ + double computeMillisInDay(); + + /** + * This method can assume EXTENDED_YEAR has been set. + * @param millis milliseconds of the date fields + * @param millisInDay milliseconds of the time fields; may be out + * or range. + * @param ec Output param set to failure code on function return + * when this function fails. + * @internal + */ + int32_t computeZoneOffset(double millis, double millisInDay, UErrorCode &ec); + + + /** + * Determine the best stamp in a range. + * @param start first enum to look at + * @param end last enum to look at + * @param bestSoFar stamp prior to function call + * @return the stamp value of the best stamp + * @internal + */ + int32_t newestStamp(UCalendarDateFields start, UCalendarDateFields end, int32_t bestSoFar) const; + + /** + * Marker for end of resolve set (row or group). Value for field resolution tables. + * + * @see #resolveFields + * @internal + */ + static constexpr int32_t kResolveSTOP = -1; + /** + * Value to be bitwised "ORed" against resolve table field values for remapping. + * Example: (UCAL_DATE | kResolveRemap) in 1st column will cause 'UCAL_DATE' to be returned, + * but will not examine the value of UCAL_DATE. + * Value for field resolution tables. + * + * @see #resolveFields + * @internal + */ + static constexpr int32_t kResolveRemap = 32; + + /** + * Precedence table for Dates + * @see #resolveFields + * @internal + */ + static const UFieldResolutionTable kDatePrecedence[]; + + /** + * Precedence table for Year + * @see #resolveFields + * @internal + */ + static const UFieldResolutionTable kYearPrecedence[]; + + /** + * Precedence table for Day of Week + * @see #resolveFields + * @internal + */ + static const UFieldResolutionTable kDOWPrecedence[]; + + /** + * Precedence table for Months + * @see #resolveFields + * @internal + */ + static const UFieldResolutionTable kMonthPrecedence[]; + + /** + * Given a precedence table, return the newest field combination in + * the table, or UCAL_FIELD_COUNT if none is found. + * + *

The precedence table is a 3-dimensional array of integers. It + * may be thought of as an array of groups. Each group is an array of + * lines. Each line is an array of field numbers. Within a line, if + * all fields are set, then the time stamp of the line is taken to be + * the stamp of the most recently set field. If any field of a line is + * unset, then the line fails to match. Within a group, the line with + * the newest time stamp is selected. The first field of the line is + * returned to indicate which line matched. + * + *

In some cases, it may be desirable to map a line to field that + * whose stamp is NOT examined. For example, if the best field is + * DAY_OF_WEEK then the DAY_OF_WEEK_IN_MONTH algorithm may be used. In + * order to do this, insert the value kResolveRemap | F at + * the start of the line, where F is the desired return + * field value. This field will NOT be examined; it only determines + * the return value if the other fields in the line are the newest. + * + *

If all lines of a group contain at least one unset field, then no + * line will match, and the group as a whole will fail to match. In + * that case, the next group will be processed. If all groups fail to + * match, then UCAL_FIELD_COUNT is returned. + * @internal + */ + UCalendarDateFields resolveFields(const UFieldResolutionTable *precedenceTable) const; +#endif /* U_HIDE_INTERNAL_API */ + + + /** + * @internal + */ + virtual const UFieldResolutionTable* getFieldResolutionTable() const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Return the field that is newer, either defaultField, or + * alternateField. If neither is newer or neither is set, return defaultField. + * @internal + */ + UCalendarDateFields newerField(UCalendarDateFields defaultField, UCalendarDateFields alternateField) const; +#endif /* U_HIDE_INTERNAL_API */ + + +private: + /** + * Helper function for calculating limits by trial and error + * @param field The field being investigated + * @param startValue starting (least max) value of field + * @param endValue ending (greatest max) value of field + * @param status return type + * @internal (private) + */ + int32_t getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const; + + +protected: + /** + * The flag which indicates if the current time is set in the calendar. + * @stable ICU 2.0 + */ + UBool fIsTimeSet; + + /** + * True if the fields are in sync with the currently set time of this Calendar. + * If false, then the next attempt to get the value of a field will + * force a recomputation of all fields from the current value of the time + * field. + *

+ * This should really be named areFieldsInSync, but the old name is retained + * for backward compatibility. + * @stable ICU 2.0 + */ + UBool fAreFieldsSet; + + /** + * True if all of the fields have been set. This is initially false, and set to + * true by computeFields(). + * @stable ICU 2.0 + */ + UBool fAreAllFieldsSet; + + /** + * True if all fields have been virtually set, but have not yet been + * computed. This occurs only in setTimeInMillis(). A calendar set + * to this state will compute all fields from the time if it becomes + * necessary, but otherwise will delay such computation. + * @stable ICU 3.0 + */ + UBool fAreFieldsVirtuallySet; + + /** + * Get the current time without recomputing. + * + * @return the current time without recomputing. + * @stable ICU 2.0 + */ + UDate internalGetTime(void) const { return fTime; } + + /** + * Set the current time without affecting flags or fields. + * + * @param time The time to be set + * @return the current time without recomputing. + * @stable ICU 2.0 + */ + void internalSetTime(UDate time) { fTime = time; } + + /** + * The time fields containing values into which the millis is computed. + * @stable ICU 2.0 + */ + int32_t fFields[UCAL_FIELD_COUNT]; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * The flags which tell if a specified time field for the calendar is set. + * @deprecated ICU 2.8 use (fStamp[n]!=kUnset) + */ + UBool fIsSet[UCAL_FIELD_COUNT]; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** Special values of stamp[] + * @stable ICU 2.0 + */ + enum { + kUnset = 0, + kInternallySet, + kMinimumUserStamp + }; + + /** + * Pseudo-time-stamps which specify when each field was set. There + * are two special values, UNSET and INTERNALLY_SET. Values from + * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values. + * @stable ICU 2.0 + */ + int32_t fStamp[UCAL_FIELD_COUNT]; + + /** + * Subclasses may override this method to compute several fields + * specific to each calendar system. These are: + * + *

  • ERA + *
  • YEAR + *
  • MONTH + *
  • DAY_OF_MONTH + *
  • DAY_OF_YEAR + *
  • EXTENDED_YEAR
+ * + * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields, which + * will be set when this method is called. Subclasses can also call + * the getGregorianXxx() methods to obtain Gregorian calendar + * equivalents for the given Julian day. + * + *

In addition, subclasses should compute any subclass-specific + * fields, that is, fields from BASE_FIELD_COUNT to + * getFieldCount() - 1. + * + *

The default implementation in Calendar implements + * a pure proleptic Gregorian calendar. + * @internal + */ + virtual void handleComputeFields(int32_t julianDay, UErrorCode &status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Return the extended year on the Gregorian calendar as computed by + * computeGregorianFields(). + * @internal + */ + int32_t getGregorianYear() const { + return fGregorianYear; + } + + /** + * Return the month (0-based) on the Gregorian calendar as computed by + * computeGregorianFields(). + * @internal + */ + int32_t getGregorianMonth() const { + return fGregorianMonth; + } + + /** + * Return the day of year (1-based) on the Gregorian calendar as + * computed by computeGregorianFields(). + * @internal + */ + int32_t getGregorianDayOfYear() const { + return fGregorianDayOfYear; + } + + /** + * Return the day of month (1-based) on the Gregorian calendar as + * computed by computeGregorianFields(). + * @internal + */ + int32_t getGregorianDayOfMonth() const { + return fGregorianDayOfMonth; + } +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Called by computeJulianDay. Returns the default month (0-based) for the year, + * taking year and era into account. Defaults to 0 for Gregorian, which doesn't care. + * @param eyear The extended year + * @internal + */ + virtual int32_t getDefaultMonthInYear(int32_t eyear) ; + + + /** + * Called by computeJulianDay. Returns the default day (1-based) for the month, + * taking currently-set year and era into account. Defaults to 1 for Gregorian. + * @param eyear the extended year + * @param month the month in the year + * @internal + */ + virtual int32_t getDefaultDayInMonth(int32_t eyear, int32_t month); + + //------------------------------------------------------------------------- + // Protected utility methods for use by subclasses. These are very handy + // for implementing add, roll, and computeFields. + //------------------------------------------------------------------------- + + /** + * Adjust the specified field so that it is within + * the allowable range for the date to which this calendar is set. + * For example, in a Gregorian calendar pinning the {@link #UCalendarDateFields DAY_OF_MONTH} + * field for a calendar set to April 31 would cause it to be set + * to April 30. + *

+ * Subclassing: + *
+ * This utility method is intended for use by subclasses that need to implement + * their own overrides of {@link #roll roll} and {@link #add add}. + *

+ * Note: + * pinField is implemented in terms of + * {@link #getActualMinimum getActualMinimum} + * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses + * a slow, iterative algorithm for a particular field, it would be + * unwise to attempt to call pinField for that field. If you + * really do need to do so, you should override this method to do + * something more efficient for that field. + *

+ * @param field The calendar field whose value should be pinned. + * @param status Output param set to failure code on function return + * when this function fails. + * + * @see #getActualMinimum + * @see #getActualMaximum + * @stable ICU 2.0 + */ + virtual void pinField(UCalendarDateFields field, UErrorCode& status); + + /** + * Return the week number of a day, within a period. This may be the week number in + * a year or the week number in a month. Usually this will be a value >= 1, but if + * some initial days of the period are excluded from week 1, because + * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, then + * the week number will be zero for those + * initial days. This method requires the day number and day of week for some + * known date in the period in order to determine the day of week + * on the desired day. + *

+ * Subclassing: + *
+ * This method is intended for use by subclasses in implementing their + * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods. + * It is often useful in {@link #getActualMinimum getActualMinimum} and + * {@link #getActualMaximum getActualMaximum} as well. + *

+ * This variant is handy for computing the week number of some other + * day of a period (often the first or last day of the period) when its day + * of the week is not known but the day number and day of week for some other + * day in the period (e.g. the current date) is known. + *

+ * @param desiredDay The {@link #UCalendarDateFields DAY_OF_YEAR} or + * {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired. + * Should be 1 for the first day of the period. + * + * @param dayOfPeriod The {@link #UCalendarDateFields DAY_OF_YEAR} + * or {@link #UCalendarDateFields DAY_OF_MONTH} for a day in the period whose + * {@link #UCalendarDateFields DAY_OF_WEEK} is specified by the + * knownDayOfWeek parameter. + * Should be 1 for first day of period. + * + * @param dayOfWeek The {@link #UCalendarDateFields DAY_OF_WEEK} for the day + * corresponding to the knownDayOfPeriod parameter. + * 1-based with 1=Sunday. + * + * @return The week number (one-based), or zero if the day falls before + * the first week because + * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} + * is more than one. + * + * @stable ICU 2.8 + */ + int32_t weekNumber(int32_t desiredDay, int32_t dayOfPeriod, int32_t dayOfWeek); + + +#ifndef U_HIDE_INTERNAL_API + /** + * Return the week number of a day, within a period. This may be the week number in + * a year, or the week number in a month. Usually this will be a value >= 1, but if + * some initial days of the period are excluded from week 1, because + * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, + * then the week number will be zero for those + * initial days. This method requires the day of week for the given date in order to + * determine the result. + *

+ * Subclassing: + *
+ * This method is intended for use by subclasses in implementing their + * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods. + * It is often useful in {@link #getActualMinimum getActualMinimum} and + * {@link #getActualMaximum getActualMaximum} as well. + *

+ * @param dayOfPeriod The {@link #UCalendarDateFields DAY_OF_YEAR} or + * {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired. + * Should be 1 for the first day of the period. + * + * @param dayOfWeek The {@link #UCalendarDateFields DAY_OF_WEEK} for the day + * corresponding to the dayOfPeriod parameter. + * 1-based with 1=Sunday. + * + * @return The week number (one-based), or zero if the day falls before + * the first week because + * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} + * is more than one. + * @internal + */ + inline int32_t weekNumber(int32_t dayOfPeriod, int32_t dayOfWeek); + + /** + * returns the local DOW, valid range 0..6 + * @internal + */ + int32_t getLocalDOW(); +#endif /* U_HIDE_INTERNAL_API */ + +private: + + /** + * The next available value for fStamp[] + */ + int32_t fNextStamp;// = MINIMUM_USER_STAMP; + + /** + * Recalculates the time stamp array (fStamp). + * Resets fNextStamp to lowest next stamp value. + */ + void recalculateStamp(); + + /** + * The current time set for the calendar. + */ + UDate fTime; + + /** + * @see #setLenient + */ + UBool fLenient; + + /** + * Time zone affects the time calculation done by Calendar. Calendar subclasses use + * the time zone data to produce the local time. Always set; never nullptr. + */ + TimeZone* fZone; + + /** + * Option for repeated wall time + * @see #setRepeatedWallTimeOption + */ + UCalendarWallTimeOption fRepeatedWallTime; + + /** + * Option for skipped wall time + * @see #setSkippedWallTimeOption + */ + UCalendarWallTimeOption fSkippedWallTime; + + /** + * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. They are + * used to figure out the week count for a specific date for a given locale. These + * must be set when a Calendar is constructed. For example, in US locale, + * firstDayOfWeek is SUNDAY; minimalDaysInFirstWeek is 1. They are used to figure + * out the week count for a specific date for a given locale. These must be set when + * a Calendar is constructed. + */ + UCalendarDaysOfWeek fFirstDayOfWeek; + uint8_t fMinimalDaysInFirstWeek; + UCalendarDaysOfWeek fWeekendOnset; + int32_t fWeekendOnsetMillis; + UCalendarDaysOfWeek fWeekendCease; + int32_t fWeekendCeaseMillis; + + /** + * Sets firstDayOfWeek and minimalDaysInFirstWeek. Called at Calendar construction + * time. + * + * @param desiredLocale The given locale. + * @param type The calendar type identifier, e.g: gregorian, buddhist, etc. + * @param success Indicates the status of setting the week count data from + * the resource for the given locale. Returns U_ZERO_ERROR if + * constructed successfully. + */ + void setWeekData(const Locale& desiredLocale, const char *type, UErrorCode& success); + + /** + * Recompute the time and update the status fields isTimeSet + * and areFieldsSet. Callers should check isTimeSet and only + * call this method if isTimeSet is false. + * + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid or restricted by + * leniency, this will be set to an error status. + */ + void updateTime(UErrorCode& status); + + /** + * The Gregorian year, as computed by computeGregorianFields() and + * returned by getGregorianYear(). + * @see #computeGregorianFields + */ + int32_t fGregorianYear; + + /** + * The Gregorian month, as computed by computeGregorianFields() and + * returned by getGregorianMonth(). + * @see #computeGregorianFields + */ + int32_t fGregorianMonth; + + /** + * The Gregorian day of the year, as computed by + * computeGregorianFields() and returned by getGregorianDayOfYear(). + * @see #computeGregorianFields + */ + int32_t fGregorianDayOfYear; + + /** + * The Gregorian day of the month, as computed by + * computeGregorianFields() and returned by getGregorianDayOfMonth(). + * @see #computeGregorianFields + */ + int32_t fGregorianDayOfMonth; + + /* calculations */ + + /** + * Compute the Gregorian calendar year, month, and day of month from + * the given Julian day. These values are not stored in fields, but in + * member variables gregorianXxx. Also compute the DAY_OF_WEEK and + * DOW_LOCAL fields. + */ + void computeGregorianAndDOWFields(int32_t julianDay, UErrorCode &ec); + +protected: + + /** + * Compute the Gregorian calendar year, month, and day of month from the + * Julian day. These values are not stored in fields, but in member + * variables gregorianXxx. They are used for time zone computations and by + * subclasses that are Gregorian derivatives. Subclasses may call this + * method to perform a Gregorian calendar millis->fields computation. + */ + void computeGregorianFields(int32_t julianDay, UErrorCode &ec); + +private: + + /** + * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH, + * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR, + * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the + * subclass based on the calendar system. + * + *

The YEAR_WOY field is computed simplistically. It is equal to YEAR + * most of the time, but at the year boundary it may be adjusted to YEAR-1 + * or YEAR+1 to reflect the overlap of a week into an adjacent year. In + * this case, a simple increment or decrement is performed on YEAR, even + * though this may yield an invalid YEAR value. For instance, if the YEAR + * is part of a calendar system with an N-year cycle field CYCLE, then + * incrementing the YEAR may involve incrementing CYCLE and setting YEAR + * back to 0 or 1. This is not handled by this code, and in fact cannot be + * simply handled without having subclasses define an entire parallel set of + * fields for fields larger than or equal to a year. This additional + * complexity is not warranted, since the intention of the YEAR_WOY field is + * to support ISO 8601 notation, so it will typically be used with a + * proleptic Gregorian calendar, which has no field larger than a year. + */ + void computeWeekFields(UErrorCode &ec); + + + /** + * Ensure that each field is within its valid range by calling {@link + * #validateField(int, int&)} on each field that has been set. This method + * should only be called if this calendar is not lenient. + * @see #isLenient + * @see #validateField(int, int&) + */ + void validateFields(UErrorCode &status); + + /** + * Validate a single field of this calendar given its minimum and + * maximum allowed value. If the field is out of range, + * U_ILLEGAL_ARGUMENT_ERROR will be set. Subclasses may + * use this method in their implementation of {@link + * #validateField(int, int&)}. + */ + void validateField(UCalendarDateFields field, int32_t min, int32_t max, UErrorCode& status); + + protected: +#ifndef U_HIDE_INTERNAL_API + /** + * Convert a quasi Julian date to the day of the week. The Julian date used here is + * not a true Julian date, since it is measured from midnight, not noon. Return + * value is one-based. + * + * @param julian The given Julian date number. + * @return Day number from 1..7 (SUN..SAT). + * @internal + */ + static uint8_t julianDayToDayOfWeek(double julian); +#endif /* U_HIDE_INTERNAL_API */ + + private: + char validLocale[ULOC_FULLNAME_CAPACITY]; + char actualLocale[ULOC_FULLNAME_CAPACITY]; + + public: +#if !UCONFIG_NO_SERVICE + /** + * INTERNAL FOR 2.6 -- Registration. + */ + +#ifndef U_HIDE_INTERNAL_API + /** + * Return a StringEnumeration over the locales available at the time of the call, + * including registered locales. + * @return a StringEnumeration over the locales available at the time of the call + * @internal + */ + static StringEnumeration* getAvailableLocales(void); + + /** + * Register a new Calendar factory. The factory will be adopted. + * INTERNAL in 2.6 + * + * Because ICU may choose to cache Calendars internally, this must + * be called at application startup, prior to any calls to + * Calendar::createInstance to avoid undefined behavior. + * + * @param toAdopt the factory instance to be adopted + * @param status the in/out status code, no special meanings are assigned + * @return a registry key that can be used to unregister this factory + * @internal + */ + static URegistryKey registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status); + + /** + * Unregister a previously-registered CalendarFactory using the key returned from the + * register call. Key becomes invalid after a successful call and should not be used again. + * The CalendarFactory corresponding to the key will be deleted. + * INTERNAL in 2.6 + * + * Because ICU may choose to cache Calendars internally, this should + * be called during application shutdown, after all calls to + * Calendar::createInstance to avoid undefined behavior. + * + * @param key the registry key returned by a previous call to registerFactory + * @param status the in/out status code, no special meanings are assigned + * @return true if the factory for the key was successfully unregistered + * @internal + */ + static UBool unregister(URegistryKey key, UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Multiple Calendar Implementation + * @internal + */ + friend class CalendarFactory; + + /** + * Multiple Calendar Implementation + * @internal + */ + friend class CalendarService; + + /** + * Multiple Calendar Implementation + * @internal + */ + friend class DefaultCalendarFactory; +#endif /* !UCONFIG_NO_SERVICE */ + + /** + * @return true if this calendar has a default century (i.e. 03 -> 2003) + * @internal + */ + virtual UBool haveDefaultCentury() const = 0; + + /** + * @return the start of the default century, as a UDate + * @internal + */ + virtual UDate defaultCenturyStart() const = 0; + /** + * @return the beginning year of the default century, as a year + * @internal + */ + virtual int32_t defaultCenturyStartYear() const = 0; + + /** Get the locale for this calendar object. You can choose between valid and actual locale. + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode &status) const; + + /** + * @return The related Gregorian year; will be obtained by modifying the value + * obtained by get from UCAL_EXTENDED_YEAR field + * @internal + */ + virtual int32_t getRelatedYear(UErrorCode &status) const; + + /** + * @param year The related Gregorian year to set; will be modified as necessary then + * set in UCAL_EXTENDED_YEAR field + * @internal + */ + virtual void setRelatedYear(int32_t year); + +#ifndef U_HIDE_INTERNAL_API + /** Get the locale for this calendar object. You can choose between valid and actual locale. + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale + * @internal + */ + const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const; +#endif /* U_HIDE_INTERNAL_API */ + +private: + /** + * Cast TimeZone used by this object to BasicTimeZone, or nullptr if the TimeZone + * is not an instance of BasicTimeZone. + */ + BasicTimeZone* getBasicTimeZone() const; + + /** + * Find the previous zone transition near the given time. + * @param base The base time, inclusive + * @param transitionTime Receives the result time + * @param status The error status + * @return true if a transition is found. + */ + UBool getImmediatePreviousZoneTransition(UDate base, UDate *transitionTime, UErrorCode& status) const; + +public: +#ifndef U_HIDE_INTERNAL_API + /** + * Creates a new Calendar from a Locale for the cache. + * This method does not set the time or timezone in returned calendar. + * @param locale the locale. + * @param status any error returned here. + * @return the new Calendar object with no time or timezone set. + * @internal For ICU use only. + */ + static Calendar * U_EXPORT2 makeInstance( + const Locale &locale, UErrorCode &status); + + /** + * Get the calendar type for given locale. + * @param locale the locale + * @param typeBuffer calendar type returned here + * @param typeBufferSize The size of typeBuffer in bytes. If the type + * can't fit in the buffer, this method sets status to + * U_BUFFER_OVERFLOW_ERROR + * @param status error, if any, returned here. + * @internal For ICU use only. + */ + static void U_EXPORT2 getCalendarTypeFromLocale( + const Locale &locale, + char *typeBuffer, + int32_t typeBufferSize, + UErrorCode &status); +#endif /* U_HIDE_INTERNAL_API */ +}; + +// ------------------------------------- + +inline Calendar* +Calendar::createInstance(TimeZone* zone, UErrorCode& errorCode) +{ + // since the Locale isn't specified, use the default locale + return createInstance(zone, Locale::getDefault(), errorCode); +} + +// ------------------------------------- + +inline void +Calendar::roll(UCalendarDateFields field, UBool up, UErrorCode& status) +{ + roll(field, (int32_t)(up ? +1 : -1), status); +} + +#ifndef U_HIDE_DEPRECATED_API +inline void +Calendar::roll(EDateFields field, UBool up, UErrorCode& status) +{ + roll((UCalendarDateFields) field, up, status); +} +#endif /* U_HIDE_DEPRECATED_API */ + + +// ------------------------------------- + +/** + * Fast method for subclasses. The caller must maintain fUserSetDSTOffset and + * fUserSetZoneOffset, as well as the isSet[] array. + */ + +inline void +Calendar::internalSet(UCalendarDateFields field, int32_t value) +{ + fFields[field] = value; + fStamp[field] = kInternallySet; + fIsSet[field] = true; // Remove later +} + + +#ifndef U_HIDE_INTERNAL_API +inline int32_t Calendar::weekNumber(int32_t dayOfPeriod, int32_t dayOfWeek) +{ + return weekNumber(dayOfPeriod, dayOfPeriod, dayOfWeek); +} +#endif /* U_HIDE_INTERNAL_API */ + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _CALENDAR diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/caniter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/caniter.h new file mode 100644 index 0000000000000000000000000000000000000000..035bd0e64eb9243dd855cc4d1f2f5d203e4ebaa0 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/caniter.h @@ -0,0 +1,214 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 1996-2014, International Business Machines Corporation and + * others. All Rights Reserved. + ******************************************************************************* + */ + +#ifndef CANITER_H +#define CANITER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_NORMALIZATION + +#include "unicode/uobject.h" +#include "unicode/unistr.h" + +/** + * \file + * \brief C++ API: Canonical Iterator + */ + +/** Should permutation skip characters with combining class zero + * Should be either true or false. This is a compile time option + * @stable ICU 2.4 + */ +#ifndef CANITER_SKIP_ZEROES +#define CANITER_SKIP_ZEROES true +#endif + +U_NAMESPACE_BEGIN + +class Hashtable; +class Normalizer2; +class Normalizer2Impl; + +/** + * This class allows one to iterate through all the strings that are canonically equivalent to a given + * string. For example, here are some sample results: +Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} +1: \\u0041\\u030A\\u0064\\u0307\\u0327 + = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} +2: \\u0041\\u030A\\u0064\\u0327\\u0307 + = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} +3: \\u0041\\u030A\\u1E0B\\u0327 + = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} +4: \\u0041\\u030A\\u1E11\\u0307 + = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} +5: \\u00C5\\u0064\\u0307\\u0327 + = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} +6: \\u00C5\\u0064\\u0327\\u0307 + = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} +7: \\u00C5\\u1E0B\\u0327 + = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} +8: \\u00C5\\u1E11\\u0307 + = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} +9: \\u212B\\u0064\\u0307\\u0327 + = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} +10: \\u212B\\u0064\\u0327\\u0307 + = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} +11: \\u212B\\u1E0B\\u0327 + = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} +12: \\u212B\\u1E11\\u0307 + = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} + *
Note: the code is intended for use with small strings, and is not suitable for larger ones, + * since it has not been optimized for that situation. + * Note, CanonicalIterator is not intended to be subclassed. + * @author M. Davis + * @author C++ port by V. Weinstein + * @stable ICU 2.4 + */ +class U_COMMON_API CanonicalIterator final : public UObject { +public: + /** + * Construct a CanonicalIterator object + * @param source string to get results for + * @param status Fill-in parameter which receives the status of this operation. + * @stable ICU 2.4 + */ + CanonicalIterator(const UnicodeString &source, UErrorCode &status); + + /** Destructor + * Cleans pieces + * @stable ICU 2.4 + */ + virtual ~CanonicalIterator(); + + /** + * Gets the NFD form of the current source we are iterating over. + * @return gets the source: NOTE: it is the NFD form of source + * @stable ICU 2.4 + */ + UnicodeString getSource(); + + /** + * Resets the iterator so that one can start again from the beginning. + * @stable ICU 2.4 + */ + void reset(); + + /** + * Get the next canonically equivalent string. + *
Warning: The strings are not guaranteed to be in any particular order. + * @return the next string that is canonically equivalent. A bogus string is returned when + * the iteration is done. + * @stable ICU 2.4 + */ + UnicodeString next(); + + /** + * Set a new source for this iterator. Allows object reuse. + * @param newSource the source string to iterate against. This allows the same iterator to be used + * while changing the source string, saving object creation. + * @param status Fill-in parameter which receives the status of this operation. + * @stable ICU 2.4 + */ + void setSource(const UnicodeString &newSource, UErrorCode &status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Dumb recursive implementation of permutation. + * TODO: optimize + * @param source the string to find permutations for + * @param skipZeros determine if skip zeros + * @param result the results in a set. + * @param status Fill-in parameter which receives the status of this operation. + * @internal + */ + static void U_EXPORT2 permute(UnicodeString &source, UBool skipZeros, Hashtable *result, UErrorCode &status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + +private: + // ===================== PRIVATES ============================== + // private default constructor + CanonicalIterator() = delete; + + + /** + * Copy constructor. Private for now. + * @internal (private) + */ + CanonicalIterator(const CanonicalIterator& other) = delete; + + /** + * Assignment operator. Private for now. + * @internal (private) + */ + CanonicalIterator& operator=(const CanonicalIterator& other) = delete; + + // fields + UnicodeString source; + UBool done; + + // 2 dimensional array holds the pieces of the string with + // their different canonically equivalent representations + UnicodeString **pieces; + int32_t pieces_length; + int32_t *pieces_lengths; + + // current is used in iterating to combine pieces + int32_t *current; + int32_t current_length; + + // transient fields + UnicodeString buffer; + + const Normalizer2 &nfd; + const Normalizer2Impl &nfcImpl; + + // we have a segment, in NFD. Find all the strings that are canonically equivalent to it. + UnicodeString *getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status); //private String[] getEquivalents(String segment) + + //Set getEquivalents2(String segment); + Hashtable *getEquivalents2(Hashtable *fillinResult, const char16_t *segment, int32_t segLen, UErrorCode &status); + //Hashtable *getEquivalents2(const UnicodeString &segment, int32_t segLen, UErrorCode &status); + + /** + * See if the decomposition of cp2 is at segment starting at segmentPos + * (with canonical rearrangement!) + * If so, take the remainder, and return the equivalents + */ + //Set extract(int comp, String segment, int segmentPos, StringBuffer buffer); + Hashtable *extract(Hashtable *fillinResult, UChar32 comp, const char16_t *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status); + //Hashtable *extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status); + + void cleanPieces(); + +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_NORMALIZATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/casemap.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/casemap.h new file mode 100644 index 0000000000000000000000000000000000000000..eca7cbf80a9ce53adb72394ab835fa5392b34874 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/casemap.h @@ -0,0 +1,497 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// casemap.h +// created: 2017jan12 Markus W. Scherer + +#ifndef __CASEMAP_H__ +#define __CASEMAP_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/stringpiece.h" +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Low-level C++ case mapping functions. + */ + +U_NAMESPACE_BEGIN + +class BreakIterator; +class ByteSink; +class Edits; + +/** + * Low-level C++ case mapping functions. + * + * @stable ICU 59 + */ +class U_COMMON_API CaseMap final : public UMemory { +public: + /** + * Lowercases a UTF-16 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of char16_ts). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see u_strToLower + * @stable ICU 59 + */ + static int32_t toLower( + const char *locale, uint32_t options, + const char16_t *src, int32_t srcLength, + char16_t *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + + /** + * Uppercases a UTF-16 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of char16_ts). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see u_strToUpper + * @stable ICU 59 + */ + static int32_t toUpper( + const char *locale, uint32_t options, + const char16_t *src, int32_t srcLength, + char16_t *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + +#if !UCONFIG_NO_BREAK_ITERATION + + /** + * Titlecases a UTF-16 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * Titlecasing uses a break iterator to find the first characters of words + * that are to be titlecased. It titlecases those characters and lowercases + * all others. (This can be modified with options bits.) + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT, U_EDITS_NO_RESET, + * U_TITLECASE_NO_LOWERCASE, + * U_TITLECASE_NO_BREAK_ADJUSTMENT, U_TITLECASE_ADJUST_TO_CASED, + * U_TITLECASE_WHOLE_STRING, U_TITLECASE_SENTENCES. + * @param iter A break iterator to find the first characters of words that are to be titlecased. + * It is set to the source string (setText()) + * and used one or more times for iteration (first() and next()). + * If nullptr, then a word break iterator for the locale is used + * (or something equivalent). + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of char16_ts). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see u_strToTitle + * @see ucasemap_toTitle + * @stable ICU 59 + */ + static int32_t toTitle( + const char *locale, uint32_t options, BreakIterator *iter, + const char16_t *src, int32_t srcLength, + char16_t *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + +#endif // UCONFIG_NO_BREAK_ITERATION + + /** + * Case-folds a UTF-16 string and optionally records edits. + * + * Case folding is locale-independent and not context-sensitive, + * but there is an option for whether to include or exclude mappings for dotted I + * and dotless i that are marked with 'T' in CaseFolding.txt. + * + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT, U_EDITS_NO_RESET, + * U_FOLD_CASE_DEFAULT, U_FOLD_CASE_EXCLUDE_SPECIAL_I. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of char16_ts). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see u_strFoldCase + * @stable ICU 59 + */ + static int32_t fold( + uint32_t options, + const char16_t *src, int32_t srcLength, + char16_t *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + + /** + * Lowercases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param sink A ByteSink to which the result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * + * @see ucasemap_utf8ToLower + * @stable ICU 60 + */ + static void utf8ToLower( + const char *locale, uint32_t options, + StringPiece src, ByteSink &sink, Edits *edits, + UErrorCode &errorCode); + + /** + * Uppercases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param sink A ByteSink to which the result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * + * @see ucasemap_utf8ToUpper + * @stable ICU 60 + */ + static void utf8ToUpper( + const char *locale, uint32_t options, + StringPiece src, ByteSink &sink, Edits *edits, + UErrorCode &errorCode); + +#if !UCONFIG_NO_BREAK_ITERATION + + /** + * Titlecases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * + * Titlecasing uses a break iterator to find the first characters of words + * that are to be titlecased. It titlecases those characters and lowercases + * all others. (This can be modified with options bits.) + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT, U_EDITS_NO_RESET, + * U_TITLECASE_NO_LOWERCASE, + * U_TITLECASE_NO_BREAK_ADJUSTMENT, U_TITLECASE_ADJUST_TO_CASED, + * U_TITLECASE_WHOLE_STRING, U_TITLECASE_SENTENCES. + * @param iter A break iterator to find the first characters of words that are to be titlecased. + * It is set to the source string (setUText()) + * and used one or more times for iteration (first() and next()). + * If nullptr, then a word break iterator for the locale is used + * (or something equivalent). + * @param src The original string. + * @param sink A ByteSink to which the result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * + * @see ucasemap_utf8ToTitle + * @stable ICU 60 + */ + static void utf8ToTitle( + const char *locale, uint32_t options, BreakIterator *iter, + StringPiece src, ByteSink &sink, Edits *edits, + UErrorCode &errorCode); + +#endif // UCONFIG_NO_BREAK_ITERATION + + /** + * Case-folds a UTF-8 string and optionally records edits. + * + * Case folding is locale-independent and not context-sensitive, + * but there is an option for whether to include or exclude mappings for dotted I + * and dotless i that are marked with 'T' in CaseFolding.txt. + * + * The result may be longer or shorter than the original. + * + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param sink A ByteSink to which the result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * + * @see ucasemap_utf8FoldCase + * @stable ICU 60 + */ + static void utf8Fold( + uint32_t options, + StringPiece src, ByteSink &sink, Edits *edits, + UErrorCode &errorCode); + + /** + * Lowercases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see ucasemap_utf8ToLower + * @stable ICU 59 + */ + static int32_t utf8ToLower( + const char *locale, uint32_t options, + const char *src, int32_t srcLength, + char *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + + /** + * Uppercases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see ucasemap_utf8ToUpper + * @stable ICU 59 + */ + static int32_t utf8ToUpper( + const char *locale, uint32_t options, + const char *src, int32_t srcLength, + char *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + +#if !UCONFIG_NO_BREAK_ITERATION + + /** + * Titlecases a UTF-8 string and optionally records edits. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * Titlecasing uses a break iterator to find the first characters of words + * that are to be titlecased. It titlecases those characters and lowercases + * all others. (This can be modified with options bits.) + * + * @param locale The locale ID. ("" = root locale, nullptr = default locale.) + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT, U_EDITS_NO_RESET, + * U_TITLECASE_NO_LOWERCASE, + * U_TITLECASE_NO_BREAK_ADJUSTMENT, U_TITLECASE_ADJUST_TO_CASED, + * U_TITLECASE_WHOLE_STRING, U_TITLECASE_SENTENCES. + * @param iter A break iterator to find the first characters of words that are to be titlecased. + * It is set to the source string (setUText()) + * and used one or more times for iteration (first() and next()). + * If nullptr, then a word break iterator for the locale is used + * (or something equivalent). + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see ucasemap_utf8ToTitle + * @stable ICU 59 + */ + static int32_t utf8ToTitle( + const char *locale, uint32_t options, BreakIterator *iter, + const char *src, int32_t srcLength, + char *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + +#endif // UCONFIG_NO_BREAK_ITERATION + + /** + * Case-folds a UTF-8 string and optionally records edits. + * + * Case folding is locale-independent and not context-sensitive, + * but there is an option for whether to include or exclude mappings for dotted I + * and dotless i that are marked with 'T' in CaseFolding.txt. + * + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT, U_EDITS_NO_RESET, + * U_FOLD_CASE_DEFAULT, U_FOLD_CASE_EXCLUDE_SPECIAL_I. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be nullptr and the function will only return the length of the result + * without writing any of the result string. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Reference to an in/out error code value + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful. + * When the result would be longer than destCapacity, + * the full length is returned and a U_BUFFER_OVERFLOW_ERROR is set. + * + * @see ucasemap_utf8FoldCase + * @stable ICU 59 + */ + static int32_t utf8Fold( + uint32_t options, + const char *src, int32_t srcLength, + char *dest, int32_t destCapacity, Edits *edits, + UErrorCode &errorCode); + +private: + CaseMap() = delete; + CaseMap(const CaseMap &other) = delete; + CaseMap &operator=(const CaseMap &other) = delete; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __CASEMAP_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/char16ptr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/char16ptr.h new file mode 100644 index 0000000000000000000000000000000000000000..de8182c7ada4c522ad8420d3b4fa1584b931d7b8 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/char16ptr.h @@ -0,0 +1,313 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// char16ptr.h +// created: 2017feb28 Markus W. Scherer + +#ifndef __CHAR16PTR_H__ +#define __CHAR16PTR_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include + +/** + * \file + * \brief C++ API: char16_t pointer wrappers with + * implicit conversion from bit-compatible raw pointer types. + * Also conversion functions from char16_t * to UChar * and OldUChar *. + */ + +U_NAMESPACE_BEGIN + +/** + * \def U_ALIASING_BARRIER + * Barrier for pointer anti-aliasing optimizations even across function boundaries. + * @internal + */ +#ifdef U_ALIASING_BARRIER + // Use the predefined value. +#elif (defined(__clang__) || defined(__GNUC__)) && U_PLATFORM != U_PF_BROWSER_NATIVE_CLIENT +# define U_ALIASING_BARRIER(ptr) asm volatile("" : : "rm"(ptr) : "memory") +#elif defined(U_IN_DOXYGEN) +# define U_ALIASING_BARRIER(ptr) +#endif + +/** + * char16_t * wrapper with implicit conversion from distinct but bit-compatible pointer types. + * @stable ICU 59 + */ +class U_COMMON_API Char16Ptr final { +public: + /** + * Copies the pointer. + * @param p pointer + * @stable ICU 59 + */ + inline Char16Ptr(char16_t *p); +#if !U_CHAR16_IS_TYPEDEF + /** + * Converts the pointer to char16_t *. + * @param p pointer to be converted + * @stable ICU 59 + */ + inline Char16Ptr(uint16_t *p); +#endif +#if U_SIZEOF_WCHAR_T==2 || defined(U_IN_DOXYGEN) + /** + * Converts the pointer to char16_t *. + * (Only defined if U_SIZEOF_WCHAR_T==2.) + * @param p pointer to be converted + * @stable ICU 59 + */ + inline Char16Ptr(wchar_t *p); +#endif + /** + * nullptr constructor. + * @param p nullptr + * @stable ICU 59 + */ + inline Char16Ptr(std::nullptr_t p); + /** + * Destructor. + * @stable ICU 59 + */ + inline ~Char16Ptr(); + + /** + * Pointer access. + * @return the wrapped pointer + * @stable ICU 59 + */ + inline char16_t *get() const; + /** + * char16_t pointer access via type conversion (e.g., static_cast). + * @return the wrapped pointer + * @stable ICU 59 + */ + inline operator char16_t *() const { return get(); } + +private: + Char16Ptr() = delete; + +#ifdef U_ALIASING_BARRIER + template static char16_t *cast(T *t) { + U_ALIASING_BARRIER(t); + return reinterpret_cast(t); + } + + char16_t *p_; +#else + union { + char16_t *cp; + uint16_t *up; + wchar_t *wp; + } u_; +#endif +}; + +/// \cond +#ifdef U_ALIASING_BARRIER + +Char16Ptr::Char16Ptr(char16_t *p) : p_(p) {} +#if !U_CHAR16_IS_TYPEDEF +Char16Ptr::Char16Ptr(uint16_t *p) : p_(cast(p)) {} +#endif +#if U_SIZEOF_WCHAR_T==2 +Char16Ptr::Char16Ptr(wchar_t *p) : p_(cast(p)) {} +#endif +Char16Ptr::Char16Ptr(std::nullptr_t p) : p_(p) {} +Char16Ptr::~Char16Ptr() { + U_ALIASING_BARRIER(p_); +} + +char16_t *Char16Ptr::get() const { return p_; } + +#else + +Char16Ptr::Char16Ptr(char16_t *p) { u_.cp = p; } +#if !U_CHAR16_IS_TYPEDEF +Char16Ptr::Char16Ptr(uint16_t *p) { u_.up = p; } +#endif +#if U_SIZEOF_WCHAR_T==2 +Char16Ptr::Char16Ptr(wchar_t *p) { u_.wp = p; } +#endif +Char16Ptr::Char16Ptr(std::nullptr_t p) { u_.cp = p; } +Char16Ptr::~Char16Ptr() {} + +char16_t *Char16Ptr::get() const { return u_.cp; } + +#endif +/// \endcond + +/** + * const char16_t * wrapper with implicit conversion from distinct but bit-compatible pointer types. + * @stable ICU 59 + */ +class U_COMMON_API ConstChar16Ptr final { +public: + /** + * Copies the pointer. + * @param p pointer + * @stable ICU 59 + */ + inline ConstChar16Ptr(const char16_t *p); +#if !U_CHAR16_IS_TYPEDEF + /** + * Converts the pointer to char16_t *. + * @param p pointer to be converted + * @stable ICU 59 + */ + inline ConstChar16Ptr(const uint16_t *p); +#endif +#if U_SIZEOF_WCHAR_T==2 || defined(U_IN_DOXYGEN) + /** + * Converts the pointer to char16_t *. + * (Only defined if U_SIZEOF_WCHAR_T==2.) + * @param p pointer to be converted + * @stable ICU 59 + */ + inline ConstChar16Ptr(const wchar_t *p); +#endif + /** + * nullptr constructor. + * @param p nullptr + * @stable ICU 59 + */ + inline ConstChar16Ptr(const std::nullptr_t p); + + /** + * Destructor. + * @stable ICU 59 + */ + inline ~ConstChar16Ptr(); + + /** + * Pointer access. + * @return the wrapped pointer + * @stable ICU 59 + */ + inline const char16_t *get() const; + /** + * char16_t pointer access via type conversion (e.g., static_cast). + * @return the wrapped pointer + * @stable ICU 59 + */ + inline operator const char16_t *() const { return get(); } + +private: + ConstChar16Ptr() = delete; + +#ifdef U_ALIASING_BARRIER + template static const char16_t *cast(const T *t) { + U_ALIASING_BARRIER(t); + return reinterpret_cast(t); + } + + const char16_t *p_; +#else + union { + const char16_t *cp; + const uint16_t *up; + const wchar_t *wp; + } u_; +#endif +}; + +/// \cond +#ifdef U_ALIASING_BARRIER + +ConstChar16Ptr::ConstChar16Ptr(const char16_t *p) : p_(p) {} +#if !U_CHAR16_IS_TYPEDEF +ConstChar16Ptr::ConstChar16Ptr(const uint16_t *p) : p_(cast(p)) {} +#endif +#if U_SIZEOF_WCHAR_T==2 +ConstChar16Ptr::ConstChar16Ptr(const wchar_t *p) : p_(cast(p)) {} +#endif +ConstChar16Ptr::ConstChar16Ptr(const std::nullptr_t p) : p_(p) {} +ConstChar16Ptr::~ConstChar16Ptr() { + U_ALIASING_BARRIER(p_); +} + +const char16_t *ConstChar16Ptr::get() const { return p_; } + +#else + +ConstChar16Ptr::ConstChar16Ptr(const char16_t *p) { u_.cp = p; } +#if !U_CHAR16_IS_TYPEDEF +ConstChar16Ptr::ConstChar16Ptr(const uint16_t *p) { u_.up = p; } +#endif +#if U_SIZEOF_WCHAR_T==2 +ConstChar16Ptr::ConstChar16Ptr(const wchar_t *p) { u_.wp = p; } +#endif +ConstChar16Ptr::ConstChar16Ptr(const std::nullptr_t p) { u_.cp = p; } +ConstChar16Ptr::~ConstChar16Ptr() {} + +const char16_t *ConstChar16Ptr::get() const { return u_.cp; } + +#endif +/// \endcond + +/** + * Converts from const char16_t * to const UChar *. + * Includes an aliasing barrier if available. + * @param p pointer + * @return p as const UChar * + * @stable ICU 59 + */ +inline const UChar *toUCharPtr(const char16_t *p) { +#ifdef U_ALIASING_BARRIER + U_ALIASING_BARRIER(p); +#endif + return reinterpret_cast(p); +} + +/** + * Converts from char16_t * to UChar *. + * Includes an aliasing barrier if available. + * @param p pointer + * @return p as UChar * + * @stable ICU 59 + */ +inline UChar *toUCharPtr(char16_t *p) { +#ifdef U_ALIASING_BARRIER + U_ALIASING_BARRIER(p); +#endif + return reinterpret_cast(p); +} + +/** + * Converts from const char16_t * to const OldUChar *. + * Includes an aliasing barrier if available. + * @param p pointer + * @return p as const OldUChar * + * @stable ICU 59 + */ +inline const OldUChar *toOldUCharPtr(const char16_t *p) { +#ifdef U_ALIASING_BARRIER + U_ALIASING_BARRIER(p); +#endif + return reinterpret_cast(p); +} + +/** + * Converts from char16_t * to OldUChar *. + * Includes an aliasing barrier if available. + * @param p pointer + * @return p as OldUChar * + * @stable ICU 59 + */ +inline OldUChar *toOldUCharPtr(char16_t *p) { +#ifdef U_ALIASING_BARRIER + U_ALIASING_BARRIER(p); +#endif + return reinterpret_cast(p); +} + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __CHAR16PTR_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/chariter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/chariter.h new file mode 100644 index 0000000000000000000000000000000000000000..45f4d984c74d3518c2f0cc3f6adf7cd43dcf1bcf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/chariter.h @@ -0,0 +1,734 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************** +* +* Copyright (C) 1997-2011, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************** +*/ + +#ifndef CHARITER_H +#define CHARITER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +/** + * \file + * \brief C++ API: Character Iterator + */ + +U_NAMESPACE_BEGIN +/** + * Abstract class that defines an API for forward-only iteration + * on text objects. + * This is a minimal interface for iteration without random access + * or backwards iteration. It is especially useful for wrapping + * streams with converters into an object for collation or + * normalization. + * + *

Characters can be accessed in two ways: as code units or as + * code points. + * Unicode code points are 21-bit integers and are the scalar values + * of Unicode characters. ICU uses the type UChar32 for them. + * Unicode code units are the storage units of a given + * Unicode/UCS Transformation Format (a character encoding scheme). + * With UTF-16, all code points can be represented with either one + * or two code units ("surrogates"). + * String storage is typically based on code units, while properties + * of characters are typically determined using code point values. + * Some processes may be designed to work with sequences of code units, + * or it may be known that all characters that are important to an + * algorithm can be represented with single code units. + * Other processes will need to use the code point access functions.

+ * + *

ForwardCharacterIterator provides nextPostInc() to access + * a code unit and advance an internal position into the text object, + * similar to a return text[position++].
+ * It provides next32PostInc() to access a code point and advance an internal + * position.

+ * + *

next32PostInc() assumes that the current position is that of + * the beginning of a code point, i.e., of its first code unit. + * After next32PostInc(), this will be true again. + * In general, access to code units and code points in the same + * iteration loop should not be mixed. In UTF-16, if the current position + * is on a second code unit (Low Surrogate), then only that code unit + * is returned even by next32PostInc().

+ * + *

For iteration with either function, there are two ways to + * check for the end of the iteration. When there are no more + * characters in the text object: + *

    + *
  • The hasNext() function returns false.
  • + *
  • nextPostInc() and next32PostInc() return DONE + * when one attempts to read beyond the end of the text object.
  • + *
+ * + * Example: + * \code + * void function1(ForwardCharacterIterator &it) { + * UChar32 c; + * while(it.hasNext()) { + * c=it.next32PostInc(); + * // use c + * } + * } + * + * void function1(ForwardCharacterIterator &it) { + * char16_t c; + * while((c=it.nextPostInc())!=ForwardCharacterIterator::DONE) { + * // use c + * } + * } + * \endcode + *

+ * + * @stable ICU 2.0 + */ +class U_COMMON_API ForwardCharacterIterator : public UObject { +public: + /** + * Value returned by most of ForwardCharacterIterator's functions + * when the iterator has reached the limits of its iteration. + * @stable ICU 2.0 + */ + enum { DONE = 0xffff }; + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~ForwardCharacterIterator(); + + /** + * Returns true when both iterators refer to the same + * character in the same character-storage object. + * @param that The ForwardCharacterIterator to be compared for equality + * @return true when both iterators refer to the same + * character in the same character-storage object + * @stable ICU 2.0 + */ + virtual bool operator==(const ForwardCharacterIterator& that) const = 0; + + /** + * Returns true when the iterators refer to different + * text-storage objects, or to different characters in the + * same text-storage object. + * @param that The ForwardCharacterIterator to be compared for inequality + * @return true when the iterators refer to different + * text-storage objects, or to different characters in the + * same text-storage object + * @stable ICU 2.0 + */ + inline bool operator!=(const ForwardCharacterIterator& that) const; + + /** + * Generates a hash code for this iterator. + * @return the hash code. + * @stable ICU 2.0 + */ + virtual int32_t hashCode(void) const = 0; + + /** + * Returns a UClassID for this ForwardCharacterIterator ("poor man's + * RTTI").

Despite the fact that this function is public, + * DO NOT CONSIDER IT PART OF CHARACTERITERATOR'S API! + * @return a UClassID for this ForwardCharacterIterator + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Gets the current code unit for returning and advances to the next code unit + * in the iteration range + * (toward endIndex()). If there are + * no more code units to return, returns DONE. + * @return the current code unit. + * @stable ICU 2.0 + */ + virtual char16_t nextPostInc(void) = 0; + + /** + * Gets the current code point for returning and advances to the next code point + * in the iteration range + * (toward endIndex()). If there are + * no more code points to return, returns DONE. + * @return the current code point. + * @stable ICU 2.0 + */ + virtual UChar32 next32PostInc(void) = 0; + + /** + * Returns false if there are no more code units or code points + * at or after the current position in the iteration range. + * This is used with nextPostInc() or next32PostInc() in forward + * iteration. + * @returns false if there are no more code units or code points + * at or after the current position in the iteration range. + * @stable ICU 2.0 + */ + virtual UBool hasNext() = 0; + +protected: + /** Default constructor to be overridden in the implementing class. @stable ICU 2.0*/ + ForwardCharacterIterator(); + + /** Copy constructor to be overridden in the implementing class. @stable ICU 2.0*/ + ForwardCharacterIterator(const ForwardCharacterIterator &other); + + /** + * Assignment operator to be overridden in the implementing class. + * @stable ICU 2.0 + */ + ForwardCharacterIterator &operator=(const ForwardCharacterIterator&) { return *this; } +}; + +/** + * Abstract class that defines an API for iteration + * on text objects. + * This is an interface for forward and backward iteration + * and random access into a text object. + * + *

The API provides backward compatibility to the Java and older ICU + * CharacterIterator classes but extends them significantly: + *

    + *
  1. CharacterIterator is now a subclass of ForwardCharacterIterator.
  2. + *
  3. While the old API functions provided forward iteration with + * "pre-increment" semantics, the new one also provides functions + * with "post-increment" semantics. They are more efficient and should + * be the preferred iterator functions for new implementations. + * The backward iteration always had "pre-decrement" semantics, which + * are efficient.
  4. + *
  5. Just like ForwardCharacterIterator, it provides access to + * both code units and code points. Code point access versions are available + * for the old and the new iteration semantics.
  6. + *
  7. There are new functions for setting and moving the current position + * without returning a character, for efficiency.
  8. + *
+ * + * See ForwardCharacterIterator for examples for using the new forward iteration + * functions. For backward iteration, there is also a hasPrevious() function + * that can be used analogously to hasNext(). + * The old functions work as before and are shown below.

+ * + *

Examples for some of the new functions:

+ * + * Forward iteration with hasNext(): + * \code + * void forward1(CharacterIterator &it) { + * UChar32 c; + * for(it.setToStart(); it.hasNext();) { + * c=it.next32PostInc(); + * // use c + * } + * } + * \endcode + * Forward iteration more similar to loops with the old forward iteration, + * showing a way to convert simple for() loops: + * \code + * void forward2(CharacterIterator &it) { + * char16_t c; + * for(c=it.firstPostInc(); c!=CharacterIterator::DONE; c=it.nextPostInc()) { + * // use c + * } + * } + * \endcode + * Backward iteration with setToEnd() and hasPrevious(): + * \code + * void backward1(CharacterIterator &it) { + * UChar32 c; + * for(it.setToEnd(); it.hasPrevious();) { + * c=it.previous32(); + * // use c + * } + * } + * \endcode + * Backward iteration with a more traditional for() loop: + * \code + * void backward2(CharacterIterator &it) { + * char16_t c; + * for(c=it.last(); c!=CharacterIterator::DONE; c=it.previous()) { + * // use c + * } + * } + * \endcode + * + * Example for random access: + * \code + * void random(CharacterIterator &it) { + * // set to the third code point from the beginning + * it.move32(3, CharacterIterator::kStart); + * // get a code point from here without moving the position + * UChar32 c=it.current32(); + * // get the position + * int32_t pos=it.getIndex(); + * // get the previous code unit + * char16_t u=it.previous(); + * // move back one more code unit + * it.move(-1, CharacterIterator::kCurrent); + * // set the position back to where it was + * // and read the same code point c and move beyond it + * it.setIndex(pos); + * if(c!=it.next32PostInc()) { + * exit(1); // CharacterIterator inconsistent + * } + * } + * \endcode + * + *

Examples, especially for the old API:

+ * + * Function processing characters, in this example simple output + *
+ * \code
+ *  void processChar( char16_t c )
+ *  {
+ *      cout << " " << c;
+ *  }
+ * \endcode
+ * 
+ * Traverse the text from start to finish + *
 
+ * \code
+ *  void traverseForward(CharacterIterator& iter)
+ *  {
+ *      for(char16_t c = iter.first(); c != CharacterIterator::DONE; c = iter.next()) {
+ *          processChar(c);
+ *      }
+ *  }
+ * \endcode
+ * 
+ * Traverse the text backwards, from end to start + *
+ * \code
+ *  void traverseBackward(CharacterIterator& iter)
+ *  {
+ *      for(char16_t c = iter.last(); c != CharacterIterator::DONE; c = iter.previous()) {
+ *          processChar(c);
+ *      }
+ *  }
+ * \endcode
+ * 
+ * Traverse both forward and backward from a given position in the text. + * Calls to notBoundary() in this example represents some additional stopping criteria. + *
+ * \code
+ * void traverseOut(CharacterIterator& iter, int32_t pos)
+ * {
+ *      char16_t c;
+ *      for (c = iter.setIndex(pos);
+ *      c != CharacterIterator::DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
+ *          c = iter.next()) {}
+ *      int32_t end = iter.getIndex();
+ *      for (c = iter.setIndex(pos);
+ *          c != CharacterIterator::DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
+ *          c = iter.previous()) {}
+ *      int32_t start = iter.getIndex() + 1;
+ *  
+ *      cout << "start: " << start << " end: " << end << endl;
+ *      for (c = iter.setIndex(start); iter.getIndex() < end; c = iter.next() ) {
+ *          processChar(c);
+ *     }
+ *  }
+ * \endcode
+ * 
+ * Creating a StringCharacterIterator and calling the test functions + *
+ * \code
+ *  void CharacterIterator_Example( void )
+ *   {
+ *       cout << endl << "===== CharacterIterator_Example: =====" << endl;
+ *       UnicodeString text("Ein kleiner Satz.");
+ *       StringCharacterIterator iterator(text);
+ *       cout << "----- traverseForward: -----------" << endl;
+ *       traverseForward( iterator );
+ *       cout << endl << endl << "----- traverseBackward: ----------" << endl;
+ *       traverseBackward( iterator );
+ *       cout << endl << endl << "----- traverseOut: ---------------" << endl;
+ *       traverseOut( iterator, 7 );
+ *       cout << endl << endl << "-----" << endl;
+ *   }
+ * \endcode
+ * 
+ * + * @stable ICU 2.0 + */ +class U_COMMON_API CharacterIterator : public ForwardCharacterIterator { +public: + /** + * Origin enumeration for the move() and move32() functions. + * @stable ICU 2.0 + */ + enum EOrigin { kStart, kCurrent, kEnd }; + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~CharacterIterator(); + + /** + * Returns a pointer to a new CharacterIterator of the same + * concrete class as this one, and referring to the same + * character in the same text-storage object as this one. The + * caller is responsible for deleting the new clone. + * @return a pointer to a new CharacterIterator + * @stable ICU 2.0 + */ + virtual CharacterIterator* clone() const = 0; + + /** + * Sets the iterator to refer to the first code unit in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with next(). + * @return the first code unit in its iteration range. + * @stable ICU 2.0 + */ + virtual char16_t first(void) = 0; + + /** + * Sets the iterator to refer to the first code unit in its + * iteration range, returns that code unit, and moves the position + * to the second code unit. This is an alternative to setToStart() + * for forward iteration with nextPostInc(). + * @return the first code unit in its iteration range. + * @stable ICU 2.0 + */ + virtual char16_t firstPostInc(void); + + /** + * Sets the iterator to refer to the first code point in its + * iteration range, and returns that code unit, + * This can be used to begin an iteration with next32(). + * Note that an iteration with next32PostInc(), beginning with, + * e.g., setToStart() or firstPostInc(), is more efficient. + * @return the first code point in its iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 first32(void) = 0; + + /** + * Sets the iterator to refer to the first code point in its + * iteration range, returns that code point, and moves the position + * to the second code point. This is an alternative to setToStart() + * for forward iteration with next32PostInc(). + * @return the first code point in its iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 first32PostInc(void); + + /** + * Sets the iterator to refer to the first code unit or code point in its + * iteration range. This can be used to begin a forward + * iteration with nextPostInc() or next32PostInc(). + * @return the start position of the iteration range + * @stable ICU 2.0 + */ + inline int32_t setToStart(); + + /** + * Sets the iterator to refer to the last code unit in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with previous(). + * @return the last code unit. + * @stable ICU 2.0 + */ + virtual char16_t last(void) = 0; + + /** + * Sets the iterator to refer to the last code point in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with previous32(). + * @return the last code point. + * @stable ICU 2.0 + */ + virtual UChar32 last32(void) = 0; + + /** + * Sets the iterator to the end of its iteration range, just behind + * the last code unit or code point. This can be used to begin a backward + * iteration with previous() or previous32(). + * @return the end position of the iteration range + * @stable ICU 2.0 + */ + inline int32_t setToEnd(); + + /** + * Sets the iterator to refer to the "position"-th code unit + * in the text-storage object the iterator refers to, and + * returns that code unit. + * @param position the "position"-th code unit in the text-storage object + * @return the "position"-th code unit. + * @stable ICU 2.0 + */ + virtual char16_t setIndex(int32_t position) = 0; + + /** + * Sets the iterator to refer to the beginning of the code point + * that contains the "position"-th code unit + * in the text-storage object the iterator refers to, and + * returns that code point. + * The current position is adjusted to the beginning of the code point + * (its first code unit). + * @param position the "position"-th code unit in the text-storage object + * @return the "position"-th code point. + * @stable ICU 2.0 + */ + virtual UChar32 setIndex32(int32_t position) = 0; + + /** + * Returns the code unit the iterator currently refers to. + * @return the current code unit. + * @stable ICU 2.0 + */ + virtual char16_t current(void) const = 0; + + /** + * Returns the code point the iterator currently refers to. + * @return the current code point. + * @stable ICU 2.0 + */ + virtual UChar32 current32(void) const = 0; + + /** + * Advances to the next code unit in the iteration range + * (toward endIndex()), and returns that code unit. If there are + * no more code units to return, returns DONE. + * @return the next code unit. + * @stable ICU 2.0 + */ + virtual char16_t next(void) = 0; + + /** + * Advances to the next code point in the iteration range + * (toward endIndex()), and returns that code point. If there are + * no more code points to return, returns DONE. + * Note that iteration with "pre-increment" semantics is less + * efficient than iteration with "post-increment" semantics + * that is provided by next32PostInc(). + * @return the next code point. + * @stable ICU 2.0 + */ + virtual UChar32 next32(void) = 0; + + /** + * Advances to the previous code unit in the iteration range + * (toward startIndex()), and returns that code unit. If there are + * no more code units to return, returns DONE. + * @return the previous code unit. + * @stable ICU 2.0 + */ + virtual char16_t previous(void) = 0; + + /** + * Advances to the previous code point in the iteration range + * (toward startIndex()), and returns that code point. If there are + * no more code points to return, returns DONE. + * @return the previous code point. + * @stable ICU 2.0 + */ + virtual UChar32 previous32(void) = 0; + + /** + * Returns false if there are no more code units or code points + * before the current position in the iteration range. + * This is used with previous() or previous32() in backward + * iteration. + * @return false if there are no more code units or code points + * before the current position in the iteration range, return true otherwise. + * @stable ICU 2.0 + */ + virtual UBool hasPrevious() = 0; + + /** + * Returns the numeric index in the underlying text-storage + * object of the character returned by first(). Since it's + * possible to create an iterator that iterates across only + * part of a text-storage object, this number isn't + * necessarily 0. + * @returns the numeric index in the underlying text-storage + * object of the character returned by first(). + * @stable ICU 2.0 + */ + inline int32_t startIndex(void) const; + + /** + * Returns the numeric index in the underlying text-storage + * object of the position immediately BEYOND the character + * returned by last(). + * @return the numeric index in the underlying text-storage + * object of the position immediately BEYOND the character + * returned by last(). + * @stable ICU 2.0 + */ + inline int32_t endIndex(void) const; + + /** + * Returns the numeric index in the underlying text-storage + * object of the character the iterator currently refers to + * (i.e., the character returned by current()). + * @return the numeric index in the text-storage object of + * the character the iterator currently refers to + * @stable ICU 2.0 + */ + inline int32_t getIndex(void) const; + + /** + * Returns the length of the entire text in the underlying + * text-storage object. + * @return the length of the entire text in the text-storage object + * @stable ICU 2.0 + */ + inline int32_t getLength() const; + + /** + * Moves the current position relative to the start or end of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code units forward + * or backward by specifying a positive or negative delta. + * @param delta the position relative to origin. A positive delta means forward; + * a negative delta means backward. + * @param origin Origin enumeration {kStart, kCurrent, kEnd} + * @return the new position + * @stable ICU 2.0 + */ + virtual int32_t move(int32_t delta, EOrigin origin) = 0; + + /** + * Moves the current position relative to the start or end of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code points forward + * or backward by specifying a positive or negative delta. + * @param delta the position relative to origin. A positive delta means forward; + * a negative delta means backward. + * @param origin Origin enumeration {kStart, kCurrent, kEnd} + * @return the new position + * @stable ICU 2.0 + */ +#ifdef move32 + // One of the system headers right now is sometimes defining a conflicting macro we don't use +#undef move32 +#endif + virtual int32_t move32(int32_t delta, EOrigin origin) = 0; + + /** + * Copies the text under iteration into the UnicodeString + * referred to by "result". + * @param result Receives a copy of the text under iteration. + * @stable ICU 2.0 + */ + virtual void getText(UnicodeString& result) = 0; + +protected: + /** + * Empty constructor. + * @stable ICU 2.0 + */ + CharacterIterator(); + + /** + * Constructor, just setting the length field in this base class. + * @stable ICU 2.0 + */ + CharacterIterator(int32_t length); + + /** + * Constructor, just setting the length and position fields in this base class. + * @stable ICU 2.0 + */ + CharacterIterator(int32_t length, int32_t position); + + /** + * Constructor, just setting the length, start, end, and position fields in this base class. + * @stable ICU 2.0 + */ + CharacterIterator(int32_t length, int32_t textBegin, int32_t textEnd, int32_t position); + + /** + * Copy constructor. + * + * @param that The CharacterIterator to be copied + * @stable ICU 2.0 + */ + CharacterIterator(const CharacterIterator &that); + + /** + * Assignment operator. Sets this CharacterIterator to have the same behavior, + * as the one passed in. + * @param that The CharacterIterator passed in. + * @return the newly set CharacterIterator. + * @stable ICU 2.0 + */ + CharacterIterator &operator=(const CharacterIterator &that); + + /** + * Base class text length field. + * Necessary this for correct getText() and hashCode(). + * @stable ICU 2.0 + */ + int32_t textLength; + + /** + * Base class field for the current position. + * @stable ICU 2.0 + */ + int32_t pos; + + /** + * Base class field for the start of the iteration range. + * @stable ICU 2.0 + */ + int32_t begin; + + /** + * Base class field for the end of the iteration range. + * @stable ICU 2.0 + */ + int32_t end; +}; + +inline bool +ForwardCharacterIterator::operator!=(const ForwardCharacterIterator& that) const { + return !operator==(that); +} + +inline int32_t +CharacterIterator::setToStart() { + return move(0, kStart); +} + +inline int32_t +CharacterIterator::setToEnd() { + return move(0, kEnd); +} + +inline int32_t +CharacterIterator::startIndex(void) const { + return begin; +} + +inline int32_t +CharacterIterator::endIndex(void) const { + return end; +} + +inline int32_t +CharacterIterator::getIndex(void) const { + return pos; +} + +inline int32_t +CharacterIterator::getLength(void) const { + return textLength; +} + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/choicfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/choicfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..429fa0cebd82c307a2ddb15b2020a99ebf77530a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/choicfmt.h @@ -0,0 +1,601 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2013, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File CHOICFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/20/97 helena Finished first cut of implementation and got rid +* of nextDouble/previousDouble and replaced with +* boolean array. +* 4/10/97 aliu Clean up. Modified to work on AIX. +* 8/6/97 nos Removed overloaded constructor, member var 'buffer'. +* 07/22/98 stephen Removed operator!= (implemented in Format) +******************************************************************************** +*/ + +#ifndef CHOICFMT_H +#define CHOICFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Choice Format. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/fieldpos.h" +#include "unicode/format.h" +#include "unicode/messagepattern.h" +#include "unicode/numfmt.h" +#include "unicode/unistr.h" + +#ifndef U_HIDE_DEPRECATED_API + +U_NAMESPACE_BEGIN + +class MessageFormat; + +/** + * ChoiceFormat converts between ranges of numeric values and strings for those ranges. + * The strings must conform to the MessageFormat pattern syntax. + * + *

ChoiceFormat is probably not what you need. + * Please use MessageFormat + * with plural arguments for proper plural selection, + * and select arguments for simple selection among a fixed set of choices!

+ * + *

A ChoiceFormat splits + * the real number line \htmlonly-∞ to + * +∞\endhtmlonly into two + * or more contiguous ranges. Each range is mapped to a + * string.

+ * + *

ChoiceFormat was originally intended + * for displaying grammatically correct + * plurals such as "There is one file." vs. "There are 2 files." + * However, plural rules for many languages + * are too complex for the capabilities of ChoiceFormat, + * and its requirement of specifying the precise rules for each message + * is unmanageable for translators.

+ * + *

There are two methods of defining a ChoiceFormat; both + * are equivalent. The first is by using a string pattern. This is the + * preferred method in most cases. The second method is through direct + * specification of the arrays that logically make up the + * ChoiceFormat.

+ * + *

Note: Typically, choice formatting is done (if done at all) via MessageFormat + * with a choice argument type, + * rather than using a stand-alone ChoiceFormat.

+ * + *
Patterns and Their Interpretation
+ * + *

The pattern string defines the range boundaries and the strings for each number range. + * Syntax: + *

+ * choiceStyle = number separator message ('|' number separator message)*
+ * number = normal_number | ['-'] \htmlonly∞\endhtmlonly (U+221E, infinity)
+ * normal_number = double value (unlocalized ASCII string)
+ * separator = less_than | less_than_or_equal
+ * less_than = '<'
+ * less_than_or_equal = '#' | \htmlonly≤\endhtmlonly (U+2264)
+ * message: see {@link MessageFormat}
+ * 
+ * Pattern_White_Space between syntax elements is ignored, except + * around each range's sub-message.

+ * + *

Each numeric sub-range extends from the current range's number + * to the next range's number. + * The number itself is included in its range if a less_than_or_equal sign is used, + * and excluded from its range (and instead included in the previous range) + * if a less_than sign is used.

+ * + *

When a ChoiceFormat is constructed from + * arrays of numbers, closure flags and strings, + * they are interpreted just like + * the sequence of (number separator string) in an equivalent pattern string. + * closure[i]==true corresponds to a less_than separator sign. + * The equivalent pattern string will be constructed automatically.

+ * + *

During formatting, a number is mapped to the first range + * where the number is not greater than the range's upper limit. + * That range's message string is returned. A NaN maps to the very first range.

+ * + *

During parsing, a range is selected for the longest match of + * any range's message. That range's number is returned, ignoring the separator/closure. + * Only a simple string match is performed, without parsing of arguments that + * might be specified in the message strings.

+ * + *

Note that the first range's number is ignored in formatting + * but may be returned from parsing.

+ * + *
Examples
+ * + *

Here is an example of two arrays that map the number + * 1..7 to the English day of the week abbreviations + * Sun..Sat. No closures array is given; this is the same as + * specifying all closures to be false.

+ * + *
    {1,2,3,4,5,6,7},
+ *     {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}
+ * + *

Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1, + * +Inf] to three strings. That is, the number line is split into three + * ranges: x < 1.0, x = 1.0, and x > 1.0. + * (The round parentheses in the notation above indicate an exclusive boundary, + * like the turned bracket in European notation: [-Inf, 1) == [-Inf, 1[ )

+ * + *
    {0, 1, 1},
+ *     {false, false, true},
+ *     {"no files", "one file", "many files"}
+ * + *

Here is an example that shows formatting and parsing:

+ * + * \code + * #include + * #include + * #include + * + * int main(int argc, char *argv[]) { + * double limits[] = {1,2,3,4,5,6,7}; + * UnicodeString monthNames[] = { + * "Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; + * ChoiceFormat fmt(limits, monthNames, 7); + * UnicodeString str; + * char buf[256]; + * for (double x = 1.0; x <= 8.0; x += 1.0) { + * fmt.format(x, str); + * str.extract(0, str.length(), buf, 256, ""); + * str.truncate(0); + * cout << x << " -> " + * << buf << endl; + * } + * cout << endl; + * return 0; + * } + * \endcode + * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + * + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ +class U_I18N_API ChoiceFormat: public NumberFormat { +public: + /** + * Constructs a new ChoiceFormat from the pattern string. + * + * @param pattern Pattern used to construct object. + * @param status Output param to receive success code. If the + * pattern cannot be parsed, set to failure code. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + ChoiceFormat(const UnicodeString& pattern, + UErrorCode& status); + + + /** + * Constructs a new ChoiceFormat with the given limits and message strings. + * All closure flags default to false, + * equivalent to less_than_or_equal separators. + * + * Copies the limits and formats instead of adopting them. + * + * @param limits Array of limit values. + * @param formats Array of formats. + * @param count Size of 'limits' and 'formats' arrays. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + ChoiceFormat(const double* limits, + const UnicodeString* formats, + int32_t count ); + + /** + * Constructs a new ChoiceFormat with the given limits, closure flags and message strings. + * + * Copies the limits and formats instead of adopting them. + * + * @param limits Array of limit values + * @param closures Array of booleans specifying whether each + * element of 'limits' is open or closed. If false, then the + * corresponding limit number is a member of its range. + * If true, then the limit number belongs to the previous range it. + * @param formats Array of formats + * @param count Size of 'limits', 'closures', and 'formats' arrays + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + ChoiceFormat(const double* limits, + const UBool* closures, + const UnicodeString* formats, + int32_t count); + + /** + * Copy constructor. + * + * @param that ChoiceFormat object to be copied from + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + ChoiceFormat(const ChoiceFormat& that); + + /** + * Assignment operator. + * + * @param that ChoiceFormat object to be copied + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + const ChoiceFormat& operator=(const ChoiceFormat& that); + + /** + * Destructor. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual ~ChoiceFormat(); + + /** + * Clones this Format object. The caller owns the + * result and must delete it when done. + * + * @return a copy of this object + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual ChoiceFormat* clone() const override; + + /** + * Returns true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * + * @param other ChoiceFormat object to be compared + * @return true if other is the same as this. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual bool operator==(const Format& other) const override; + + /** + * Sets the pattern. + * @param pattern The pattern to be applied. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual void applyPattern(const UnicodeString& pattern, + UErrorCode& status); + + /** + * Sets the pattern. + * @param pattern The pattern to be applied. + * @param parseError Struct to receive information on position + * of error if an error is encountered + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual void applyPattern(const UnicodeString& pattern, + UParseError& parseError, + UErrorCode& status); + /** + * Gets the pattern. + * + * @param pattern Output param which will receive the pattern + * Previous contents are deleted. + * @return A reference to 'pattern' + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UnicodeString& toPattern(UnicodeString &pattern) const; + + /** + * Sets the choices to be used in formatting. + * For details see the constructor with the same parameter list. + * + * @param limitsToCopy Contains the top value that you want + * parsed with that format,and should be in + * ascending sorted order. When formatting X, + * the choice will be the i, where limit[i] + * <= X < limit[i+1]. + * @param formatsToCopy The format strings you want to use for each limit. + * @param count The size of the above arrays. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual void setChoices(const double* limitsToCopy, + const UnicodeString* formatsToCopy, + int32_t count ); + + /** + * Sets the choices to be used in formatting. + * For details see the constructor with the same parameter list. + * + * @param limits Array of limits + * @param closures Array of limit booleans + * @param formats Array of format string + * @param count The size of the above arrays + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual void setChoices(const double* limits, + const UBool* closures, + const UnicodeString* formats, + int32_t count); + + /** + * Returns nullptr and 0. + * Before ICU 4.8, this used to return the choice limits array. + * + * @param count Will be set to 0. + * @return nullptr + * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. + */ + virtual const double* getLimits(int32_t& count) const; + + /** + * Returns nullptr and 0. + * Before ICU 4.8, this used to return the limit booleans array. + * + * @param count Will be set to 0. + * @return nullptr + * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. + */ + virtual const UBool* getClosures(int32_t& count) const; + + /** + * Returns nullptr and 0. + * Before ICU 4.8, this used to return the array of choice strings. + * + * @param count Will be set to 0. + * @return nullptr + * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. + */ + virtual const UnicodeString* getFormats(int32_t& count) const; + + + using NumberFormat::format; + + /** + * Formats a double number using this object's choices. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UnicodeString& format(double number, + UnicodeString& appendTo, + FieldPosition& pos) const override; + /** + * Formats an int32_t number using this object's choices. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UnicodeString& format(int32_t number, + UnicodeString& appendTo, + FieldPosition& pos) const override; + + /** + * Formats an int64_t number using this object's choices. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UnicodeString& format(int64_t number, + UnicodeString& appendTo, + FieldPosition& pos) const override; + + /** + * Formats an array of objects using this object's choices. + * + * @param objs The array of objects to be formatted. + * @param cnt The size of objs. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param success Output param set to success/failure code on + * exit. + * @return Reference to 'appendTo' parameter. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UnicodeString& format(const Formattable* objs, + int32_t cnt, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& success) const; + + using NumberFormat::parse; + + /** + * Looks for the longest match of any message string on the input text and, + * if there is a match, sets the result object to the corresponding range's number. + * + * If no string matches, then the parsePosition is unchanged. + * + * @param text The text to be parsed. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parsePosition The position to start parsing at on input. + * On output, moved to after the last successfully + * parse character. On parse failure, does not change. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual void parse(const UnicodeString& text, + Formattable& result, + ParsePosition& parsePosition) const override; + + /** + * Returns a unique class ID POLYMORPHICALLY. Part of ICU's "poor man's RTTI". + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Returns the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + *

+     * .       Base* polymorphic_pointer = createPolymorphicObject();
+     * .       if (polymorphic_pointer->getDynamicClassID() ==
+     * .           Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +private: + /** + * Converts a double value to a string. + * @param value the double number to be converted. + * @param string the result string. + * @return the converted string. + */ + static UnicodeString& dtos(double value, UnicodeString& string); + + ChoiceFormat() = delete; // default constructor not implemented + + /** + * Construct a new ChoiceFormat with the limits and the corresponding formats + * based on the pattern. + * + * @param newPattern Pattern used to construct object. + * @param parseError Struct to receive information on position + * of error if an error is encountered. + * @param status Output param to receive success code. If the + * pattern cannot be parsed, set to failure code. + */ + ChoiceFormat(const UnicodeString& newPattern, + UParseError& parseError, + UErrorCode& status); + + friend class MessageFormat; + + virtual void setChoices(const double* limits, + const UBool* closures, + const UnicodeString* formats, + int32_t count, + UErrorCode &errorCode); + + /** + * Finds the ChoiceFormat sub-message for the given number. + * @param pattern A MessagePattern. + * @param partIndex the index of the first ChoiceFormat argument style part. + * @param number a number to be mapped to one of the ChoiceFormat argument's intervals + * @return the sub-message start part index. + */ + static int32_t findSubMessage(const MessagePattern &pattern, int32_t partIndex, double number); + + static double parseArgument( + const MessagePattern &pattern, int32_t partIndex, + const UnicodeString &source, ParsePosition &pos); + + /** + * Matches the pattern string from the end of the partIndex to + * the beginning of the limitPartIndex, + * including all syntax except SKIP_SYNTAX, + * against the source string starting at sourceOffset. + * If they match, returns the length of the source string match. + * Otherwise returns -1. + */ + static int32_t matchStringUntilLimitPart( + const MessagePattern &pattern, int32_t partIndex, int32_t limitPartIndex, + const UnicodeString &source, int32_t sourceOffset); + + /** + * Some of the ChoiceFormat constructors do not have a UErrorCode parameter. + * We need _some_ way to provide one for the MessagePattern constructor. + * Alternatively, the MessagePattern could be a pointer field, but that is + * not nice either. + */ + UErrorCode constructorErrorCode; + + /** + * The MessagePattern which contains the parsed structure of the pattern string. + * + * Starting with ICU 4.8, the MessagePattern contains a sequence of + * numeric/selector/message parts corresponding to the parsed pattern. + * For details see the MessagePattern class API docs. + */ + MessagePattern msgPattern; + + /** + * Docs & fields from before ICU 4.8, before MessagePattern was used. + * Commented out, and left only for explanation of semantics. + * -------- + * Each ChoiceFormat divides the range -Inf..+Inf into fCount + * intervals. The intervals are: + * + * 0: fChoiceLimits[0]..fChoiceLimits[1] + * 1: fChoiceLimits[1]..fChoiceLimits[2] + * ... + * fCount-2: fChoiceLimits[fCount-2]..fChoiceLimits[fCount-1] + * fCount-1: fChoiceLimits[fCount-1]..+Inf + * + * Interval 0 is special; during formatting (mapping numbers to + * strings), it also contains all numbers less than + * fChoiceLimits[0], as well as NaN values. + * + * Interval i maps to and from string fChoiceFormats[i]. When + * parsing (mapping strings to numbers), then intervals map to + * their lower limit, that is, interval i maps to fChoiceLimit[i]. + * + * The intervals may be closed, half open, or open. This affects + * formatting but does not affect parsing. Interval i is affected + * by fClosures[i] and fClosures[i+1]. If fClosures[i] + * is false, then the value fChoiceLimits[i] is in interval i. + * That is, intervals i and i are: + * + * i-1: ... x < fChoiceLimits[i] + * i: fChoiceLimits[i] <= x ... + * + * If fClosures[i] is true, then the value fChoiceLimits[i] is + * in interval i-1. That is, intervals i-1 and i are: + * + * i-1: ... x <= fChoiceLimits[i] + * i: fChoiceLimits[i] < x ... + * + * Because of the nature of interval 0, fClosures[0] has no + * effect. + */ + // double* fChoiceLimits; + // UBool* fClosures; + // UnicodeString* fChoiceFormats; + // int32_t fCount; +}; + + +U_NAMESPACE_END + +#endif // U_HIDE_DEPRECATED_API +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // CHOICFMT_H +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coleitr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coleitr.h new file mode 100644 index 0000000000000000000000000000000000000000..bd0c569f35c80a81fae456abb6233f399bdcf27a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coleitr.h @@ -0,0 +1,411 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ****************************************************************************** + * Copyright (C) 1997-2014, International Business Machines + * Corporation and others. All Rights Reserved. + ****************************************************************************** + */ + +/** + * \file + * \brief C++ API: Collation Element Iterator. + */ + +/** +* File coleitr.h +* +* Created by: Helena Shih +* +* Modification History: +* +* Date Name Description +* +* 8/18/97 helena Added internal API documentation. +* 08/03/98 erm Synched with 1.2 version CollationElementIterator.java +* 12/10/99 aliu Ported Thai collation support from Java. +* 01/25/01 swquek Modified into a C++ wrapper calling C APIs (ucoliter.h) +* 02/19/01 swquek Removed CollationElementsIterator() since it is +* private constructor and no calls are made to it +* 2012-2014 markus Rewritten in C++ again. +*/ + +#ifndef COLEITR_H +#define COLEITR_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_COLLATION + +#include "unicode/unistr.h" +#include "unicode/uobject.h" + +struct UCollationElements; +struct UHashtable; + +U_NAMESPACE_BEGIN + +struct CollationData; + +class CharacterIterator; +class CollationIterator; +class RuleBasedCollator; +class UCollationPCE; +class UVector32; + +/** +* The CollationElementIterator class is used as an iterator to walk through +* each character of an international string. Use the iterator to return the +* ordering priority of the positioned character. The ordering priority of a +* character, which we refer to as a key, defines how a character is collated in +* the given collation object. +* For example, consider the following in Slovak and in traditional Spanish collation: +*
+*        "ca" -> the first key is key('c') and second key is key('a').
+*        "cha" -> the first key is key('ch') and second key is key('a').
+* And in German phonebook collation, +*
 \htmlonly       "æb"-> the first key is key('a'), the second key is key('e'), and
+*        the third key is key('b'). \endhtmlonly 
+* The key of a character, is an integer composed of primary order(short), +* secondary order(char), and tertiary order(char). Java strictly defines the +* size and signedness of its primitive data types. Therefore, the static +* functions primaryOrder(), secondaryOrder(), and tertiaryOrder() return +* int32_t to ensure the correctness of the key value. +*

Example of the iterator usage: (without error checking) +*

+* \code
+*   void CollationElementIterator_Example()
+*   {
+*       UnicodeString str = "This is a test";
+*       UErrorCode success = U_ZERO_ERROR;
+*       RuleBasedCollator* rbc =
+*           (RuleBasedCollator*) RuleBasedCollator::createInstance(success);
+*       CollationElementIterator* c =
+*           rbc->createCollationElementIterator( str );
+*       int32_t order = c->next(success);
+*       c->reset();
+*       order = c->previous(success);
+*       delete c;
+*       delete rbc;
+*   }
+* \endcode
+* 
+*

+* The method next() returns the collation order of the next character based on +* the comparison level of the collator. The method previous() returns the +* collation order of the previous character based on the comparison level of +* the collator. The Collation Element Iterator moves only in one direction +* between calls to reset(), setOffset(), or setText(). That is, next() +* and previous() can not be inter-used. Whenever previous() is to be called after +* next() or vice versa, reset(), setOffset() or setText() has to be called first +* to reset the status, shifting pointers to either the end or the start of +* the string (reset() or setText()), or the specified position (setOffset()). +* Hence at the next call of next() or previous(), the first or last collation order, +* or collation order at the specified position will be returned. If a change of +* direction is done without one of these calls, the result is undefined. +*

+* The result of a forward iterate (next()) and reversed result of the backward +* iterate (previous()) on the same string are equivalent, if collation orders +* with the value 0 are ignored. +* Character based on the comparison level of the collator. A collation order +* consists of primary order, secondary order and tertiary order. The data +* type of the collation order is int32_t. +* +* Note, CollationElementIterator should not be subclassed. +* @see Collator +* @see RuleBasedCollator +* @version 1.8 Jan 16 2001 +*/ +class U_I18N_API CollationElementIterator final : public UObject { +public: + + // CollationElementIterator public data member ------------------------------ + + enum { + /** + * NULLORDER indicates that an error has occurred while processing + * @stable ICU 2.0 + */ + NULLORDER = (int32_t)0xffffffff + }; + + // CollationElementIterator public constructor/destructor ------------------- + + /** + * Copy constructor. + * + * @param other the object to be copied from + * @stable ICU 2.0 + */ + CollationElementIterator(const CollationElementIterator& other); + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~CollationElementIterator(); + + // CollationElementIterator public methods ---------------------------------- + + /** + * Returns true if "other" is the same as "this" + * + * @param other the object to be compared + * @return true if "other" is the same as "this" + * @stable ICU 2.0 + */ + bool operator==(const CollationElementIterator& other) const; + + /** + * Returns true if "other" is not the same as "this". + * + * @param other the object to be compared + * @return true if "other" is not the same as "this" + * @stable ICU 2.0 + */ + bool operator!=(const CollationElementIterator& other) const; + + /** + * Resets the cursor to the beginning of the string. + * @stable ICU 2.0 + */ + void reset(void); + + /** + * Gets the ordering priority of the next character in the string. + * @param status the error code status. + * @return the next character's ordering. otherwise returns NULLORDER if an + * error has occurred or if the end of string has been reached + * @stable ICU 2.0 + */ + int32_t next(UErrorCode& status); + + /** + * Get the ordering priority of the previous collation element in the string. + * @param status the error code status. + * @return the previous element's ordering. otherwise returns NULLORDER if an + * error has occurred or if the start of string has been reached + * @stable ICU 2.0 + */ + int32_t previous(UErrorCode& status); + + /** + * Gets the primary order of a collation order. + * @param order the collation order + * @return the primary order of a collation order. + * @stable ICU 2.0 + */ + static inline int32_t primaryOrder(int32_t order); + + /** + * Gets the secondary order of a collation order. + * @param order the collation order + * @return the secondary order of a collation order. + * @stable ICU 2.0 + */ + static inline int32_t secondaryOrder(int32_t order); + + /** + * Gets the tertiary order of a collation order. + * @param order the collation order + * @return the tertiary order of a collation order. + * @stable ICU 2.0 + */ + static inline int32_t tertiaryOrder(int32_t order); + + /** + * Return the maximum length of any expansion sequences that end with the + * specified comparison order. + * @param order a collation order returned by previous or next. + * @return maximum size of the expansion sequences ending with the collation + * element or 1 if collation element does not occur at the end of any + * expansion sequence + * @stable ICU 2.0 + */ + int32_t getMaxExpansion(int32_t order) const; + + /** + * Gets the comparison order in the desired strength. Ignore the other + * differences. + * @param order The order value + * @stable ICU 2.0 + */ + int32_t strengthOrder(int32_t order) const; + + /** + * Sets the source string. + * @param str the source string. + * @param status the error code status. + * @stable ICU 2.0 + */ + void setText(const UnicodeString& str, UErrorCode& status); + + /** + * Sets the source string. + * @param str the source character iterator. + * @param status the error code status. + * @stable ICU 2.0 + */ + void setText(CharacterIterator& str, UErrorCode& status); + + /** + * Checks if a comparison order is ignorable. + * @param order the collation order. + * @return true if a character is ignorable, false otherwise. + * @stable ICU 2.0 + */ + static inline UBool isIgnorable(int32_t order); + + /** + * Gets the offset of the currently processed character in the source string. + * @return the offset of the character. + * @stable ICU 2.0 + */ + int32_t getOffset(void) const; + + /** + * Sets the offset of the currently processed character in the source string. + * @param newOffset the new offset. + * @param status the error code status. + * @return the offset of the character. + * @stable ICU 2.0 + */ + void setOffset(int32_t newOffset, UErrorCode& status); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + static inline CollationElementIterator *fromUCollationElements(UCollationElements *uc) { + return reinterpret_cast(uc); + } + /** @internal */ + static inline const CollationElementIterator *fromUCollationElements(const UCollationElements *uc) { + return reinterpret_cast(uc); + } + /** @internal */ + inline UCollationElements *toUCollationElements() { + return reinterpret_cast(this); + } + /** @internal */ + inline const UCollationElements *toUCollationElements() const { + return reinterpret_cast(this); + } +#endif // U_HIDE_INTERNAL_API + +private: + friend class RuleBasedCollator; + friend class UCollationPCE; + + /** + * CollationElementIterator constructor. This takes the source string and the + * collation object. The cursor will walk thru the source string based on the + * predefined collation rules. If the source string is empty, NULLORDER will + * be returned on the calls to next(). + * @param sourceText the source string. + * @param order the collation object. + * @param status the error code status. + */ + CollationElementIterator(const UnicodeString& sourceText, + const RuleBasedCollator* order, UErrorCode& status); + // Note: The constructors should take settings & tailoring, not a collator, + // to avoid circular dependencies. + // However, for operator==() we would need to be able to compare tailoring data for equality + // without making CollationData or CollationTailoring depend on TailoredSet. + // (See the implementation of RuleBasedCollator::operator==().) + // That might require creating an intermediate class that would be used + // by both CollationElementIterator and RuleBasedCollator + // but only contain the part of RBC== related to data and rules. + + /** + * CollationElementIterator constructor. This takes the source string and the + * collation object. The cursor will walk thru the source string based on the + * predefined collation rules. If the source string is empty, NULLORDER will + * be returned on the calls to next(). + * @param sourceText the source string. + * @param order the collation object. + * @param status the error code status. + */ + CollationElementIterator(const CharacterIterator& sourceText, + const RuleBasedCollator* order, UErrorCode& status); + + /** + * Assignment operator + * + * @param other the object to be copied + */ + const CollationElementIterator& + operator=(const CollationElementIterator& other); + + CollationElementIterator() = delete; // default constructor not implemented + + /** Normalizes dir_=1 (just after setOffset()) to dir_=0 (just after reset()). */ + inline int8_t normalizeDir() const { return dir_ == 1 ? 0 : dir_; } + + static UHashtable *computeMaxExpansions(const CollationData *data, UErrorCode &errorCode); + + static int32_t getMaxExpansion(const UHashtable *maxExpansions, int32_t order); + + // CollationElementIterator private data members ---------------------------- + + CollationIterator *iter_; // owned + const RuleBasedCollator *rbc_; // aliased + uint32_t otherHalf_; + /** + * <0: backwards; 0: just after reset() (previous() begins from end); + * 1: just after setOffset(); >1: forward + */ + int8_t dir_; + /** + * Stores offsets from expansions and from unsafe-backwards iteration, + * so that getOffset() returns intermediate offsets for the CEs + * that are consistent with forward iteration. + */ + UVector32 *offsets_; + + UnicodeString string_; +}; + +// CollationElementIterator inline method definitions -------------------------- + +inline int32_t CollationElementIterator::primaryOrder(int32_t order) +{ + return (order >> 16) & 0xffff; +} + +inline int32_t CollationElementIterator::secondaryOrder(int32_t order) +{ + return (order >> 8) & 0xff; +} + +inline int32_t CollationElementIterator::tertiaryOrder(int32_t order) +{ + return order & 0xff; +} + +inline UBool CollationElementIterator::isIgnorable(int32_t order) +{ + return (order & 0xffff0000) == 0; +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coll.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coll.h new file mode 100644 index 0000000000000000000000000000000000000000..fc5af953495529b015600dada5534b9a732f3a5f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/coll.h @@ -0,0 +1,1294 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 1996-2016, International Business Machines +* Corporation and others. All Rights Reserved. +****************************************************************************** +*/ + +/** + * \file + * \brief C++ API: Collation Service. + */ + +/** +* File coll.h +* +* Created by: Helena Shih +* +* Modification History: +* +* Date Name Description +* 02/5/97 aliu Modified createDefault to load collation data from +* binary files when possible. Added related methods +* createCollationFromFile, chopLocale, createPathName. +* 02/11/97 aliu Added members addToCache, findInCache, and fgCache. +* 02/12/97 aliu Modified to create objects from RuleBasedCollator cache. +* Moved cache out of Collation class. +* 02/13/97 aliu Moved several methods out of this class and into +* RuleBasedCollator, with modifications. Modified +* createDefault() to call new RuleBasedCollator(Locale&) +* constructor. General clean up and documentation. +* 02/20/97 helena Added clone, operator==, operator!=, operator=, copy +* constructor and getDynamicClassID. +* 03/25/97 helena Updated with platform independent data types. +* 05/06/97 helena Added memory allocation error detection. +* 06/20/97 helena Java class name change. +* 09/03/97 helena Added createCollationKeyValues(). +* 02/10/98 damiba Added compare() with length as parameter. +* 04/23/99 stephen Removed EDecompositionMode, merged with +* Normalizer::EMode. +* 11/02/99 helena Collator performance enhancements. Eliminates the +* UnicodeString construction and special case for NO_OP. +* 11/23/99 srl More performance enhancements. Inlining of +* critical accessors. +* 05/15/00 helena Added version information API. +* 01/29/01 synwee Modified into a C++ wrapper which calls C apis +* (ucol.h). +* 2012-2014 markus Rewritten in C++ again. +*/ + +#ifndef COLL_H +#define COLL_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_COLLATION + +#include "unicode/uobject.h" +#include "unicode/ucol.h" +#include "unicode/unorm.h" +#include "unicode/locid.h" +#include "unicode/uniset.h" +#include "unicode/umisc.h" +#include "unicode/uiter.h" +#include "unicode/stringpiece.h" + +U_NAMESPACE_BEGIN + +class StringEnumeration; + +#if !UCONFIG_NO_SERVICE +/** + * @stable ICU 2.6 + */ +class CollatorFactory; +#endif + +/** +* @stable ICU 2.0 +*/ +class CollationKey; + +/** +* The Collator class performs locale-sensitive string +* comparison.
+* You use this class to build searching and sorting routines for natural +* language text. +*

+* Collator is an abstract base class. Subclasses implement +* specific collation strategies. One subclass, +* RuleBasedCollator, is currently provided and is applicable +* to a wide set of languages. Other subclasses may be created to handle more +* specialized needs. +*

+* Like other locale-sensitive classes, you can use the static factory method, +* createInstance, to obtain the appropriate +* Collator object for a given locale. You will only need to +* look at the subclasses of Collator if you need to +* understand the details of a particular collation strategy or if you need to +* modify that strategy. +*

+* The following example shows how to compare two strings using the +* Collator for the default locale. +* \htmlonly

\endhtmlonly +*
+* \code
+* // Compare two strings in the default locale
+* UErrorCode success = U_ZERO_ERROR;
+* Collator* myCollator = Collator::createInstance(success);
+* if (myCollator->compare("abc", "ABC") < 0)
+*   cout << "abc is less than ABC" << endl;
+* else
+*   cout << "abc is greater than or equal to ABC" << endl;
+* \endcode
+* 
+* \htmlonly
\endhtmlonly +*

+* You can set a Collator's strength attribute to +* determine the level of difference considered significant in comparisons. +* Five strengths are provided: PRIMARY, SECONDARY, +* TERTIARY, QUATERNARY and IDENTICAL. +* The exact assignment of strengths to language features is locale dependent. +* For example, in Czech, "e" and "f" are considered primary differences, +* while "e" and "\u00EA" are secondary differences, "e" and "E" are tertiary +* differences and "e" and "e" are identical. The following shows how both case +* and accents could be ignored for US English. +* \htmlonly

\endhtmlonly +*
+* \code
+* //Get the Collator for US English and set its strength to PRIMARY
+* UErrorCode success = U_ZERO_ERROR;
+* Collator* usCollator = Collator::createInstance(Locale::getUS(), success);
+* usCollator->setStrength(Collator::PRIMARY);
+* if (usCollator->compare("abc", "ABC") == 0)
+*     cout << "'abc' and 'ABC' strings are equivalent with strength PRIMARY" << endl;
+* \endcode
+* 
+* \htmlonly
\endhtmlonly +* +* The getSortKey methods +* convert a string to a series of bytes that can be compared bitwise against +* other sort keys using strcmp(). Sort keys are written as +* zero-terminated byte strings. +* +* Another set of APIs returns a CollationKey object that wraps +* the sort key bytes instead of returning the bytes themselves. +*

+*

+* Note: Collators with different Locale, +* and CollationStrength settings will return different sort +* orders for the same set of strings. Locales have specific collation rules, +* and the way in which secondary and tertiary differences are taken into +* account, for example, will result in a different sorting order for same +* strings. +*

+* @see RuleBasedCollator +* @see CollationKey +* @see CollationElementIterator +* @see Locale +* @see Normalizer2 +* @version 2.0 11/15/01 +*/ + +class U_I18N_API Collator : public UObject { +public: + + // Collator public enums ----------------------------------------------- + + /** + * Base letter represents a primary difference. Set comparison level to + * PRIMARY to ignore secondary and tertiary differences.
+ * Use this to set the strength of a Collator object.
+ * Example of primary difference, "abc" < "abd" + * + * Diacritical differences on the same base letter represent a secondary + * difference. Set comparison level to SECONDARY to ignore tertiary + * differences. Use this to set the strength of a Collator object.
+ * Example of secondary difference, "ä" >> "a". + * + * Uppercase and lowercase versions of the same character represents a + * tertiary difference. Set comparison level to TERTIARY to include all + * comparison differences. Use this to set the strength of a Collator + * object.
+ * Example of tertiary difference, "abc" <<< "ABC". + * + * Two characters are considered "identical" when they have the same unicode + * spellings.
+ * For example, "ä" == "ä". + * + * UCollationStrength is also used to determine the strength of sort keys + * generated from Collator objects. + * @stable ICU 2.0 + */ + enum ECollationStrength + { + PRIMARY = UCOL_PRIMARY, // 0 + SECONDARY = UCOL_SECONDARY, // 1 + TERTIARY = UCOL_TERTIARY, // 2 + QUATERNARY = UCOL_QUATERNARY, // 3 + IDENTICAL = UCOL_IDENTICAL // 15 + }; + + + // Cannot use #ifndef U_HIDE_DEPRECATED_API for the following, it is + // used by virtual methods that cannot have that conditional. +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * LESS is returned if source string is compared to be less than target + * string in the compare() method. + * EQUAL is returned if source string is compared to be equal to target + * string in the compare() method. + * GREATER is returned if source string is compared to be greater than + * target string in the compare() method. + * @see Collator#compare + * @deprecated ICU 2.6. Use C enum UCollationResult defined in ucol.h + */ + enum EComparisonResult + { + LESS = UCOL_LESS, // -1 + EQUAL = UCOL_EQUAL, // 0 + GREATER = UCOL_GREATER // 1 + }; +#endif // U_FORCE_HIDE_DEPRECATED_API + + // Collator public destructor ----------------------------------------- + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~Collator(); + + // Collator public methods -------------------------------------------- + + /** + * Returns true if "other" is the same as "this". + * + * The base class implementation returns true if "other" has the same type/class as "this": + * `typeid(*this) == typeid(other)`. + * + * Subclass implementations should do something like the following: + * + * if (this == &other) { return true; } + * if (!Collator::operator==(other)) { return false; } // not the same class + * + * const MyCollator &o = (const MyCollator&)other; + * (compare this vs. o's subclass fields) + * + * @param other Collator object to be compared + * @return true if other is the same as this. + * @stable ICU 2.0 + */ + virtual bool operator==(const Collator& other) const; + + /** + * Returns true if "other" is not the same as "this". + * Calls ! operator==(const Collator&) const which works for all subclasses. + * @param other Collator object to be compared + * @return true if other is not the same as this. + * @stable ICU 2.0 + */ + virtual bool operator!=(const Collator& other) const; + + /** + * Makes a copy of this object. + * @return a copy of this object, owned by the caller + * @stable ICU 2.0 + */ + virtual Collator* clone() const = 0; + + /** + * Creates the Collator object for the current default locale. + * The default locale is determined by Locale::getDefault. + * The UErrorCode& err parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check the + * value of U_SUCCESS(err). If you wish more detailed information, you can + * check for informational error results which still indicate success. + * U_USING_FALLBACK_ERROR indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_ERROR indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * The caller owns the returned object and is responsible for deleting it. + * + * @param err the error code status. + * @return the collation object of the default locale.(for example, en_US) + * @see Locale#getDefault + * @stable ICU 2.0 + */ + static Collator* U_EXPORT2 createInstance(UErrorCode& err); + + /** + * Gets the collation object for the desired locale. The + * resource of the desired locale will be loaded. + * + * Locale::getRoot() is the base collation table and all other languages are + * built on top of it with additional language-specific modifications. + * + * For some languages, multiple collation types are available; + * for example, "de@collation=phonebook". + * Starting with ICU 54, collation attributes can be specified via locale keywords as well, + * in the old locale extension syntax ("el@colCaseFirst=upper") + * or in language tag syntax ("el-u-kf-upper"). + * See User Guide: Collation API. + * + * The UErrorCode& err parameter is used to return status information to the user. + * To check whether the construction succeeded or not, you should check + * the value of U_SUCCESS(err). If you wish more detailed information, you + * can check for informational error results which still indicate success. + * U_USING_FALLBACK_ERROR indicates that a fall back locale was used. For + * example, 'de_CH' was requested, but nothing was found there, so 'de' was + * used. U_USING_DEFAULT_ERROR indicates that the default locale data was + * used; neither the requested locale nor any of its fall back locales + * could be found. + * + * The caller owns the returned object and is responsible for deleting it. + * @param loc The locale ID for which to open a collator. + * @param err the error code status. + * @return the created table-based collation object based on the desired + * locale. + * @see Locale + * @see ResourceLoader + * @stable ICU 2.2 + */ + static Collator* U_EXPORT2 createInstance(const Locale& loc, UErrorCode& err); + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * The comparison function compares the character data stored in two + * different strings. Returns information about whether a string is less + * than, greater than or equal to another string. + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @return Returns a byte value. GREATER if source is greater + * than target; EQUAL if source is equal to target; LESS if source is less + * than target + * @deprecated ICU 2.6 use the overload with UErrorCode & + */ + virtual EComparisonResult compare(const UnicodeString& source, + const UnicodeString& target) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * The comparison function compares the character data stored in two + * different strings. Returns information about whether a string is less + * than, greater than or equal to another string. + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source is greater + * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less + * than target + * @stable ICU 2.6 + */ + virtual UCollationResult compare(const UnicodeString& source, + const UnicodeString& target, + UErrorCode &status) const = 0; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Does the same thing as compare but limits the comparison to a specified + * length + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @param length the length the comparison is limited to + * @return Returns a byte value. GREATER if source (up to the specified + * length) is greater than target; EQUAL if source (up to specified + * length) is equal to target; LESS if source (up to the specified + * length) is less than target. + * @deprecated ICU 2.6 use the overload with UErrorCode & + */ + virtual EComparisonResult compare(const UnicodeString& source, + const UnicodeString& target, + int32_t length) const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Does the same thing as compare but limits the comparison to a specified + * length + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @param length the length the comparison is limited to + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source (up to the specified + * length) is greater than target; UCOL_EQUAL if source (up to specified + * length) is equal to target; UCOL_LESS if source (up to the specified + * length) is less than target. + * @stable ICU 2.6 + */ + virtual UCollationResult compare(const UnicodeString& source, + const UnicodeString& target, + int32_t length, + UErrorCode &status) const = 0; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * The comparison function compares the character data stored in two + * different string arrays. Returns information about whether a string array + * is less than, greater than or equal to another string array. + *

Example of use: + *

+     * .       char16_t ABC[] = {0x41, 0x42, 0x43, 0};  // = "ABC"
+     * .       char16_t abc[] = {0x61, 0x62, 0x63, 0};  // = "abc"
+     * .       UErrorCode status = U_ZERO_ERROR;
+     * .       Collator *myCollation =
+     * .                         Collator::createInstance(Locale::getUS(), status);
+     * .       if (U_FAILURE(status)) return;
+     * .       myCollation->setStrength(Collator::PRIMARY);
+     * .       // result would be Collator::EQUAL ("abc" == "ABC")
+     * .       // (no primary difference between "abc" and "ABC")
+     * .       Collator::EComparisonResult result =
+     * .                             myCollation->compare(abc, 3, ABC, 3);
+     * .       myCollation->setStrength(Collator::TERTIARY);
+     * .       // result would be Collator::LESS ("abc" <<< "ABC")
+     * .       // (with tertiary difference between "abc" and "ABC")
+     * .       result = myCollation->compare(abc, 3, ABC, 3);
+     * 
+ * @param source the source string array to be compared with. + * @param sourceLength the length of the source string array. If this value + * is equal to -1, the string array is null-terminated. + * @param target the string that is to be compared with the source string. + * @param targetLength the length of the target string array. If this value + * is equal to -1, the string array is null-terminated. + * @return Returns a byte value. GREATER if source is greater than target; + * EQUAL if source is equal to target; LESS if source is less than + * target + * @deprecated ICU 2.6 use the overload with UErrorCode & + */ + virtual EComparisonResult compare(const char16_t* source, int32_t sourceLength, + const char16_t* target, int32_t targetLength) + const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * The comparison function compares the character data stored in two + * different string arrays. Returns information about whether a string array + * is less than, greater than or equal to another string array. + * @param source the source string array to be compared with. + * @param sourceLength the length of the source string array. If this value + * is equal to -1, the string array is null-terminated. + * @param target the string that is to be compared with the source string. + * @param targetLength the length of the target string array. If this value + * is equal to -1, the string array is null-terminated. + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source is greater + * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less + * than target + * @stable ICU 2.6 + */ + virtual UCollationResult compare(const char16_t* source, int32_t sourceLength, + const char16_t* target, int32_t targetLength, + UErrorCode &status) const = 0; + + /** + * Compares two strings using the Collator. + * Returns whether the first one compares less than/equal to/greater than + * the second one. + * This version takes UCharIterator input. + * @param sIter the first ("source") string iterator + * @param tIter the second ("target") string iterator + * @param status ICU status + * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER + * @stable ICU 4.2 + */ + virtual UCollationResult compare(UCharIterator &sIter, + UCharIterator &tIter, + UErrorCode &status) const; + + /** + * Compares two UTF-8 strings using the Collator. + * Returns whether the first one compares less than/equal to/greater than + * the second one. + * This version takes UTF-8 input. + * Note that a StringPiece can be implicitly constructed + * from a std::string or a NUL-terminated const char * string. + * @param source the first UTF-8 string + * @param target the second UTF-8 string + * @param status ICU status + * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER + * @stable ICU 4.2 + */ + virtual UCollationResult compareUTF8(const StringPiece &source, + const StringPiece &target, + UErrorCode &status) const; + + /** + * Transforms the string into a series of characters that can be compared + * with CollationKey::compareTo. It is not possible to restore the original + * string from the chars in the sort key. + *

Use CollationKey::equals or CollationKey::compare to compare the + * generated sort keys. + * If the source string is null, a null collation key will be returned. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source the source string to be transformed into a sort key. + * @param key the collation key to be filled in + * @param status the error code status. + * @return the collation key of the string based on the collation rules. + * @see CollationKey#compare + * @stable ICU 2.0 + */ + virtual CollationKey& getCollationKey(const UnicodeString& source, + CollationKey& key, + UErrorCode& status) const = 0; + + /** + * Transforms the string into a series of characters that can be compared + * with CollationKey::compareTo. It is not possible to restore the original + * string from the chars in the sort key. + *

Use CollationKey::equals or CollationKey::compare to compare the + * generated sort keys. + *

If the source string is null, a null collation key will be returned. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source the source string to be transformed into a sort key. + * @param sourceLength length of the collation key + * @param key the collation key to be filled in + * @param status the error code status. + * @return the collation key of the string based on the collation rules. + * @see CollationKey#compare + * @stable ICU 2.0 + */ + virtual CollationKey& getCollationKey(const char16_t*source, + int32_t sourceLength, + CollationKey& key, + UErrorCode& status) const = 0; + /** + * Generates the hash code for the collation object + * @stable ICU 2.0 + */ + virtual int32_t hashCode(void) const = 0; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the locale of the Collator + * + * @param type can be either requested, valid or actual locale. For more + * information see the definition of ULocDataLocaleType in + * uloc.h + * @param status the error code status. + * @return locale where the collation data lives. If the collator + * was instantiated from rules, locale is empty. + * @deprecated ICU 2.8 This API is under consideration for revision + * in ICU 3.0. + */ + virtual Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const = 0; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Convenience method for comparing two strings based on the collation rules. + * @param source the source string to be compared with. + * @param target the target string to be compared with. + * @return true if the first string is greater than the second one, + * according to the collation rules. false, otherwise. + * @see Collator#compare + * @stable ICU 2.0 + */ + UBool greater(const UnicodeString& source, const UnicodeString& target) + const; + + /** + * Convenience method for comparing two strings based on the collation rules. + * @param source the source string to be compared with. + * @param target the target string to be compared with. + * @return true if the first string is greater than or equal to the second + * one, according to the collation rules. false, otherwise. + * @see Collator#compare + * @stable ICU 2.0 + */ + UBool greaterOrEqual(const UnicodeString& source, + const UnicodeString& target) const; + + /** + * Convenience method for comparing two strings based on the collation rules. + * @param source the source string to be compared with. + * @param target the target string to be compared with. + * @return true if the strings are equal according to the collation rules. + * false, otherwise. + * @see Collator#compare + * @stable ICU 2.0 + */ + UBool equals(const UnicodeString& source, const UnicodeString& target) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Determines the minimum strength that will be used in comparison or + * transformation. + *

E.g. with strength == SECONDARY, the tertiary difference is ignored + *

E.g. with strength == PRIMARY, the secondary and tertiary difference + * are ignored. + * @return the current comparison level. + * @see Collator#setStrength + * @deprecated ICU 2.6 Use getAttribute(UCOL_STRENGTH...) instead + */ + virtual ECollationStrength getStrength(void) const; + + /** + * Sets the minimum strength to be used in comparison or transformation. + *

Example of use: + *

+     *  \code
+     *  UErrorCode status = U_ZERO_ERROR;
+     *  Collator*myCollation = Collator::createInstance(Locale::getUS(), status);
+     *  if (U_FAILURE(status)) return;
+     *  myCollation->setStrength(Collator::PRIMARY);
+     *  // result will be "abc" == "ABC"
+     *  // tertiary differences will be ignored
+     *  Collator::ComparisonResult result = myCollation->compare("abc", "ABC");
+     * \endcode
+     * 
+ * @see Collator#getStrength + * @param newStrength the new comparison level. + * @deprecated ICU 2.6 Use setAttribute(UCOL_STRENGTH...) instead + */ + virtual void setStrength(ECollationStrength newStrength); +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Retrieves the reordering codes for this collator. + * @param dest The array to fill with the script ordering. + * @param destCapacity The length of dest. If it is 0, then dest may be nullptr and the function + * will only return the length of the result without writing any codes (pre-flighting). + * @param status A reference to an error code value, which must not indicate + * a failure before the function call. + * @return The length of the script ordering array. + * @see ucol_setReorderCodes + * @see Collator#getEquivalentReorderCodes + * @see Collator#setReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ + virtual int32_t getReorderCodes(int32_t *dest, + int32_t destCapacity, + UErrorCode& status) const; + + /** + * Sets the ordering of scripts for this collator. + * + *

The reordering codes are a combination of script codes and reorder codes. + * @param reorderCodes An array of script codes in the new order. This can be nullptr if the + * length is also set to 0. An empty array will clear any reordering codes on the collator. + * @param reorderCodesLength The length of reorderCodes. + * @param status error code + * @see ucol_setReorderCodes + * @see Collator#getReorderCodes + * @see Collator#getEquivalentReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ + virtual void setReorderCodes(const int32_t* reorderCodes, + int32_t reorderCodesLength, + UErrorCode& status) ; + + /** + * Retrieves the reorder codes that are grouped with the given reorder code. Some reorder + * codes will be grouped and must reorder together. + * Beginning with ICU 55, scripts only reorder together if they are primary-equal, + * for example Hiragana and Katakana. + * + * @param reorderCode The reorder code to determine equivalence for. + * @param dest The array to fill with the script equivalence reordering codes. + * @param destCapacity The length of dest. If it is 0, then dest may be nullptr and the + * function will only return the length of the result without writing any codes (pre-flighting). + * @param status A reference to an error code value, which must not indicate + * a failure before the function call. + * @return The length of the of the reordering code equivalence array. + * @see ucol_setReorderCodes + * @see Collator#getReorderCodes + * @see Collator#setReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ + static int32_t U_EXPORT2 getEquivalentReorderCodes(int32_t reorderCode, + int32_t* dest, + int32_t destCapacity, + UErrorCode& status); + + /** + * Get name of the object for the desired Locale, in the desired language + * @param objectLocale must be from getAvailableLocales + * @param displayLocale specifies the desired locale for output + * @param name the fill-in parameter of the return value + * @return display-able name of the object for the object locale in the + * desired language + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, + const Locale& displayLocale, + UnicodeString& name); + + /** + * Get name of the object for the desired Locale, in the language of the + * default locale. + * @param objectLocale must be from getAvailableLocales + * @param name the fill-in parameter of the return value + * @return name of the object for the desired locale in the default language + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, + UnicodeString& name); + + /** + * Get the set of Locales for which Collations are installed. + * + *

Note this does not include locales supported by registered collators. + * If collators might have been registered, use the overload of getAvailableLocales + * that returns a StringEnumeration.

+ * + * @param count the output parameter of number of elements in the locale list + * @return the list of available locales for which collations are installed + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + /** + * Return a StringEnumeration over the locales available at the time of the call, + * including registered locales. If a severe error occurs (such as out of memory + * condition) this will return null. If there is no locale data, an empty enumeration + * will be returned. + * @return a StringEnumeration over the locales available at the time of the call + * @stable ICU 2.6 + */ + static StringEnumeration* U_EXPORT2 getAvailableLocales(void); + + /** + * Create a string enumerator of all possible keywords that are relevant to + * collation. At this point, the only recognized keyword for this + * service is "collation". + * @param status input-output error code + * @return a string enumeration over locale strings. The caller is + * responsible for closing the result. + * @stable ICU 3.0 + */ + static StringEnumeration* U_EXPORT2 getKeywords(UErrorCode& status); + + /** + * Given a keyword, create a string enumeration of all values + * for that keyword that are currently in use. + * @param keyword a particular keyword as enumerated by + * ucol_getKeywords. If any other keyword is passed in, status is set + * to U_ILLEGAL_ARGUMENT_ERROR. + * @param status input-output error code + * @return a string enumeration over collation keyword values, or nullptr + * upon error. The caller is responsible for deleting the result. + * @stable ICU 3.0 + */ + static StringEnumeration* U_EXPORT2 getKeywordValues(const char *keyword, UErrorCode& status); + + /** + * Given a key and a locale, returns an array of string values in a preferred + * order that would make a difference. These are all and only those values where + * the open (creation) of the service with the locale formed from the input locale + * plus input keyword and that value has different behavior than creation with the + * input locale alone. + * @param keyword one of the keys supported by this service. For now, only + * "collation" is supported. + * @param locale the locale + * @param commonlyUsed if set to true it will return only commonly used values + * with the given locale in preferred order. Otherwise, + * it will return all the available values for the locale. + * @param status ICU status + * @return a string enumeration over keyword values for the given key and the locale. + * @stable ICU 4.2 + */ + static StringEnumeration* U_EXPORT2 getKeywordValuesForLocale(const char* keyword, const Locale& locale, + UBool commonlyUsed, UErrorCode& status); + + /** + * Return the functionally equivalent locale for the given + * requested locale, with respect to given keyword, for the + * collation service. If two locales return the same result, then + * collators instantiated for these locales will behave + * equivalently. The converse is not always true; two collators + * may in fact be equivalent, but return different results, due to + * internal details. The return result has no other meaning than + * that stated above, and implies nothing as to the relationship + * between the two locales. This is intended for use by + * applications who wish to cache collators, or otherwise reuse + * collators when possible. The functional equivalent may change + * over time. For more information, please see the + * Locales and Services section of the ICU User Guide. + * @param keyword a particular keyword as enumerated by + * ucol_getKeywords. + * @param locale the requested locale + * @param isAvailable reference to a fillin parameter that + * indicates whether the requested locale was 'available' to the + * collation service. A locale is defined as 'available' if it + * physically exists within the collation locale data. + * @param status reference to input-output error code + * @return the functionally equivalent collation locale, or the root + * locale upon error. + * @stable ICU 3.0 + */ + static Locale U_EXPORT2 getFunctionalEquivalent(const char* keyword, const Locale& locale, + UBool& isAvailable, UErrorCode& status); + +#if !UCONFIG_NO_SERVICE + /** + * Register a new Collator. The collator will be adopted. + * Because ICU may choose to cache collators internally, this must be + * called at application startup, prior to any calls to + * Collator::createInstance to avoid undefined behavior. + * @param toAdopt the Collator instance to be adopted + * @param locale the locale with which the collator will be associated + * @param status the in/out status code, no special meanings are assigned + * @return a registry key that can be used to unregister this collator + * @stable ICU 2.6 + */ + static URegistryKey U_EXPORT2 registerInstance(Collator* toAdopt, const Locale& locale, UErrorCode& status); + + /** + * Register a new CollatorFactory. The factory will be adopted. + * Because ICU may choose to cache collators internally, this must be + * called at application startup, prior to any calls to + * Collator::createInstance to avoid undefined behavior. + * @param toAdopt the CollatorFactory instance to be adopted + * @param status the in/out status code, no special meanings are assigned + * @return a registry key that can be used to unregister this collator + * @stable ICU 2.6 + */ + static URegistryKey U_EXPORT2 registerFactory(CollatorFactory* toAdopt, UErrorCode& status); + + /** + * Unregister a previously-registered Collator or CollatorFactory + * using the key returned from the register call. Key becomes + * invalid after a successful call and should not be used again. + * The object corresponding to the key will be deleted. + * Because ICU may choose to cache collators internally, this should + * be called during application shutdown, after all calls to + * Collator::createInstance to avoid undefined behavior. + * @param key the registry key returned by a previous call to registerInstance + * @param status the in/out status code, no special meanings are assigned + * @return true if the collator for the key was successfully unregistered + * @stable ICU 2.6 + */ + static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); +#endif /* UCONFIG_NO_SERVICE */ + + /** + * Gets the version information for a Collator. + * @param info the version # information, the result will be filled in + * @stable ICU 2.0 + */ + virtual void getVersion(UVersionInfo info) const = 0; + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual method. + * This method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * @return The class ID for this object. All objects of a given class have + * the same class ID. Objects of other classes have different class + * IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Universal attribute setter + * @param attr attribute type + * @param value attribute value + * @param status to indicate whether the operation went on smoothly or + * there were errors + * @stable ICU 2.2 + */ + virtual void setAttribute(UColAttribute attr, UColAttributeValue value, + UErrorCode &status) = 0; + + /** + * Universal attribute getter + * @param attr attribute type + * @param status to indicate whether the operation went on smoothly or + * there were errors + * @return attribute value + * @stable ICU 2.2 + */ + virtual UColAttributeValue getAttribute(UColAttribute attr, + UErrorCode &status) const = 0; + + /** + * Sets the variable top to the top of the specified reordering group. + * The variable top determines the highest-sorting character + * which is affected by UCOL_ALTERNATE_HANDLING. + * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. + * + * The base class implementation sets U_UNSUPPORTED_ERROR. + * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, + * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; + * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @see getMaxVariable + * @stable ICU 53 + */ + virtual Collator &setMaxVariable(UColReorderCode group, UErrorCode &errorCode); + + /** + * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. + * + * The base class implementation returns UCOL_REORDER_CODE_PUNCTUATION. + * @return the maximum variable reordering group. + * @see setMaxVariable + * @stable ICU 53 + */ + virtual UColReorderCode getMaxVariable() const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Sets the variable top to the primary weight of the specified string. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop one or more (if contraction) char16_ts to which the variable top should be set + * @param len length of variable top string. If -1 it is considered to be zero terminated. + * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
+ * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
+ * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond + * the last reordering group supported by setMaxVariable() + * @return variable top primary weight + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual uint32_t setVariableTop(const char16_t *varTop, int32_t len, UErrorCode &status) = 0; + + /** + * Sets the variable top to the primary weight of the specified string. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop a UnicodeString size 1 or more (if contraction) of char16_ts to which the variable top should be set + * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
+ * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
+ * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond + * the last reordering group supported by setMaxVariable() + * @return variable top primary weight + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual uint32_t setVariableTop(const UnicodeString &varTop, UErrorCode &status) = 0; + + /** + * Sets the variable top to the specified primary weight. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop primary weight, as returned by setVariableTop or ucol_getVariableTop + * @param status error code + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual void setVariableTop(uint32_t varTop, UErrorCode &status) = 0; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the variable top value of a Collator. + * @param status error code (not changed by function). If error code is set, the return value is undefined. + * @return the variable top primary weight + * @see getMaxVariable + * @stable ICU 2.0 + */ + virtual uint32_t getVariableTop(UErrorCode &status) const = 0; + + /** + * Get a UnicodeSet that contains all the characters and sequences + * tailored in this collator. + * @param status error code of the operation + * @return a pointer to a UnicodeSet object containing all the + * code points and sequences that may sort differently than + * in the root collator. The object must be disposed of by using delete + * @stable ICU 2.4 + */ + virtual UnicodeSet *getTailoredSet(UErrorCode &status) const; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Same as clone(). + * The base class implementation simply calls clone(). + * @return a copy of this object, owned by the caller + * @see clone() + * @deprecated ICU 50 no need to have two methods for cloning + */ + virtual Collator* safeClone() const; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Get the sort key as an array of bytes from a UnicodeString. + * Sort key byte arrays are zero-terminated and can be compared using + * strcmp(). + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source string to be processed. + * @param result buffer to store result in. If nullptr, number of bytes needed + * will be returned. + * @param resultLength length of the result buffer. If if not enough the + * buffer will be filled to capacity. + * @return Number of bytes needed for storing the sort key + * @stable ICU 2.2 + */ + virtual int32_t getSortKey(const UnicodeString& source, + uint8_t* result, + int32_t resultLength) const = 0; + + /** + * Get the sort key as an array of bytes from a char16_t buffer. + * Sort key byte arrays are zero-terminated and can be compared using + * strcmp(). + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source string to be processed. + * @param sourceLength length of string to be processed. + * If -1, the string is 0 terminated and length will be decided by the + * function. + * @param result buffer to store result in. If nullptr, number of bytes needed + * will be returned. + * @param resultLength length of the result buffer. If if not enough the + * buffer will be filled to capacity. + * @return Number of bytes needed for storing the sort key + * @stable ICU 2.2 + */ + virtual int32_t getSortKey(const char16_t*source, int32_t sourceLength, + uint8_t*result, int32_t resultLength) const = 0; + + /** + * Produce a bound for a given sortkey and a number of levels. + * Return value is always the number of bytes needed, regardless of + * whether the result buffer was big enough or even valid.
+ * Resulting bounds can be used to produce a range of strings that are + * between upper and lower bounds. For example, if bounds are produced + * for a sortkey of string "smith", strings between upper and lower + * bounds with one level would include "Smith", "SMITH", "sMiTh".
+ * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER + * is produced, strings matched would be as above. However, if bound + * produced using UCOL_BOUND_UPPER_LONG is used, the above example will + * also match "Smithsonian" and similar.
+ * For more on usage, see example in cintltst/capitst.c in procedure + * TestBounds. + * Sort keys may be compared using strcmp. + * @param source The source sortkey. + * @param sourceLength The length of source, or -1 if null-terminated. + * (If an unmodified sortkey is passed, it is always null + * terminated). + * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which + * produces a lower inclusive bound, UCOL_BOUND_UPPER, that + * produces upper bound that matches strings of the same length + * or UCOL_BOUND_UPPER_LONG that matches strings that have the + * same starting substring as the source string. + * @param noOfLevels Number of levels required in the resulting bound (for most + * uses, the recommended value is 1). See users guide for + * explanation on number of levels a sortkey can have. + * @param result A pointer to a buffer to receive the resulting sortkey. + * @param resultLength The maximum size of result. + * @param status Used for returning error code if something went wrong. If the + * number of levels requested is higher than the number of levels + * in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is + * issued. + * @return The size needed to fully store the bound. + * @see ucol_keyHashCode + * @stable ICU 2.1 + */ + static int32_t U_EXPORT2 getBound(const uint8_t *source, + int32_t sourceLength, + UColBoundMode boundType, + uint32_t noOfLevels, + uint8_t *result, + int32_t resultLength, + UErrorCode &status); + + +protected: + + // Collator protected constructors ------------------------------------- + + /** + * Default constructor. + * Constructor is different from the old default Collator constructor. + * The task for determining the default collation strength and normalization + * mode is left to the child class. + * @stable ICU 2.0 + */ + Collator(); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Constructor. + * Empty constructor, does not handle the arguments. + * This constructor is done for backward compatibility with 1.7 and 1.8. + * The task for handling the argument collation strength and normalization + * mode is left to the child class. + * @param collationStrength collation strength + * @param decompositionMode + * @deprecated ICU 2.4. Subclasses should use the default constructor + * instead and handle the strength and normalization mode themselves. + */ + Collator(UCollationStrength collationStrength, + UNormalizationMode decompositionMode); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Copy constructor. + * @param other Collator object to be copied from + * @stable ICU 2.0 + */ + Collator(const Collator& other); + +public: + /** + * Used internally by registration to define the requested and valid locales. + * @param requestedLocale the requested locale + * @param validLocale the valid locale + * @param actualLocale the actual locale + * @internal + */ + virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale); + + /** Get the short definition string for a collator. This internal API harvests the collator's + * locale and the attribute set and produces a string that can be used for opening + * a collator with the same attributes using the ucol_openFromShortString API. + * This string will be normalized. + * The structure and the syntax of the string is defined in the "Naming collators" + * section of the users guide: + * https://unicode-org.github.io/icu/userguide/collation/concepts#collator-naming-scheme + * This function supports preflighting. + * + * This is internal, and intended to be used with delegate converters. + * + * @param locale a locale that will appear as a collators locale in the resulting + * short string definition. If nullptr, the locale will be harvested + * from the collator. + * @param buffer space to hold the resulting string + * @param capacity capacity of the buffer + * @param status for returning errors. All the preflighting errors are featured + * @return length of the resulting string + * @see ucol_openFromShortString + * @see ucol_normalizeShortDefinitionString + * @see ucol_getShortDefinitionString + * @internal + */ + virtual int32_t internalGetShortDefinitionString(const char *locale, + char *buffer, + int32_t capacity, + UErrorCode &status) const; + + /** + * Implements ucol_strcollUTF8(). + * @internal + */ + virtual UCollationResult internalCompareUTF8( + const char *left, int32_t leftLength, + const char *right, int32_t rightLength, + UErrorCode &errorCode) const; + + /** + * Implements ucol_nextSortKeyPart(). + * @internal + */ + virtual int32_t + internalNextSortKeyPart( + UCharIterator *iter, uint32_t state[2], + uint8_t *dest, int32_t count, UErrorCode &errorCode) const; + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + static inline Collator *fromUCollator(UCollator *uc) { + return reinterpret_cast(uc); + } + /** @internal */ + static inline const Collator *fromUCollator(const UCollator *uc) { + return reinterpret_cast(uc); + } + /** @internal */ + inline UCollator *toUCollator() { + return reinterpret_cast(this); + } + /** @internal */ + inline const UCollator *toUCollator() const { + return reinterpret_cast(this); + } +#endif // U_HIDE_INTERNAL_API + +private: + /** + * Assignment operator. Private for now. + */ + Collator& operator=(const Collator& other) = delete; + + friend class CFactory; + friend class SimpleCFactory; + friend class ICUCollatorFactory; + friend class ICUCollatorService; + static Collator* makeInstance(const Locale& desiredLocale, + UErrorCode& status); +}; + +#if !UCONFIG_NO_SERVICE +/** + * A factory, used with registerFactory, the creates multiple collators and provides + * display names for them. A factory supports some number of locales-- these are the + * locales for which it can create collators. The factory can be visible, in which + * case the supported locales will be enumerated by getAvailableLocales, or invisible, + * in which they are not. Invisible locales are still supported, they are just not + * listed by getAvailableLocales. + *

+ * If standard locale display names are sufficient, Collator instances can + * be registered using registerInstance instead.

+ *

+ * Note: if the collators are to be used from C APIs, they must be instances + * of RuleBasedCollator.

+ * + * @stable ICU 2.6 + */ +class U_I18N_API CollatorFactory : public UObject { +public: + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~CollatorFactory(); + + /** + * Return true if this factory is visible. Default is true. + * If not visible, the locales supported by this factory will not + * be listed by getAvailableLocales. + * @return true if the factory is visible. + * @stable ICU 2.6 + */ + virtual UBool visible(void) const; + + /** + * Return a collator for the provided locale. If the locale + * is not supported, return nullptr. + * @param loc the locale identifying the collator to be created. + * @return a new collator if the locale is supported, otherwise nullptr. + * @stable ICU 2.6 + */ + virtual Collator* createCollator(const Locale& loc) = 0; + + /** + * Return the name of the collator for the objectLocale, localized for the displayLocale. + * If objectLocale is not supported, or the factory is not visible, set the result string + * to bogus. + * @param objectLocale the locale identifying the collator + * @param displayLocale the locale for which the display name of the collator should be localized + * @param result an output parameter for the display name, set to bogus if not supported. + * @return the display name + * @stable ICU 2.6 + */ + virtual UnicodeString& getDisplayName(const Locale& objectLocale, + const Locale& displayLocale, + UnicodeString& result); + + /** + * Return an array of all the locale names directly supported by this factory. + * The number of names is returned in count. This array is owned by the factory. + * Its contents must never change. + * @param count output parameter for the number of locales supported by the factory + * @param status the in/out error code + * @return a pointer to an array of count UnicodeStrings. + * @stable ICU 2.6 + */ + virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) = 0; +}; +#endif /* UCONFIG_NO_SERVICE */ + +// Collator inline methods ----------------------------------------------- + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/compactdecimalformat.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/compactdecimalformat.h new file mode 100644 index 0000000000000000000000000000000000000000..0cbf3d4c73ad272436455232a2c4536bad76f11f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/compactdecimalformat.h @@ -0,0 +1,196 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 2012-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File COMPACTDECIMALFORMAT.H +******************************************************************************** +*/ + +#ifndef __COMPACT_DECIMAL_FORMAT_H__ +#define __COMPACT_DECIMAL_FORMAT_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Compatibility APIs for compact decimal number formatting. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/decimfmt.h" + +struct UHashtable; + +U_NAMESPACE_BEGIN + +class PluralRules; + +/** + * **IMPORTANT:** New users are strongly encouraged to see if + * numberformatter.h fits their use case. Although not deprecated, this header + * is provided for backwards compatibility only. + * + * ----------------------------------------------------------------------------- + * + * The CompactDecimalFormat produces abbreviated numbers, suitable for display in + * environments will limited real estate. For example, 'Hits: 1.2B' instead of + * 'Hits: 1,200,000,000'. The format will be appropriate for the given language, + * such as "1,2 Mrd." for German. + * + * For numbers under 1000 trillion (under 10^15, such as 123,456,789,012,345), + * the result will be short for supported languages. However, the result may + * sometimes exceed 7 characters, such as when there are combining marks or thin + * characters. In such cases, the visual width in fonts should still be short. + * + * By default, there are 3 significant digits. After creation, if more than + * three significant digits are set (with setMaximumSignificantDigits), or if a + * fixed number of digits are set (with setMaximumIntegerDigits or + * setMaximumFractionDigits), then result may be wider. + * + * At this time, parsing is not supported, and will produce a U_UNSUPPORTED_ERROR. + * Resetting the pattern prefixes or suffixes is not supported; the method calls + * are ignored. + * + * @stable ICU 51 + */ +class U_I18N_API CompactDecimalFormat : public DecimalFormat { +public: + + /** + * Returns a compact decimal instance for specified locale. + * + * **NOTE:** New users are strongly encouraged to use + * `number::NumberFormatter` instead of NumberFormat. + * @param inLocale the given locale. + * @param style whether to use short or long style. + * @param status error code returned here. + * @stable ICU 51 + */ + static CompactDecimalFormat* U_EXPORT2 createInstance( + const Locale& inLocale, UNumberCompactStyle style, UErrorCode& status); + + /** + * Copy constructor. + * + * @param source the DecimalFormat object to be copied from. + * @stable ICU 51 + */ + CompactDecimalFormat(const CompactDecimalFormat& source); + + /** + * Destructor. + * @stable ICU 51 + */ + ~CompactDecimalFormat() override; + + /** + * Assignment operator. + * + * @param rhs the DecimalFormat object to be copied. + * @stable ICU 51 + */ + CompactDecimalFormat& operator=(const CompactDecimalFormat& rhs); + + /** + * Clone this Format object polymorphically. The caller owns the + * result and should delete it when done. + * + * @return a polymorphic copy of this CompactDecimalFormat. + * @stable ICU 51 + */ + CompactDecimalFormat* clone() const override; + + using DecimalFormat::format; + + /** + * CompactDecimalFormat does not support parsing. This implementation + * does nothing. + * @param text Unused. + * @param result Does not change. + * @param parsePosition Does not change. + * @see Formattable + * @stable ICU 51 + */ + void parse(const UnicodeString& text, Formattable& result, + ParsePosition& parsePosition) const override; + + /** + * CompactDecimalFormat does not support parsing. This implementation + * sets status to U_UNSUPPORTED_ERROR + * + * @param text Unused. + * @param result Does not change. + * @param status Always set to U_UNSUPPORTED_ERROR. + * @stable ICU 51 + */ + void parse(const UnicodeString& text, Formattable& result, UErrorCode& status) const override; + +#ifndef U_HIDE_INTERNAL_API + /** + * Parses text from the given string as a currency amount. Unlike + * the parse() method, this method will attempt to parse a generic + * currency name, searching for a match of this object's locale's + * currency display names, or for a 3-letter ISO currency code. + * This method will fail if this format is not a currency format, + * that is, if it does not contain the currency pattern symbol + * (U+00A4) in its prefix or suffix. This implementation always returns + * nullptr. + * + * @param text the string to parse + * @param pos input-output position; on input, the position within text + * to match; must have 0 <= pos.getIndex() < text.length(); + * on output, the position after the last matched character. + * If the parse fails, the position in unchanged upon output. + * @return if parse succeeds, a pointer to a newly-created CurrencyAmount + * object (owned by the caller) containing information about + * the parsed currency; if parse fails, this is nullptr. + * @internal + */ + CurrencyAmount* parseCurrency(const UnicodeString& text, ParsePosition& pos) const override; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + *
+     * .      Base* polymorphic_pointer = createPolymorphicObject();
+     * .      if (polymorphic_pointer->getDynamicClassID() ==
+     * .          Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 51 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. + * This method is to implement a simple version of RTTI, since not all + * C++ compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 51 + */ + UClassID getDynamicClassID() const override; + + private: + CompactDecimalFormat(const Locale& inLocale, UNumberCompactStyle style, UErrorCode& status); +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __COMPACT_DECIMAL_FORMAT_H__ +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/curramt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/curramt.h new file mode 100644 index 0000000000000000000000000000000000000000..e0f6aa13dd2a6652f8b0afe708596a36060b707a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/curramt.h @@ -0,0 +1,133 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2004-2006, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: April 26, 2004 +* Since: ICU 3.0 +********************************************************************** +*/ +#ifndef __CURRENCYAMOUNT_H__ +#define __CURRENCYAMOUNT_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/measure.h" +#include "unicode/currunit.h" + +/** + * \file + * \brief C++ API: Currency Amount Object. + */ + +U_NAMESPACE_BEGIN + +/** + * + * A currency together with a numeric amount, such as 200 USD. + * + * @author Alan Liu + * @stable ICU 3.0 + */ +class U_I18N_API CurrencyAmount: public Measure { + public: + /** + * Construct an object with the given numeric amount and the given + * ISO currency code. + * @param amount a numeric object; amount.isNumeric() must be true + * @param isoCode the 3-letter ISO 4217 currency code; must not be + * nullptr and must have length 3 + * @param ec input-output error code. If the amount or the isoCode + * is invalid, then this will be set to a failing value. + * @stable ICU 3.0 + */ + CurrencyAmount(const Formattable& amount, ConstChar16Ptr isoCode, + UErrorCode &ec); + + /** + * Construct an object with the given numeric amount and the given + * ISO currency code. + * @param amount the amount of the given currency + * @param isoCode the 3-letter ISO 4217 currency code; must not be + * nullptr and must have length 3 + * @param ec input-output error code. If the isoCode is invalid, + * then this will be set to a failing value. + * @stable ICU 3.0 + */ + CurrencyAmount(double amount, ConstChar16Ptr isoCode, + UErrorCode &ec); + + /** + * Copy constructor + * @stable ICU 3.0 + */ + CurrencyAmount(const CurrencyAmount& other); + + /** + * Assignment operator + * @stable ICU 3.0 + */ + CurrencyAmount& operator=(const CurrencyAmount& other); + + /** + * Return a polymorphic clone of this object. The result will + * have the same class as returned by getDynamicClassID(). + * @stable ICU 3.0 + */ + virtual CurrencyAmount* clone() const override; + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~CurrencyAmount(); + + /** + * Returns a unique class ID for this object POLYMORPHICALLY. + * This method implements a simple form of RTTI used by ICU. + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 3.0 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * Returns the class ID for this class. This is used to compare to + * the return value of getDynamicClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 3.0 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * Return the currency unit object of this object. + * @stable ICU 3.0 + */ + const CurrencyUnit& getCurrency() const; + + /** + * Return the ISO currency code of this object. + * @stable ICU 3.0 + */ + inline const char16_t* getISOCurrency() const; +}; + +inline const char16_t* CurrencyAmount::getISOCurrency() const { + return getCurrency().getISOCurrency(); +} + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __CURRENCYAMOUNT_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currpinf.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currpinf.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ca34b26f27a33290553ec94a58daf89c2deedb --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currpinf.h @@ -0,0 +1,274 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2009-2015, International Business Machines Corporation and * + * others. All Rights Reserved. * + ******************************************************************************* + */ +#ifndef CURRPINF_H +#define CURRPINF_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Currency Plural Information used by Decimal Format + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" + +U_NAMESPACE_BEGIN + +class Locale; +class PluralRules; +class Hashtable; + +/** + * This class represents the information needed by + * DecimalFormat to format currency plural, + * such as "3.00 US dollars" or "1.00 US dollar". + * DecimalFormat creates for itself an instance of + * CurrencyPluralInfo from its locale data. + * If you need to change any of these symbols, you can get the + * CurrencyPluralInfo object from your + * DecimalFormat and modify it. + * + * Following are the information needed for currency plural format and parse: + * locale information, + * plural rule of the locale, + * currency plural pattern of the locale. + * + * @stable ICU 4.2 + */ +class U_I18N_API CurrencyPluralInfo : public UObject { +public: + + /** + * Create a CurrencyPluralInfo object for the default locale. + * @param status output param set to success/failure code on exit + * @stable ICU 4.2 + */ + CurrencyPluralInfo(UErrorCode& status); + + /** + * Create a CurrencyPluralInfo object for the given locale. + * @param locale the locale + * @param status output param set to success/failure code on exit + * @stable ICU 4.2 + */ + CurrencyPluralInfo(const Locale& locale, UErrorCode& status); + + /** + * Copy constructor + * + * @stable ICU 4.2 + */ + CurrencyPluralInfo(const CurrencyPluralInfo& info); + + + /** + * Assignment operator + * + * @stable ICU 4.2 + */ + CurrencyPluralInfo& operator=(const CurrencyPluralInfo& info); + + + /** + * Destructor + * + * @stable ICU 4.2 + */ + virtual ~CurrencyPluralInfo(); + + + /** + * Equal operator. + * + * @stable ICU 4.2 + */ + bool operator==(const CurrencyPluralInfo& info) const; + + + /** + * Not equal operator + * + * @stable ICU 4.2 + */ + bool operator!=(const CurrencyPluralInfo& info) const; + + + /** + * Clone + * + * @stable ICU 4.2 + */ + CurrencyPluralInfo* clone() const; + + + /** + * Gets plural rules of this locale, used for currency plural format + * + * @return plural rule + * @stable ICU 4.2 + */ + const PluralRules* getPluralRules() const; + + /** + * Given a plural count, gets currency plural pattern of this locale, + * used for currency plural format + * + * @param pluralCount currency plural count + * @param result output param to receive the pattern + * @return a currency plural pattern based on plural count + * @stable ICU 4.2 + */ + UnicodeString& getCurrencyPluralPattern(const UnicodeString& pluralCount, + UnicodeString& result) const; + + /** + * Get locale + * + * @return locale + * @stable ICU 4.2 + */ + const Locale& getLocale() const; + + /** + * Set plural rules. + * The plural rule is set when CurrencyPluralInfo + * instance is created. + * You can call this method to reset plural rules only if you want + * to modify the default plural rule of the locale. + * + * @param ruleDescription new plural rule description + * @param status output param set to success/failure code on exit + * @stable ICU 4.2 + */ + void setPluralRules(const UnicodeString& ruleDescription, + UErrorCode& status); + + /** + * Set currency plural pattern. + * The currency plural pattern is set when CurrencyPluralInfo + * instance is created. + * You can call this method to reset currency plural pattern only if + * you want to modify the default currency plural pattern of the locale. + * + * @param pluralCount the plural count for which the currency pattern will + * be overridden. + * @param pattern the new currency plural pattern + * @param status output param set to success/failure code on exit + * @stable ICU 4.2 + */ + void setCurrencyPluralPattern(const UnicodeString& pluralCount, + const UnicodeString& pattern, + UErrorCode& status); + + /** + * Set locale + * + * @param loc the new locale to set + * @param status output param set to success/failure code on exit + * @stable ICU 4.2 + */ + void setLocale(const Locale& loc, UErrorCode& status); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 4.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 4.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + friend class DecimalFormat; + friend class DecimalFormatImpl; + + void initialize(const Locale& loc, UErrorCode& status); + + void setupCurrencyPluralPattern(const Locale& loc, UErrorCode& status); + + /* + * delete hash table + * + * @param hTable hash table to be deleted + */ + void deleteHash(Hashtable* hTable); + + + /* + * initialize hash table + * + * @param status output param set to success/failure code on exit + * @return hash table initialized + */ + Hashtable* initHash(UErrorCode& status); + + + + /** + * copy hash table + * + * @param source the source to copy from + * @param target the target to copy to + * @param status error code + */ + void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); + + //-------------------- private data member --------------------- + // map from plural count to currency plural pattern, for example + // a plural pattern defined in "CurrencyUnitPatterns" is + // "one{{0} {1}}", in which "one" is a plural count + // and "{0} {1}" is a currency plural pattern". + // The currency plural pattern saved in this mapping is the pattern + // defined in "CurrencyUnitPattern" by replacing + // {0} with the number format pattern, + // and {1} with 3 currency sign. + Hashtable* fPluralCountToCurrencyUnitPattern; + + /* + * The plural rule is used to format currency plural name, + * for example: "3.00 US Dollars". + * If there are 3 currency signs in the currency pattern, + * the 3 currency signs will be replaced by currency plural name. + */ + PluralRules* fPluralRules; + + // locale + Locale* fLocale; + +private: + /** + * An internal status variable used to indicate that the object is in an 'invalid' state. + * Used by copy constructor, the assignment operator and the clone method. + */ + UErrorCode fInternalStatus; +}; + + +inline bool +CurrencyPluralInfo::operator!=(const CurrencyPluralInfo& info) const { + return !operator==(info); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _CURRPINFO +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currunit.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currunit.h new file mode 100644 index 0000000000000000000000000000000000000000..3b367b052bd2372b9841256ec1f80bb266d98da3 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/currunit.h @@ -0,0 +1,146 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2004-2014, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: April 26, 2004 +* Since: ICU 3.0 +********************************************************************** +*/ +#ifndef __CURRENCYUNIT_H__ +#define __CURRENCYUNIT_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/measunit.h" + +/** + * \file + * \brief C++ API: Currency Unit Information. + */ + +U_NAMESPACE_BEGIN + +/** + * A unit of currency, such as USD (U.S. dollars) or JPY (Japanese + * yen). This class is a thin wrapper over a char16_t string that + * subclasses MeasureUnit, for use with Measure and MeasureFormat. + * + * @author Alan Liu + * @stable ICU 3.0 + */ +class U_I18N_API CurrencyUnit: public MeasureUnit { + public: + /** + * Default constructor. Initializes currency code to "XXX" (no currency). + * @stable ICU 60 + */ + CurrencyUnit(); + + /** + * Construct an object with the given ISO currency code. + * + * @param isoCode the 3-letter ISO 4217 currency code; must have + * length 3 and need not be NUL-terminated. If nullptr, the currency + * is initialized to the unknown currency XXX. + * @param ec input-output error code. If the isoCode is invalid, + * then this will be set to a failing value. + * @stable ICU 3.0 + */ + CurrencyUnit(ConstChar16Ptr isoCode, UErrorCode &ec); + + /** + * Construct an object with the given ISO currency code. + * + * @param isoCode the 3-letter ISO 4217 currency code; must have + * length 3. If invalid, the currency is initialized to XXX. + * @param ec input-output error code. If the isoCode is invalid, + * then this will be set to a failing value. + * @stable ICU 64 + */ + CurrencyUnit(StringPiece isoCode, UErrorCode &ec); + + /** + * Copy constructor + * @stable ICU 3.0 + */ + CurrencyUnit(const CurrencyUnit& other); + + /** + * Copy constructor from MeasureUnit. This constructor allows you to + * restore a CurrencyUnit that was sliced to MeasureUnit. + * + * @param measureUnit The MeasureUnit to copy from. + * @param ec Set to a failing value if the MeasureUnit is not a currency. + * @stable ICU 60 + */ + CurrencyUnit(const MeasureUnit& measureUnit, UErrorCode &ec); + + /** + * Assignment operator + * @stable ICU 3.0 + */ + CurrencyUnit& operator=(const CurrencyUnit& other); + + /** + * Return a polymorphic clone of this object. The result will + * have the same class as returned by getDynamicClassID(). + * @stable ICU 3.0 + */ + virtual CurrencyUnit* clone() const override; + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~CurrencyUnit(); + + /** + * Returns a unique class ID for this object POLYMORPHICALLY. + * This method implements a simple form of RTTI used by ICU. + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 3.0 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * Returns the class ID for this class. This is used to compare to + * the return value of getDynamicClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 3.0 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * Return the ISO currency code of this object. + * @stable ICU 3.0 + */ + inline const char16_t* getISOCurrency() const; + + private: + /** + * The ISO 4217 code of this object. + */ + char16_t isoCode[4]; +}; + +inline const char16_t* CurrencyUnit::getISOCurrency() const { + return isoCode; +} + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __CURRENCYUNIT_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/datefmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/datefmt.h new file mode 100644 index 0000000000000000000000000000000000000000..27240a4e1c6dd21462a23796cecb564acfb35ebd --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/datefmt.h @@ -0,0 +1,969 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************** + * Copyright (C) 1997-2016, International Business Machines + * Corporation and others. All Rights Reserved. + ******************************************************************************** + * + * File DATEFMT.H + * + * Modification History: + * + * Date Name Description + * 02/19/97 aliu Converted from java. + * 04/01/97 aliu Added support for centuries. + * 07/23/98 stephen JDK 1.2 sync + * 11/15/99 weiv Added support for week of year/day of week formatting + ******************************************************************************** + */ + +#ifndef DATEFMT_H +#define DATEFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/udat.h" +#include "unicode/calendar.h" +#include "unicode/numfmt.h" +#include "unicode/format.h" +#include "unicode/locid.h" +#include "unicode/enumset.h" +#include "unicode/udisplaycontext.h" + +/** + * \file + * \brief C++ API: Abstract class for converting dates. + */ + +U_NAMESPACE_BEGIN + +class TimeZone; +class DateTimePatternGenerator; + +/** + * \cond + * Export an explicit template instantiation. (See digitlst.h, datefmt.h, and others.) + * (When building DLLs for Windows this is required.) + */ +#if U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN && !defined(U_IN_DOXYGEN) +template class U_I18N_API EnumSet; +#endif +/** \endcond */ + +/** + * DateFormat is an abstract class for a family of classes that convert dates and + * times from their internal representations to textual form and back again in a + * language-independent manner. Converting from the internal representation (milliseconds + * since midnight, January 1, 1970) to text is known as "formatting," and converting + * from text to millis is known as "parsing." We currently define only one concrete + * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal + * date formatting and parsing actions. + *

+ * DateFormat helps you to format and parse dates for any locale. Your code can + * be completely independent of the locale conventions for months, days of the + * week, or even the calendar format: lunar vs. solar. + *

+ * To format a date for the current Locale, use one of the static factory + * methods: + *

+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      UDate myDate = Calendar::getNow();
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ * \endcode
+ * 
+ * If you are formatting multiple numbers, it is more efficient to get the + * format and use it multiple times so that the system doesn't have to fetch the + * information about the local language and country conventions multiple times. + *
+ * \code
+ *      DateFormat* df = DateFormat::createDateInstance();
+ *      UnicodeString myString;
+ *      UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *      for (int32_t i = 0; i < 3; ++i) {
+ *          myString.remove();
+ *          cout << df->format( myDateArr[i], myString ) << endl;
+ *      }
+ * \endcode
+ * 
+ * To get specific fields of a date, you can use UFieldPosition to + * get specific fields. + *
+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      FieldPosition pos(DateFormat::YEAR_FIELD);
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ *      cout << myString << endl;
+ *      cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
+ * \endcode
+ * 
+ * To format a date for a different Locale, specify it in the call to + * createDateInstance(). + *
+ * \code
+ *       DateFormat* df =
+ *           DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
+ * \endcode
+ * 
+ * You can use a DateFormat to parse also. + *
+ * \code
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       UDate myDate = df->parse(myString, status);
+ * \endcode
+ * 
+ * Use createDateInstance() to produce the normal date format for that country. + * There are other static factory methods available. Use createTimeInstance() + * to produce the normal time format for that country. Use createDateTimeInstance() + * to produce a DateFormat that formats both date and time. You can pass in + * different options to these factory methods to control the length of the + * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the + * locale, but generally: + *
    + *
  • SHORT is completely numeric, such as 12/13/52 or 3:30pm + *
  • MEDIUM is longer, such as Jan 12, 1952 + *
  • LONG is longer, such as January 12, 1952 or 3:30:32pm + *
  • FULL is pretty completely specified, such as + * Tuesday, April 12, 1952 AD or 3:30:42pm PST. + *
+ * You can also set the time zone on the format if you wish. If you want even + * more control over the format or parsing, (or want to give your users more + * control), you can try casting the DateFormat you get from the factory methods + * to a SimpleDateFormat. This will work for the majority of countries; just + * remember to check getDynamicClassID() before carrying out the cast. + *

+ * You can also use forms of the parse and format methods with ParsePosition and + * FieldPosition to allow you to + *

    + *
  • Progressively parse through pieces of a string. + *
  • Align any particular field, or find out where it is for selection + * on the screen. + *
+ * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API DateFormat : public Format { +public: + + /** + * Constants for various style patterns. These reflect the order of items in + * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns, + * the default date-time pattern, and 4 date-time patterns. Each block of 4 values + * in the resource occurs in the order full, long, medium, short. + * @stable ICU 2.4 + */ + enum EStyle + { + kNone = -1, + + kFull = 0, + kLong = 1, + kMedium = 2, + kShort = 3, + + kDateOffset = kShort + 1, + // kFull + kDateOffset = 4 + // kLong + kDateOffset = 5 + // kMedium + kDateOffset = 6 + // kShort + kDateOffset = 7 + + kDateTime = 8, + // Default DateTime + + kDateTimeOffset = kDateTime + 1, + // kFull + kDateTimeOffset = 9 + // kLong + kDateTimeOffset = 10 + // kMedium + kDateTimeOffset = 11 + // kShort + kDateTimeOffset = 12 + + // relative dates + kRelative = (1 << 7), + + kFullRelative = (kFull | kRelative), + + kLongRelative = kLong | kRelative, + + kMediumRelative = kMedium | kRelative, + + kShortRelative = kShort | kRelative, + + + kDefault = kMedium, + + + + /** + * These constants are provided for backwards compatibility only. + * Please use the C++ style constants defined above. + */ + FULL = kFull, + LONG = kLong, + MEDIUM = kMedium, + SHORT = kShort, + DEFAULT = kDefault, + DATE_OFFSET = kDateOffset, + NONE = kNone, + DATE_TIME = kDateTime + }; + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~DateFormat(); + + /** + * Clones this object polymorphically. + * The caller owns the result and should delete it when done. + * @return clone, or nullptr if an error occurred + * @stable ICU 2.0 + */ + virtual DateFormat* clone() const override = 0; + + /** + * Equality operator. Returns true if the two formats have the same behavior. + * @stable ICU 2.0 + */ + virtual bool operator==(const Format&) const override; + + + using Format::format; + + /** + * Format an object to produce a string. This method handles Formattable + * objects with a UDate type. If a the Formattable object type is not a Date, + * then it returns a failing UErrorCode. + * + * @param obj The object to format. Must be a Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; + + /** + * Format an object to produce a string. This method handles Formattable + * objects with a UDate type. If a the Formattable object type is not a Date, + * then it returns a failing UErrorCode. + * + * @param obj The object to format. Must be a Date. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const override; + /** + * Formats a date into a date/time string. This is an abstract method which + * concrete subclasses must implement. + *

+ * On input, the FieldPosition parameter may have its "field" member filled with + * an enum value specifying a field. On output, the FieldPosition will be filled + * in with the text offsets for that field. + *

For example, given a time text + * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is + * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and + * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. + *

Notice + * that if the same time field appears more than once in a pattern, the status will + * be set for the first occurrence of that time field. For instance, + * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" + * using the pattern "h a z (zzzz)" and the alignment field + * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and + * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first + * occurrence of the timezone pattern character 'z'. + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. When the calendar type is + * different from the internal calendar held by this + * DateFormat instance, the date and the time zone will + * be inherited from the input calendar, but other calendar + * field values will be calculated by the internal calendar. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired (see examples above) + * On output: the offsets of the alignment field (see examples above) + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.1 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const = 0; + + /** + * Formats a date into a date/time string. Subclasses should implement this method. + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. When the calendar type is + * different from the internal calendar held by this + * DateFormat instance, the date and the time zone will + * be inherited from the input calendar, but other calendar + * field values will be calculated by the internal calendar. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be nullptr. + * @param status error status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(Calendar& cal, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Formats a UDate into a date/time string. + *

+ * On input, the FieldPosition parameter may have its "field" member filled with + * an enum value specifying a field. On output, the FieldPosition will be filled + * in with the text offsets for that field. + *

For example, given a time text + * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is + * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and + * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. + *

Notice + * that if the same time field appears more than once in a pattern, the status will + * be set for the first occurrence of that time field. For instance, + * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" + * using the pattern "h a z (zzzz)" and the alignment field + * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and + * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first + * occurrence of the timezone pattern character 'z'. + * + * @param date UDate to be formatted into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired (see examples above) + * On output: the offsets of the alignment field (see examples above) + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format( UDate date, + UnicodeString& appendTo, + FieldPosition& fieldPosition) const; + + /** + * Formats a UDate into a date/time string. + * + * @param date UDate to be formatted into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. Can be nullptr. + * @param status error status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(UDate date, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Formats a UDate into a date/time string. If there is a problem, you won't + * know, using this method. Use the overloaded format() method which takes a + * FieldPosition& to detect formatting problems. + * + * @param date The UDate value to be formatted into a string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(UDate date, UnicodeString& appendTo) const; + + /** + * Parse a date/time string. For example, a time text "07/10/96 4:5 PM, PDT" + * will be parsed into a UDate that is equivalent to Date(837039928046). + * Parsing begins at the beginning of the string and proceeds as far as + * possible. Assuming no parse errors were encountered, this function + * doesn't return any information about how much of the string was consumed + * by the parsing. If you need that information, use the version of + * parse() that takes a ParsePosition. + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * @see DateFormat::setLenient(boolean) + *

+ * Note that the normal date formats associated with some calendars - such + * as the Chinese lunar calendar - do not specify enough fields to enable + * dates to be parsed unambiguously. In the case of the Chinese lunar + * calendar, while the year within the current 60-year cycle is specified, + * the number of such cycles since the start date of the calendar (in the + * ERA field of the Calendar object) is not normally part of the format, + * and parsing may assume the wrong era. For cases such as this it is + * recommended that clients parse using the method + * parse(const UnicodeString&, Calendar& cal, ParsePosition&) + * with the Calendar passed in set to the current date, or to a date + * within the era/cycle that should be assumed if absent in the format. + * + * @param text The date/time string to be parsed into a UDate value. + * @param status Output param to be set to success/failure code. If + * 'text' cannot be parsed, it will be set to a failure + * code. + * @return The parsed UDate value, if successful. + * @stable ICU 2.0 + */ + virtual UDate parse( const UnicodeString& text, + UErrorCode& status) const; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * @see DateFormat::setLenient(boolean) + * + * @param text The date/time string to be parsed. + * @param cal A Calendar set on input to the date and time to be used for + * missing values in the date/time string being parsed, and set + * on output to the parsed date/time. When the calendar type is + * different from the internal calendar held by this DateFormat + * instance, the internal calendar will be cloned to a work + * calendar set to the same milliseconds and time zone as the + * cal parameter, field values will be parsed based on the work + * calendar, then the result (milliseconds and time zone) will + * be set in this calendar. + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @stable ICU 2.1 + */ + virtual void parse( const UnicodeString& text, + Calendar& cal, + ParsePosition& pos) const = 0; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * @see DateFormat::setLenient(boolean) + *

+ * Note that the normal date formats associated with some calendars - such + * as the Chinese lunar calendar - do not specify enough fields to enable + * dates to be parsed unambiguously. In the case of the Chinese lunar + * calendar, while the year within the current 60-year cycle is specified, + * the number of such cycles since the start date of the calendar (in the + * ERA field of the Calendar object) is not normally part of the format, + * and parsing may assume the wrong era. For cases such as this it is + * recommended that clients parse using the method + * parse(const UnicodeString&, Calendar& cal, ParsePosition&) + * with the Calendar passed in set to the current date, or to a date + * within the era/cycle that should be assumed if absent in the format. + * + * @param text The date/time string to be parsed into a UDate value. + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @return A valid UDate if the input could be parsed. + * @stable ICU 2.0 + */ + UDate parse( const UnicodeString& text, + ParsePosition& pos) const; + + /** + * Parse a string to produce an object. This methods handles parsing of + * date/time strings into Formattable objects with UDate types. + *

+ * Before calling, set parse_pos.index to the offset you want to start + * parsing at in the source. After calling, parse_pos.index is the end of + * the text you parsed. If error occurs, index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with a successful parse), + * while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @stable ICU 2.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const override; + + /** + * Create a default date/time formatter that uses the SHORT style for both + * the date and the time. + * + * @return A date/time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createInstance(void); + + /** + * Creates a time formatter with the given formatting style for the given + * locale. + * + * @param style The given formatting style. For example, + * SHORT for "h:mm a" in the US locale. Relative + * time styles are not currently supported. + * @param aLocale The given locale. + * @return A time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault, + const Locale& aLocale = Locale::getDefault()); + + /** + * Creates a date formatter with the given formatting style for the given + * const locale. + * + * @param style The given formatting style. For example, SHORT for "M/d/yy" in the + * US locale. As currently implemented, relative date formatting only + * affects a limited range of calendar days before or after the + * current date, based on the CLDR <field type="day">/<relative> data: + * For example, in English, "Yesterday", "Today", and "Tomorrow". + * Outside of this range, dates are formatted using the corresponding + * non-relative style. + * @param aLocale The given locale. + * @return A date formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault, + const Locale& aLocale = Locale::getDefault()); + + /** + * Creates a date/time formatter with the given formatting styles for the + * given locale. + * + * @param dateStyle The given formatting style for the date portion of the result. + * For example, SHORT for "M/d/yy" in the US locale. As currently + * implemented, relative date formatting only affects a limited range + * of calendar days before or after the current date, based on the + * CLDR <field type="day">/<relative> data: For example, in English, + * "Yesterday", "Today", and "Tomorrow". Outside of this range, dates + * are formatted using the corresponding non-relative style. + * @param timeStyle The given formatting style for the time portion of the result. + * For example, SHORT for "h:mm a" in the US locale. Relative + * time styles are not currently supported. + * @param aLocale The given locale. + * @return A date/time formatter which the caller owns. + * @stable ICU 2.0 + */ + static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault, + EStyle timeStyle = kDefault, + const Locale& aLocale = Locale::getDefault()); + +#ifndef U_HIDE_INTERNAL_API + /** + * Returns the best pattern given a skeleton and locale. + * @param locale the locale + * @param skeleton the skeleton + * @param status ICU error returned here + * @return the best pattern. + * @internal For ICU use only. + */ + static UnicodeString getBestPattern( + const Locale &locale, + const UnicodeString &skeleton, + UErrorCode &status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Creates a date/time formatter for the given skeleton and + * default locale. + * + * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can + * be in any order, and this method uses the locale to + * map the skeleton to a pattern that includes locale + * specific separators with the fields in the appropriate + * order for that locale. + * @param status Any error returned here. + * @return A date/time formatter which the caller owns. + * @stable ICU 55 + */ + static DateFormat* U_EXPORT2 createInstanceForSkeleton( + const UnicodeString& skeleton, + UErrorCode &status); + + /** + * Creates a date/time formatter for the given skeleton and locale. + * + * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can + * be in any order, and this method uses the locale to + * map the skeleton to a pattern that includes locale + * specific separators with the fields in the appropriate + * order for that locale. + * @param locale The given locale. + * @param status Any error returned here. + * @return A date/time formatter which the caller owns. + * @stable ICU 55 + */ + static DateFormat* U_EXPORT2 createInstanceForSkeleton( + const UnicodeString& skeleton, + const Locale &locale, + UErrorCode &status); + + /** + * Creates a date/time formatter for the given skeleton and locale. + * + * @param calendarToAdopt the calendar returned DateFormat is to use. + * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can + * be in any order, and this method uses the locale to + * map the skeleton to a pattern that includes locale + * specific separators with the fields in the appropriate + * order for that locale. + * @param locale The given locale. + * @param status Any error returned here. + * @return A date/time formatter which the caller owns. + * @stable ICU 55 + */ + static DateFormat* U_EXPORT2 createInstanceForSkeleton( + Calendar *calendarToAdopt, + const UnicodeString& skeleton, + const Locale &locale, + UErrorCode &status); + + + /** + * Gets the set of locales for which DateFormats are installed. + * @param count Filled in with the number of locales in the list that is returned. + * @return the set of locales for which DateFormats are installed. The caller + * does NOT own this list and must not delete it. + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + /** + * Returns whether both date/time parsing in the encapsulated Calendar object and DateFormat whitespace & + * numeric processing is lenient. + * @stable ICU 2.0 + */ + virtual UBool isLenient(void) const; + + /** + * Specifies whether date/time parsing is to be lenient. With + * lenient parsing, the parser may use heuristics to interpret inputs that + * do not precisely match this object's format. Without lenient parsing, + * inputs must match this object's format more closely. + * + * Note: ICU 53 introduced finer grained control of leniency (and added + * new control points) making the preferred method a combination of + * setCalendarLenient() & setBooleanAttribute() calls. + * This method supports prior functionality but may not support all + * future leniency control & behavior of DateFormat. For control of pre 53 leniency, + * Calendar and DateFormat whitespace & numeric tolerance, this method is safe to + * use. However, mixing leniency control via this method and modification of the + * newer attributes via setBooleanAttribute() may produce undesirable + * results. + * + * @param lenient True specifies date/time interpretation to be lenient. + * @see Calendar::setLenient + * @stable ICU 2.0 + */ + virtual void setLenient(UBool lenient); + + + /** + * Returns whether date/time parsing in the encapsulated Calendar object processing is lenient. + * @stable ICU 53 + */ + virtual UBool isCalendarLenient(void) const; + + + /** + * Specifies whether encapsulated Calendar date/time parsing is to be lenient. With + * lenient parsing, the parser may use heuristics to interpret inputs that + * do not precisely match this object's format. Without lenient parsing, + * inputs must match this object's format more closely. + * @param lenient when true, parsing is lenient + * @see com.ibm.icu.util.Calendar#setLenient + * @stable ICU 53 + */ + virtual void setCalendarLenient(UBool lenient); + + + /** + * Gets the calendar associated with this date/time formatter. + * The calendar is owned by the formatter and must not be modified. + * Also, the calendar does not reflect the results of a parse operation. + * To parse to a calendar, use {@link #parse(const UnicodeString&, Calendar& cal, ParsePosition&) const parse(const UnicodeString&, Calendar& cal, ParsePosition&)} + * @return the calendar associated with this date/time formatter. + * @stable ICU 2.0 + */ + virtual const Calendar* getCalendar(void) const; + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. The caller should + * not delete the Calendar object after it is adopted by this call. + * Adopting a new calendar will change to the default symbols. + * + * @param calendarToAdopt Calendar object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptCalendar(Calendar* calendarToAdopt); + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. + * + * @param newCalendar Calendar object to be set. + * @stable ICU 2.0 + */ + virtual void setCalendar(const Calendar& newCalendar); + + + /** + * Gets the number formatter which this date/time formatter uses to format + * and parse the numeric portions of the pattern. + * @return the number formatter which this date/time formatter uses. + * @stable ICU 2.0 + */ + virtual const NumberFormat* getNumberFormat(void) const; + + /** + * Allows you to set the number formatter. The caller should + * not delete the NumberFormat object after it is adopted by this call. + * @param formatToAdopt NumberFormat object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptNumberFormat(NumberFormat* formatToAdopt); + + /** + * Allows you to set the number formatter. + * @param newNumberFormat NumberFormat object to be set. + * @stable ICU 2.0 + */ + virtual void setNumberFormat(const NumberFormat& newNumberFormat); + + /** + * Returns a reference to the TimeZone used by this DateFormat's calendar. + * @return the time zone associated with the calendar of DateFormat. + * @stable ICU 2.0 + */ + virtual const TimeZone& getTimeZone(void) const; + + /** + * Sets the time zone for the calendar of this DateFormat object. The caller + * no longer owns the TimeZone object and should not delete it after this call. + * @param zoneToAdopt the TimeZone to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptTimeZone(TimeZone* zoneToAdopt); + + /** + * Sets the time zone for the calendar of this DateFormat object. + * @param zone the new time zone. + * @stable ICU 2.0 + */ + virtual void setTimeZone(const TimeZone& zone); + + /** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. + * @param value The UDisplayContext value to set. + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @stable ICU 53 + */ + virtual void setContext(UDisplayContext value, UErrorCode& status); + + /** + * Get the formatter's UDisplayContext value for the specified UDisplayContextType, + * such as UDISPCTX_TYPE_CAPITALIZATION. + * @param type The UDisplayContextType whose value to return + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @return The UDisplayContextValue for the specified type. + * @stable ICU 53 + */ + virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; + + /** + * Sets an boolean attribute on this DateFormat. + * May return U_UNSUPPORTED_ERROR if this instance does not support + * the specified attribute. + * @param attr the attribute to set + * @param newvalue new value + * @param status the error type + * @return *this - for chaining (example: format.setAttribute(...).setAttribute(...) ) + * @stable ICU 53 + */ + + virtual DateFormat& U_EXPORT2 setBooleanAttribute(UDateFormatBooleanAttribute attr, + UBool newvalue, + UErrorCode &status); + + /** + * Returns a boolean from this DateFormat + * May return U_UNSUPPORTED_ERROR if this instance does not support + * the specified attribute. + * @param attr the attribute to set + * @param status the error type + * @return the attribute value. Undefined if there is an error. + * @stable ICU 53 + */ + virtual UBool U_EXPORT2 getBooleanAttribute(UDateFormatBooleanAttribute attr, UErrorCode &status) const; + +protected: + /** + * Default constructor. Creates a DateFormat with no Calendar or NumberFormat + * associated with it. This constructor depends on the subclasses to fill in + * the calendar and numberFormat fields. + * @stable ICU 2.0 + */ + DateFormat(); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + DateFormat(const DateFormat&); + + /** + * Default assignment operator. + * @stable ICU 2.0 + */ + DateFormat& operator=(const DateFormat&); + + /** + * The calendar that DateFormat uses to produce the time field values needed + * to implement date/time formatting. Subclasses should generally initialize + * this to the default calendar for the locale associated with this DateFormat. + * @stable ICU 2.4 + */ + Calendar* fCalendar; + + /** + * The number formatter that DateFormat uses to format numbers in dates and + * times. Subclasses should generally initialize this to the default number + * format for the locale associated with this DateFormat. + * @stable ICU 2.4 + */ + NumberFormat* fNumberFormat; + + +private: + + /** + * Gets the date/time formatter with the given formatting styles for the + * given locale. + * @param dateStyle the given date formatting style. + * @param timeStyle the given time formatting style. + * @param inLocale the given locale. + * @return a date/time formatter, or 0 on failure. + */ + static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale& inLocale); + + + /** + * enum set of active boolean attributes for this instance + */ + EnumSet fBoolFlags; + + + UDisplayContext fCapitalizationContext; + friend class DateFmtKeyByStyle; + +public: +#ifndef U_HIDE_OBSOLETE_API + /** + * Field selector for FieldPosition for DateFormat fields. + * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be + * removed in that release + */ + enum EField + { + // Obsolete; use UDateFormatField instead + kEraField = UDAT_ERA_FIELD, + kYearField = UDAT_YEAR_FIELD, + kMonthField = UDAT_MONTH_FIELD, + kDateField = UDAT_DATE_FIELD, + kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD, + kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD, + kMinuteField = UDAT_MINUTE_FIELD, + kSecondField = UDAT_SECOND_FIELD, + kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD, + kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD, + kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD, + kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, + kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD, + kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD, + kAmPmField = UDAT_AM_PM_FIELD, + kHour1Field = UDAT_HOUR1_FIELD, + kHour0Field = UDAT_HOUR0_FIELD, + kTimezoneField = UDAT_TIMEZONE_FIELD, + kYearWOYField = UDAT_YEAR_WOY_FIELD, + kDOWLocalField = UDAT_DOW_LOCAL_FIELD, + kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD, + kJulianDayField = UDAT_JULIAN_DAY_FIELD, + kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD, + + // Obsolete; use UDateFormatField instead + ERA_FIELD = UDAT_ERA_FIELD, + YEAR_FIELD = UDAT_YEAR_FIELD, + MONTH_FIELD = UDAT_MONTH_FIELD, + DATE_FIELD = UDAT_DATE_FIELD, + HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD, + HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD, + MINUTE_FIELD = UDAT_MINUTE_FIELD, + SECOND_FIELD = UDAT_SECOND_FIELD, + MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD, + DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD, + DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD, + DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, + WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD, + WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD, + AM_PM_FIELD = UDAT_AM_PM_FIELD, + HOUR1_FIELD = UDAT_HOUR1_FIELD, + HOUR0_FIELD = UDAT_HOUR0_FIELD, + TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD + }; +#endif /* U_HIDE_OBSOLETE_API */ +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _DATEFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dbbi.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dbbi.h new file mode 100644 index 0000000000000000000000000000000000000000..3de9cc381408c51c77f1414ea62f9f180adeda7a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dbbi.h @@ -0,0 +1,48 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2006,2013 IBM Corp. All rights reserved. +********************************************************************** +* Date Name Description +* 12/1/99 rgillam Complete port from Java. +* 01/13/2000 helena Added UErrorCode to ctors. +********************************************************************** +*/ + +#ifndef DBBI_H +#define DBBI_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/rbbi.h" + +#if !UCONFIG_NO_BREAK_ITERATION + +/** + * \file + * \brief C++ API: Dictionary Based Break Iterator + */ + +U_NAMESPACE_BEGIN + +#ifndef U_HIDE_DEPRECATED_API +/** + * An obsolete subclass of RuleBasedBreakIterator. Handling of dictionary- + * based break iteration has been folded into the base class. This class + * is deprecated as of ICU 3.6. + * @deprecated ICU 3.6 + */ +typedef RuleBasedBreakIterator DictionaryBasedBreakIterator; + +#endif /* U_HIDE_DEPRECATED_API */ + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dcfmtsym.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dcfmtsym.h new file mode 100644 index 0000000000000000000000000000000000000000..6b79c99000e774b1345d43efaa666bc3db9bcd05 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dcfmtsym.h @@ -0,0 +1,614 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File DCFMTSYM.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/18/97 clhuang Updated per C++ implementation. +* 03/27/97 helena Updated to pass the simple test after code review. +* 08/26/97 aliu Added currency/intl currency symbol support. +* 07/22/98 stephen Changed to match C++ style +* currencySymbol -> fCurrencySymbol +* Constants changed from CAPS to kCaps +* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes +* 09/22/00 grhoten Marked deprecation tags with a pointer to replacement +* functions. +******************************************************************************** +*/ + +#ifndef DCFMTSYM_H +#define DCFMTSYM_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uchar.h" +#include "unicode/uobject.h" +#include "unicode/locid.h" +#include "unicode/numsys.h" +#include "unicode/unum.h" +#include "unicode/unistr.h" + +/** + * \file + * \brief C++ API: Symbols for formatting numbers. + */ + + +U_NAMESPACE_BEGIN + +/** + * This class represents the set of symbols needed by DecimalFormat + * to format numbers. DecimalFormat creates for itself an instance of + * DecimalFormatSymbols from its locale data. If you need to change any + * of these symbols, you can get the DecimalFormatSymbols object from + * your DecimalFormat and modify it. + *

+ * Here are the special characters used in the parts of the + * subpattern, with notes on their usage. + *

+ * \code
+ *        Symbol   Meaning
+ *          0      a digit
+ *          #      a digit, zero shows as absent
+ *          .      placeholder for decimal separator
+ *          ,      placeholder for grouping separator.
+ *          ;      separates formats.
+ *          -      default negative prefix.
+ *          %      divide by 100 and show as percentage
+ *          X      any other characters can be used in the prefix or suffix
+ *          '      used to quote special characters in a prefix or suffix.
+ * \endcode
+ *  
+ * [Notes] + *

+ * If there is no explicit negative subpattern, - is prefixed to the + * positive form. That is, "0.00" alone is equivalent to "0.00;-0.00". + *

+ * The grouping separator is commonly used for thousands, but in some + * countries for ten-thousands. The interval is a constant number of + * digits between the grouping characters, such as 100,000,000 or 1,0000,0000. + * If you supply a pattern with multiple grouping characters, the interval + * between the last one and the end of the integer is the one that is + * used. So "#,##,###,####" == "######,####" == "##,####,####". + */ +class U_I18N_API DecimalFormatSymbols : public UObject { +public: + /** + * Constants for specifying a number format symbol. + * @stable ICU 2.0 + */ + enum ENumberFormatSymbol { + /** The decimal separator */ + kDecimalSeparatorSymbol, + /** The grouping separator */ + kGroupingSeparatorSymbol, + /** The pattern separator */ + kPatternSeparatorSymbol, + /** The percent sign */ + kPercentSymbol, + /** Zero*/ + kZeroDigitSymbol, + /** Character representing a digit in the pattern */ + kDigitSymbol, + /** The minus sign */ + kMinusSignSymbol, + /** The plus sign */ + kPlusSignSymbol, + /** The currency symbol */ + kCurrencySymbol, + /** The international currency symbol */ + kIntlCurrencySymbol, + /** The monetary separator */ + kMonetarySeparatorSymbol, + /** The exponential symbol */ + kExponentialSymbol, + /** Per mill symbol - replaces kPermillSymbol */ + kPerMillSymbol, + /** Escape padding character */ + kPadEscapeSymbol, + /** Infinity symbol */ + kInfinitySymbol, + /** Nan symbol */ + kNaNSymbol, + /** Significant digit symbol + * @stable ICU 3.0 */ + kSignificantDigitSymbol, + /** The monetary grouping separator + * @stable ICU 3.6 + */ + kMonetaryGroupingSeparatorSymbol, + /** One + * @stable ICU 4.6 + */ + kOneDigitSymbol, + /** Two + * @stable ICU 4.6 + */ + kTwoDigitSymbol, + /** Three + * @stable ICU 4.6 + */ + kThreeDigitSymbol, + /** Four + * @stable ICU 4.6 + */ + kFourDigitSymbol, + /** Five + * @stable ICU 4.6 + */ + kFiveDigitSymbol, + /** Six + * @stable ICU 4.6 + */ + kSixDigitSymbol, + /** Seven + * @stable ICU 4.6 + */ + kSevenDigitSymbol, + /** Eight + * @stable ICU 4.6 + */ + kEightDigitSymbol, + /** Nine + * @stable ICU 4.6 + */ + kNineDigitSymbol, + /** Multiplication sign. + * @stable ICU 54 + */ + kExponentMultiplicationSymbol, +#ifndef U_HIDE_INTERNAL_API + /** Approximately sign. + * @internal + */ + kApproximatelySignSymbol, +#endif /* U_HIDE_INTERNAL_API */ + /** count symbol constants */ + kFormatSymbolCount = kExponentMultiplicationSymbol + 2 + }; + + /** + * Create a DecimalFormatSymbols object for the given locale. + * + * @param locale The locale to get symbols for. + * @param status Input/output parameter, set to success or + * failure code upon return. + * @stable ICU 2.0 + */ + DecimalFormatSymbols(const Locale& locale, UErrorCode& status); + + /** + * Creates a DecimalFormatSymbols instance for the given locale with digits and symbols + * corresponding to the given NumberingSystem. + * + * This constructor behaves equivalently to the normal constructor called with a locale having a + * "numbers=xxxx" keyword specifying the numbering system by name. + * + * In this constructor, the NumberingSystem argument will be used even if the locale has its own + * "numbers=xxxx" keyword. + * + * @param locale The locale to get symbols for. + * @param ns The numbering system. + * @param status Input/output parameter, set to success or + * failure code upon return. + * @stable ICU 60 + */ + DecimalFormatSymbols(const Locale& locale, const NumberingSystem& ns, UErrorCode& status); + + /** + * Create a DecimalFormatSymbols object for the default locale. + * This constructor will not fail. If the resource file data is + * not available, it will use hard-coded last-resort data and + * set status to U_USING_FALLBACK_ERROR. + * + * @param status Input/output parameter, set to success or + * failure code upon return. + * @stable ICU 2.0 + */ + DecimalFormatSymbols(UErrorCode& status); + + /** + * Creates a DecimalFormatSymbols object with last-resort data. + * Intended for callers who cache the symbols data and + * set all symbols on the resulting object. + * + * The last-resort symbols are similar to those for the root data, + * except that the grouping separators are empty, + * the NaN symbol is U+FFFD rather than "NaN", + * and the CurrencySpacing patterns are empty. + * + * @param status Input/output parameter, set to success or + * failure code upon return. + * @return last-resort symbols + * @stable ICU 52 + */ + static DecimalFormatSymbols* createWithLastResortData(UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + DecimalFormatSymbols(const DecimalFormatSymbols&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + DecimalFormatSymbols& operator=(const DecimalFormatSymbols&); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~DecimalFormatSymbols(); + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the object to be compared with. + * @return true if another object is semantically equal to this one. + * @stable ICU 2.0 + */ + bool operator==(const DecimalFormatSymbols& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the object to be compared with. + * @return true if another object is semantically unequal to this one. + * @stable ICU 2.0 + */ + bool operator!=(const DecimalFormatSymbols& other) const { return !operator==(other); } + + /** + * Get one of the format symbols by its enum constant. + * Each symbol is stored as a string so that graphemes + * (characters with modifier letters) can be used. + * + * @param symbol Constant to indicate a number format symbol. + * @return the format symbols by the param 'symbol' + * @stable ICU 2.0 + */ + inline UnicodeString getSymbol(ENumberFormatSymbol symbol) const; + + /** + * Set one of the format symbols by its enum constant. + * Each symbol is stored as a string so that graphemes + * (characters with modifier letters) can be used. + * + * @param symbol Constant to indicate a number format symbol. + * @param value value of the format symbol + * @param propagateDigits If false, setting the zero digit will not automatically set 1-9. + * The default behavior is to automatically set 1-9 if zero is being set and the value + * it is being set to corresponds to a known Unicode zero digit. + * @stable ICU 2.0 + */ + void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propagateDigits); + +#ifndef U_HIDE_INTERNAL_API + /** + * Loads symbols for the specified currency into this instance. + * + * This method is internal. If you think it should be public, file a ticket. + * + * @internal + */ + void setCurrency(const char16_t* currency, UErrorCode& status); +#endif // U_HIDE_INTERNAL_API + + /** + * Returns the locale for which this object was constructed. + * @stable ICU 2.6 + */ + inline Locale getLocale() const; + + /** + * Returns the locale for this object. Two flavors are available: + * valid and actual locale. + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; + + /** + * Get pattern string for 'CurrencySpacing' that can be applied to + * currency format. + * This API gets the CurrencySpacing data from ResourceBundle. The pattern can + * be empty if there is no data from current locale and its parent locales. + * + * @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT. + * @param beforeCurrency : true if the pattern is for before currency symbol. + * false if the pattern is for after currency symbol. + * @param status: Input/output parameter, set to success or + * failure code upon return. + * @return pattern string for currencyMatch, surroundingMatch or spaceInsert. + * Return empty string if there is no data for this locale and its parent + * locales. + * @stable ICU 4.8 + */ + const UnicodeString& getPatternForCurrencySpacing(UCurrencySpacing type, + UBool beforeCurrency, + UErrorCode& status) const; + /** + * Set pattern string for 'CurrencySpacing' that can be applied to + * currency format. + * + * @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT. + * @param beforeCurrency : true if the pattern is for before currency symbol. + * false if the pattern is for after currency symbol. + * @param pattern : pattern string to override current setting. + * @stable ICU 4.8 + */ + void setPatternForCurrencySpacing(UCurrencySpacing type, + UBool beforeCurrency, + const UnicodeString& pattern); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + DecimalFormatSymbols(); + + /** + * Initializes the symbols from the LocaleElements resource bundle. + * Note: The organization of LocaleElements badly needs to be + * cleaned up. + * + * @param locale The locale to get symbols for. + * @param success Input/output parameter, set to success or + * failure code upon return. + * @param useLastResortData determine if use last resort data + * @param ns The NumberingSystem to use; otherwise, fall + * back to the locale. + */ + void initialize(const Locale& locale, UErrorCode& success, + UBool useLastResortData = false, const NumberingSystem* ns = nullptr); + + /** + * Initialize the symbols with default values. + */ + void initialize(); + +public: + +#ifndef U_HIDE_INTERNAL_API + /** + * @internal For ICU use only + */ + inline UBool isCustomCurrencySymbol() const { + return fIsCustomCurrencySymbol; + } + + /** + * @internal For ICU use only + */ + inline UBool isCustomIntlCurrencySymbol() const { + return fIsCustomIntlCurrencySymbol; + } + + /** + * @internal For ICU use only + */ + inline UChar32 getCodePointZero() const { + return fCodePointZero; + } +#endif /* U_HIDE_INTERNAL_API */ + + /** + * _Internal_ function - more efficient version of getSymbol, + * returning a const reference to one of the symbol strings. + * The returned reference becomes invalid when the symbol is changed + * or when the DecimalFormatSymbols are destroyed. + * Note: moved \#ifndef U_HIDE_INTERNAL_API after this, since this is needed for inline in DecimalFormat + * + * This is not currently stable API, but if you think it should be stable, + * post a comment on the following ticket and the ICU team will take a look: + * https://unicode-org.atlassian.net/browse/ICU-13580 + * + * @param symbol Constant to indicate a number format symbol. + * @return the format symbol by the param 'symbol' + * @internal + */ + inline const UnicodeString& getConstSymbol(ENumberFormatSymbol symbol) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Returns the const UnicodeString reference, like getConstSymbol, + * corresponding to the digit with the given value. This is equivalent + * to accessing the symbol from getConstSymbol with the corresponding + * key, such as kZeroDigitSymbol or kOneDigitSymbol. + * + * This is not currently stable API, but if you think it should be stable, + * post a comment on the following ticket and the ICU team will take a look: + * https://unicode-org.atlassian.net/browse/ICU-13580 + * + * @param digit The digit, an integer between 0 and 9 inclusive. + * If outside the range 0 to 9, the zero digit is returned. + * @return the format symbol for the given digit. + * @internal This API is currently for ICU use only. + */ + inline const UnicodeString& getConstDigitSymbol(int32_t digit) const; + + /** + * Returns that pattern stored in currency info. Internal API for use by NumberFormat API. + * @internal + */ + inline const char16_t* getCurrencyPattern(void) const; + + /** + * Returns the numbering system with which this DecimalFormatSymbols was initialized. + * @internal + */ + inline const char* getNumberingSystemName(void) const; +#endif /* U_HIDE_INTERNAL_API */ + +private: + /** + * Private symbol strings. + * They are either loaded from a resource bundle or otherwise owned. + * setSymbol() clones the symbol string. + * Readonly aliases can only come from a resource bundle, so that we can always + * use fastCopyFrom() with them. + * + * If DecimalFormatSymbols becomes subclassable and the status of fSymbols changes + * from private to protected, + * or when fSymbols can be set any other way that allows them to be readonly aliases + * to non-resource bundle strings, + * then regular UnicodeString copies must be used instead of fastCopyFrom(). + * + */ + UnicodeString fSymbols[kFormatSymbolCount]; + + /** + * Non-symbol variable for getConstSymbol(). Always empty. + */ + UnicodeString fNoSymbol; + + /** + * Dealing with code points is faster than dealing with strings when formatting. Because of + * this, we maintain a value containing the zero code point that is used whenever digitStrings + * represents a sequence of ten code points in order. + * + *

If the value stored here is positive, it means that the code point stored in this value + * corresponds to the digitStrings array, and codePointZero can be used instead of the + * digitStrings array for the purposes of efficient formatting; if -1, then digitStrings does + * *not* contain a sequence of code points, and it must be used directly. + * + *

It is assumed that codePointZero always shadows the value in digitStrings. codePointZero + * should never be set directly; rather, it should be updated only when digitStrings mutates. + * That is, the flow of information is digitStrings -> codePointZero, not the other way. + */ + UChar32 fCodePointZero; + + Locale locale; + + char actualLocale[ULOC_FULLNAME_CAPACITY]; + char validLocale[ULOC_FULLNAME_CAPACITY]; + const char16_t* currPattern = nullptr; + + UnicodeString currencySpcBeforeSym[UNUM_CURRENCY_SPACING_COUNT]; + UnicodeString currencySpcAfterSym[UNUM_CURRENCY_SPACING_COUNT]; + UBool fIsCustomCurrencySymbol; + UBool fIsCustomIntlCurrencySymbol; + char nsName[kInternalNumSysNameCapacity+1] = {}; +}; + +// ------------------------------------- + +inline UnicodeString +DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const { + const UnicodeString *strPtr; + if(symbol < kFormatSymbolCount) { + strPtr = &fSymbols[symbol]; + } else { + strPtr = &fNoSymbol; + } + return *strPtr; +} + +// See comments above for this function. Not hidden with #ifdef U_HIDE_INTERNAL_API +inline const UnicodeString & +DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const { + const UnicodeString *strPtr; + if(symbol < kFormatSymbolCount) { + strPtr = &fSymbols[symbol]; + } else { + strPtr = &fNoSymbol; + } + return *strPtr; +} + +#ifndef U_HIDE_INTERNAL_API +inline const UnicodeString& DecimalFormatSymbols::getConstDigitSymbol(int32_t digit) const { + if (digit < 0 || digit > 9) { + digit = 0; + } + if (digit == 0) { + return fSymbols[kZeroDigitSymbol]; + } + ENumberFormatSymbol key = static_cast(kOneDigitSymbol + digit - 1); + return fSymbols[key]; +} +#endif /* U_HIDE_INTERNAL_API */ + +// ------------------------------------- + +inline void +DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propagateDigits = true) { + if (symbol == kCurrencySymbol) { + fIsCustomCurrencySymbol = true; + } + else if (symbol == kIntlCurrencySymbol) { + fIsCustomIntlCurrencySymbol = true; + } + if(symbol= kOneDigitSymbol && symbol <= kNineDigitSymbol) { + fCodePointZero = -1; + } +} + +// ------------------------------------- + +inline Locale +DecimalFormatSymbols::getLocale() const { + return locale; +} + +#ifndef U_HIDE_INTERNAL_API +inline const char16_t* +DecimalFormatSymbols::getCurrencyPattern() const { + return currPattern; +} +inline const char* +DecimalFormatSymbols::getNumberingSystemName() const { + return nsName; +} +#endif /* U_HIDE_INTERNAL_API */ + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _DCFMTSYM +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/decimfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/decimfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..f72ba687258ffa3f4cc15201cec4c6ad437e1588 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/decimfmt.h @@ -0,0 +1,2212 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File DECIMFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/20/97 clhuang Updated per C++ implementation. +* 04/03/97 aliu Rewrote parsing and formatting completely, and +* cleaned up and debugged. Actually works now. +* 04/17/97 aliu Changed DigitCount to int per code review. +* 07/10/97 helena Made ParsePosition a class and get rid of the function +* hiding problems. +* 09/09/97 aliu Ported over support for exponential formats. +* 07/20/98 stephen Changed documentation +* 01/30/13 emmons Added Scaling methods +******************************************************************************** +*/ + +#ifndef DECIMFMT_H +#define DECIMFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Compatibility APIs for decimal formatting. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/dcfmtsym.h" +#include "unicode/numfmt.h" +#include "unicode/locid.h" +#include "unicode/fpositer.h" +#include "unicode/stringpiece.h" +#include "unicode/curramt.h" +#include "unicode/enumset.h" + +U_NAMESPACE_BEGIN + +class CurrencyPluralInfo; +class CompactDecimalFormat; + +namespace number { +class LocalizedNumberFormatter; +namespace impl { +class DecimalQuantity; +struct DecimalFormatFields; +class UFormattedNumberData; +} +} + +namespace numparse { +namespace impl { +class NumberParserImpl; +} +} + +/** + * **IMPORTANT:** New users are strongly encouraged to see if + * numberformatter.h fits their use case. Although not deprecated, this header + * is provided for backwards compatibility only. + * + * DecimalFormat is a concrete subclass of NumberFormat that formats decimal + * numbers. It has a variety of features designed to make it possible to parse + * and format numbers in any locale, including support for Western, Arabic, or + * Indic digits. It also supports different flavors of numbers, including + * integers ("123"), fixed-point numbers ("123.4"), scientific notation + * ("1.23E4"), percentages ("12%"), and currency amounts ("$123", "USD123", + * "123 US dollars"). All of these flavors can be easily localized. + * + * To obtain a NumberFormat for a specific locale (including the default + * locale) call one of NumberFormat's factory methods such as + * createInstance(). Do not call the DecimalFormat constructors directly, unless + * you know what you are doing, since the NumberFormat factory methods may + * return subclasses other than DecimalFormat. + * + * **Example Usage** + * + * \code + * // Normally we would have a GUI with a menu for this + * int32_t locCount; + * const Locale* locales = NumberFormat::getAvailableLocales(locCount); + * + * double myNumber = -1234.56; + * UErrorCode success = U_ZERO_ERROR; + * NumberFormat* form; + * + * // Print out a number with the localized number, currency and percent + * // format for each locale. + * UnicodeString countryName; + * UnicodeString displayName; + * UnicodeString str; + * UnicodeString pattern; + * Formattable fmtable; + * for (int32_t j = 0; j < 3; ++j) { + * cout << endl << "FORMAT " << j << endl; + * for (int32_t i = 0; i < locCount; ++i) { + * if (locales[i].getCountry(countryName).size() == 0) { + * // skip language-only + * continue; + * } + * switch (j) { + * case 0: + * form = NumberFormat::createInstance(locales[i], success ); break; + * case 1: + * form = NumberFormat::createCurrencyInstance(locales[i], success ); break; + * default: + * form = NumberFormat::createPercentInstance(locales[i], success ); break; + * } + * if (form) { + * str.remove(); + * pattern = ((DecimalFormat*)form)->toPattern(pattern); + * cout << locales[i].getDisplayName(displayName) << ": " << pattern; + * cout << " -> " << form->format(myNumber,str) << endl; + * form->parse(form->format(myNumber,str), fmtable, success); + * delete form; + * } + * } + * } + * \endcode + * + * **Another example use createInstance(style)** + * + * \code + * // Print out a number using the localized number, currency, + * // percent, scientific, integer, iso currency, and plural currency + * // format for each locale + * Locale* locale = new Locale("en", "US"); + * double myNumber = 1234.56; + * UErrorCode success = U_ZERO_ERROR; + * UnicodeString str; + * Formattable fmtable; + * for (int j=NumberFormat::kNumberStyle; + * j<=NumberFormat::kPluralCurrencyStyle; + * ++j) { + * NumberFormat* form = NumberFormat::createInstance(locale, j, success); + * str.remove(); + * cout << "format result " << form->format(myNumber, str) << endl; + * format->parse(form->format(myNumber, str), fmtable, success); + * delete form; + * } + * \endcode + * + * + *

Patterns + * + *

A DecimalFormat consists of a pattern and a set of + * symbols. The pattern may be set directly using + * applyPattern(), or indirectly using other API methods which + * manipulate aspects of the pattern, such as the minimum number of integer + * digits. The symbols are stored in a DecimalFormatSymbols + * object. When using the NumberFormat factory methods, the + * pattern and symbols are read from ICU's locale data. + * + *

Special Pattern Characters + * + *

Many characters in a pattern are taken literally; they are matched during + * parsing and output unchanged during formatting. Special characters, on the + * other hand, stand for other characters, strings, or classes of characters. + * For example, the '#' character is replaced by a localized digit. Often the + * replacement character is the same as the pattern character; in the U.S. locale, + * the ',' grouping character is replaced by ','. However, the replacement is + * still happening, and if the symbols are modified, the grouping character + * changes. Some special characters affect the behavior of the formatter by + * their presence; for example, if the percent character is seen, then the + * value is multiplied by 100 before being displayed. + * + *

To insert a special character in a pattern as a literal, that is, without + * any special meaning, the character must be quoted. There are some exceptions to + * this which are noted below. + * + *

The characters listed here are used in non-localized patterns. Localized + * patterns use the corresponding characters taken from this formatter's + * DecimalFormatSymbols object instead, and these characters lose + * their special status. Two exceptions are the currency sign and quote, which + * are not localized. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Symbol + * Location + * Localized? + * Meaning + *
0 + * Number + * Yes + * Digit + *
1-9 + * Number + * Yes + * '1' through '9' indicate rounding. + *
\htmlonly@\endhtmlonly + * Number + * No + * Significant digit + *
# + * Number + * Yes + * Digit, zero shows as absent + *
. + * Number + * Yes + * Decimal separator or monetary decimal separator + *
- + * Number + * Yes + * Minus sign + *
, + * Number + * Yes + * Grouping separator + *
E + * Number + * Yes + * Separates mantissa and exponent in scientific notation. + * Need not be quoted in prefix or suffix. + *
+ + * Exponent + * Yes + * Prefix positive exponents with localized plus sign. + * Need not be quoted in prefix or suffix. + *
; + * Subpattern boundary + * Yes + * Separates positive and negative subpatterns + *
\% + * Prefix or suffix + * Yes + * Multiply by 100 and show as percentage + *
\\u2030 + * Prefix or suffix + * Yes + * Multiply by 1000 and show as per mille + *
\htmlonly¤\endhtmlonly (\\u00A4) + * Prefix or suffix + * No + * Currency sign, replaced by currency symbol. If + * doubled, replaced by international currency symbol. + * If tripled, replaced by currency plural names, for example, + * "US dollar" or "US dollars" for America. + * If present in a pattern, the monetary decimal separator + * is used instead of the decimal separator. + *
' + * Prefix or suffix + * No + * Used to quote special characters in a prefix or suffix, + * for example, "'#'#" formats 123 to + * "#123". To create a single quote + * itself, use two in a row: "# o''clock". + *
* + * Prefix or suffix boundary + * Yes + * Pad escape, precedes pad character + *
+ * + *

A DecimalFormat pattern contains a positive and negative + * subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a + * prefix, a numeric part, and a suffix. If there is no explicit negative + * subpattern, the negative subpattern is the localized minus sign prefixed to the + * positive subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there + * is an explicit negative subpattern, it serves only to specify the negative + * prefix and suffix; the number of digits, minimal digits, and other + * characteristics are ignored in the negative subpattern. That means that + * "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)". + * + *

The prefixes, suffixes, and various symbols used for infinity, digits, + * thousands separators, decimal separators, etc. may be set to arbitrary + * values, and they will appear properly during formatting. However, care must + * be taken that the symbols and strings do not conflict, or parsing will be + * unreliable. For example, either the positive and negative prefixes or the + * suffixes must be distinct for parse() to be able + * to distinguish positive from negative values. Another example is that the + * decimal separator and thousands separator should be distinct characters, or + * parsing will be impossible. + * + *

The grouping separator is a character that separates clusters of + * integer digits to make large numbers more legible. It commonly used for + * thousands, but in some locales it separates ten-thousands. The grouping + * size is the number of digits between the grouping separators, such as 3 + * for "100,000,000" or 4 for "1 0000 0000". There are actually two different + * grouping sizes: One used for the least significant integer digits, the + * primary grouping size, and one used for all others, the + * secondary grouping size. In most locales these are the same, but + * sometimes they are different. For example, if the primary grouping interval + * is 3, and the secondary is 2, then this corresponds to the pattern + * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a + * pattern contains multiple grouping separators, the interval between the last + * one and the end of the integer defines the primary grouping size, and the + * interval between the last two defines the secondary grouping size. All others + * are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####". + * + *

Illegal patterns, such as "#.#.#" or "#.###,###", will cause + * DecimalFormat to set a failing UErrorCode. + * + *

Pattern BNF + * + *

+ * pattern    := subpattern (';' subpattern)?
+ * subpattern := prefix? number exponent? suffix?
+ * number     := (integer ('.' fraction)?) | sigDigits
+ * prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
+ * suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
+ * integer    := '#'* '0'* '0'
+ * fraction   := '0'* '#'*
+ * sigDigits  := '#'* '@' '@'* '#'*
+ * exponent   := 'E' '+'? '0'* '0'
+ * padSpec    := '*' padChar
+ * padChar    := '\\u0000'..'\\uFFFD' - quote
+ *  
+ * Notation:
+ *   X*       0 or more instances of X
+ *   X?       0 or 1 instances of X
+ *   X|Y      either X or Y
+ *   C..D     any character from C up to D, inclusive
+ *   S-T      characters in S, except those in T
+ * 
+ * The first subpattern is for positive numbers. The second (optional) + * subpattern is for negative numbers. + * + *

Not indicated in the BNF syntax above: + * + *

  • The grouping separator ',' can occur inside the integer and + * sigDigits elements, between any two pattern characters of that + * element, as long as the integer or sigDigits element is not + * followed by the exponent element. + * + *
  • Two grouping intervals are recognized: That between the + * decimal point and the first grouping symbol, and that + * between the first and second grouping symbols. These + * intervals are identical in most locales, but in some + * locales they differ. For example, the pattern + * "#,##,###" formats the number 123456789 as + * "12,34,56,789".
  • + * + *
  • The pad specifier padSpec may appear before the prefix, + * after the prefix, before the suffix, after the suffix, or not at all. + * + *
  • In place of '0', the digits '1' through '9' may be used to + * indicate a rounding increment. + *
+ * + *

Parsing + * + *

DecimalFormat parses all Unicode characters that represent + * decimal digits, as defined by u_charDigitValue(). In addition, + * DecimalFormat also recognizes as digits the ten consecutive + * characters starting with the localized zero digit defined in the + * DecimalFormatSymbols object. During formatting, the + * DecimalFormatSymbols-based digits are output. + * + *

During parsing, grouping separators are ignored if in lenient mode; + * otherwise, if present, they must be in appropriate positions. + * + *

For currency parsing, the formatter is able to parse every currency + * style formats no matter which style the formatter is constructed with. + * For example, a formatter instance gotten from + * NumberFormat.getInstance(ULocale, NumberFormat.CURRENCYSTYLE) can parse + * formats such as "USD1.00" and "3.00 US dollars". + * + *

If parse(UnicodeString&,Formattable&,ParsePosition&) + * fails to parse a string, it leaves the parse position unchanged. + * The convenience method parse(UnicodeString&,Formattable&,UErrorCode&) + * indicates parse failure by setting a failing + * UErrorCode. + * + *

Formatting + * + *

Formatting is guided by several parameters, all of which can be + * specified either using a pattern or using the API. The following + * description applies to formats that do not use scientific + * notation or significant digits. + * + *

  • If the number of actual integer digits exceeds the + * maximum integer digits, then only the least significant + * digits are shown. For example, 1997 is formatted as "97" if the + * maximum integer digits is set to 2. + * + *
  • If the number of actual integer digits is less than the + * minimum integer digits, then leading zeros are added. For + * example, 1997 is formatted as "01997" if the minimum integer digits + * is set to 5. + * + *
  • If the number of actual fraction digits exceeds the maximum + * fraction digits, then rounding is performed to the + * maximum fraction digits. For example, 0.125 is formatted as "0.12" + * if the maximum fraction digits is 2. This behavior can be changed + * by specifying a rounding increment and/or a rounding mode. + * + *
  • If the number of actual fraction digits is less than the + * minimum fraction digits, then trailing zeros are added. + * For example, 0.125 is formatted as "0.1250" if the minimum fraction + * digits is set to 4. + * + *
  • Trailing fractional zeros are not displayed if they occur + * j positions after the decimal, where j is less + * than the maximum fraction digits. For example, 0.10004 is + * formatted as "0.1" if the maximum fraction digits is four or less. + *
+ * + *

Special Values + * + *

NaN is represented as a single character, typically + * \\uFFFD. This character is determined by the + * DecimalFormatSymbols object. This is the only value for which + * the prefixes and suffixes are not used. + * + *

Infinity is represented as a single character, typically + * \\u221E, with the positive or negative prefixes and suffixes + * applied. The infinity character is determined by the + * DecimalFormatSymbols object. + * + * Scientific Notation + * + *

Numbers in scientific notation are expressed as the product of a mantissa + * and a power of ten, for example, 1234 can be expressed as 1.234 x 103. The + * mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0), + * but it need not be. DecimalFormat supports arbitrary mantissas. + * DecimalFormat can be instructed to use scientific + * notation through the API or through the pattern. In a pattern, the exponent + * character immediately followed by one or more digit characters indicates + * scientific notation. Example: "0.###E0" formats the number 1234 as + * "1.234E3". + * + *

    + *
  • The number of digit characters after the exponent character gives the + * minimum exponent digit count. There is no maximum. Negative exponents are + * formatted using the localized minus sign, not the prefix and suffix + * from the pattern. This allows patterns such as "0.###E0 m/s". To prefix + * positive exponents with a localized plus sign, specify '+' between the + * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0", + * "1E-1", etc. (In localized patterns, use the localized plus sign rather than + * '+'.) + * + *
  • The minimum number of integer digits is achieved by adjusting the + * exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This + * only happens if there is no maximum number of integer digits. If there is a + * maximum, then the minimum number of integer digits is fixed at one. + * + *
  • The maximum number of integer digits, if present, specifies the exponent + * grouping. The most common use of this is to generate engineering + * notation, in which the exponent is a multiple of three, e.g., + * "##0.###E0". The number 12345 is formatted using "##0.####E0" as "12.345E3". + * + *
  • When using scientific notation, the formatter controls the + * digit counts using significant digits logic. The maximum number of + * significant digits limits the total number of integer and fraction + * digits that will be shown in the mantissa; it does not affect + * parsing. For example, 12345 formatted with "##0.##E0" is "12.3E3". + * See the section on significant digits for more details. + * + *
  • The number of significant digits shown is determined as + * follows: If areSignificantDigitsUsed() returns false, then the + * minimum number of significant digits shown is one, and the maximum + * number of significant digits shown is the sum of the minimum + * integer and maximum fraction digits, and is + * unaffected by the maximum integer digits. If this sum is zero, + * then all significant digits are shown. If + * areSignificantDigitsUsed() returns true, then the significant digit + * counts are specified by getMinimumSignificantDigits() and + * getMaximumSignificantDigits(). In this case, the number of + * integer digits is fixed at one, and there is no exponent grouping. + * + *
  • Exponential patterns may not contain grouping separators. + *
+ * + * Significant Digits + * + * DecimalFormat has two ways of controlling how many + * digits are shows: (a) significant digits counts, or (b) integer and + * fraction digit counts. Integer and fraction digit counts are + * described above. When a formatter is using significant digits + * counts, the number of integer and fraction digits is not specified + * directly, and the formatter settings for these counts are ignored. + * Instead, the formatter uses however many integer and fraction + * digits are required to display the specified number of significant + * digits. Examples: + * + * + * + * + * + * + * + *
Pattern + * Minimum significant digits + * Maximum significant digits + * Number + * Output of format() + *
\@\@\@ + * 3 + * 3 + * 12345 + * 12300 + *
\@\@\@ + * 3 + * 3 + * 0.12345 + * 0.123 + *
\@\@## + * 2 + * 4 + * 3.14159 + * 3.142 + *
\@\@## + * 2 + * 4 + * 1.23004 + * 1.23 + *
+ * + *
    + *
  • Significant digit counts may be expressed using patterns that + * specify a minimum and maximum number of significant digits. These + * are indicated by the '@' and '#' + * characters. The minimum number of significant digits is the number + * of '@' characters. The maximum number of significant + * digits is the number of '@' characters plus the number + * of '#' characters following on the right. For + * example, the pattern "@@@" indicates exactly 3 + * significant digits. The pattern "@##" indicates from + * 1 to 3 significant digits. Trailing zero digits to the right of + * the decimal separator are suppressed after the minimum number of + * significant digits have been shown. For example, the pattern + * "@##" formats the number 0.1203 as + * "0.12". + * + *
  • If a pattern uses significant digits, it may not contain a + * decimal separator, nor the '0' pattern character. + * Patterns such as "@00" or "@.###" are + * disallowed. + * + *
  • Any number of '#' characters may be prepended to + * the left of the leftmost '@' character. These have no + * effect on the minimum and maximum significant digits counts, but + * may be used to position grouping separators. For example, + * "#,#@#" indicates a minimum of one significant digits, + * a maximum of two significant digits, and a grouping size of three. + * + *
  • In order to enable significant digits formatting, use a pattern + * containing the '@' pattern character. Alternatively, + * call setSignificantDigitsUsed(true). + * + *
  • In order to disable significant digits formatting, use a + * pattern that does not contain the '@' pattern + * character. Alternatively, call setSignificantDigitsUsed(false). + * + *
  • The number of significant digits has no effect on parsing. + * + *
  • Significant digits may be used together with exponential notation. Such + * patterns are equivalent to a normal exponential pattern with a minimum and + * maximum integer digit count of one, a minimum fraction digit count of + * getMinimumSignificantDigits() - 1, and a maximum fraction digit + * count of getMaximumSignificantDigits() - 1. For example, the + * pattern "@@###E0" is equivalent to "0.0###E0". + * + *
  • If significant digits are in use, then the integer and fraction + * digit counts, as set via the API, are ignored. If significant + * digits are not in use, then the significant digit counts, as set via + * the API, are ignored. + * + *
+ * + *

Padding + * + *

DecimalFormat supports padding the result of + * format() to a specific width. Padding may be specified either + * through the API or through the pattern syntax. In a pattern the pad escape + * character, followed by a single pad character, causes padding to be parsed + * and formatted. The pad escape character is '*' in unlocalized patterns, and + * can be localized using DecimalFormatSymbols::setSymbol() with a + * DecimalFormatSymbols::kPadEscapeSymbol + * selector. For example, "$*x#,##0.00" formats 123 to + * "$xx123.00", and 1234 to "$1,234.00". + * + *

    + *
  • When padding is in effect, the width of the positive subpattern, + * including prefix and suffix, determines the format width. For example, in + * the pattern "* #0 o''clock", the format width is 10. + * + *
  • The width is counted in 16-bit code units (char16_ts). + * + *
  • Some parameters which usually do not matter have meaning when padding is + * used, because the pattern width is significant with padding. In the pattern + * "* ##,##,#,##0.##", the format width is 14. The initial characters "##,##," + * do not affect the grouping size or maximum integer digits, but they do affect + * the format width. + * + *
  • Padding may be inserted at one of four locations: before the prefix, + * after the prefix, before the suffix, or after the suffix. If padding is + * specified in any other location, applyPattern() + * sets a failing UErrorCode. If there is no prefix, + * before the prefix and after the prefix are equivalent, likewise for the + * suffix. + * + *
  • When specified in a pattern, the 32-bit code point immediately + * following the pad escape is the pad character. This may be any character, + * including a special pattern character. That is, the pad escape + * escapes the following character. If there is no character after + * the pad escape, then the pattern is illegal. + * + *
+ * + *

Rounding + * + *

DecimalFormat supports rounding to a specific increment. For + * example, 1230 rounded to the nearest 50 is 1250. 1.234 rounded to the + * nearest 0.65 is 1.3. The rounding increment may be specified through the API + * or in a pattern. To specify a rounding increment in a pattern, include the + * increment in the pattern itself. "#,#50" specifies a rounding increment of + * 50. "#,##0.05" specifies a rounding increment of 0.05. + * + *

In the absence of an explicit rounding increment numbers are + * rounded to their formatted width. + * + *

    + *
  • Rounding only affects the string produced by formatting. It does + * not affect parsing or change any numerical values. + * + *
  • A rounding mode determines how values are rounded; see + * DecimalFormat::ERoundingMode. The default rounding mode is + * DecimalFormat::kRoundHalfEven. The rounding mode can only be set + * through the API; it can not be set with a pattern. + * + *
  • Some locales use rounding in their currency formats to reflect the + * smallest currency denomination. + * + *
  • In a pattern, digits '1' through '9' specify rounding, but otherwise + * behave identically to digit '0'. + *
+ * + *

Synchronization + * + *

DecimalFormat objects are not synchronized. Multiple + * threads should not access one formatter concurrently. + * + *

Subclassing + * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API DecimalFormat : public NumberFormat { + public: + /** + * Pad position. + * @stable ICU 2.4 + */ + enum EPadPosition { + kPadBeforePrefix, kPadAfterPrefix, kPadBeforeSuffix, kPadAfterSuffix + }; + + /** + * Create a DecimalFormat using the default pattern and symbols + * for the default locale. This is a convenient way to obtain a + * DecimalFormat when internationalization is not the main concern. + *

+ * To obtain standard formats for a given locale, use the factory methods + * on NumberFormat such as createInstance. These factories will + * return the most appropriate sub-class of NumberFormat for a given + * locale. + *

+ * NOTE: New users are strongly encouraged to use + * #icu::number::NumberFormatter instead of DecimalFormat. + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @stable ICU 2.0 + */ + DecimalFormat(UErrorCode& status); + + /** + * Create a DecimalFormat from the given pattern and the symbols + * for the default locale. This is a convenient way to obtain a + * DecimalFormat when internationalization is not the main concern. + *

+ * To obtain standard formats for a given locale, use the factory methods + * on NumberFormat such as createInstance. These factories will + * return the most appropriate sub-class of NumberFormat for a given + * locale. + *

+ * NOTE: New users are strongly encouraged to use + * #icu::number::NumberFormatter instead of DecimalFormat. + * @param pattern A non-localized pattern string. + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @stable ICU 2.0 + */ + DecimalFormat(const UnicodeString& pattern, UErrorCode& status); + + /** + * Create a DecimalFormat from the given pattern and symbols. + * Use this constructor when you need to completely customize the + * behavior of the format. + *

+ * To obtain standard formats for a given + * locale, use the factory methods on NumberFormat such as + * createInstance or createCurrencyInstance. If you need only minor adjustments + * to a standard format, you can modify the format returned by + * a NumberFormat factory method. + *

+ * NOTE: New users are strongly encouraged to use + * #icu::number::NumberFormatter instead of DecimalFormat. + * + * @param pattern a non-localized pattern string + * @param symbolsToAdopt the set of symbols to be used. The caller should not + * delete this object after making this call. + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @stable ICU 2.0 + */ + DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt, UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + + /** + * This API is for ICU use only. + * Create a DecimalFormat from the given pattern, symbols, and style. + * + * @param pattern a non-localized pattern string + * @param symbolsToAdopt the set of symbols to be used. The caller should not + * delete this object after making this call. + * @param style style of decimal format + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @internal + */ + DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt, + UNumberFormatStyle style, UErrorCode& status); + +#if UCONFIG_HAVE_PARSEALLINPUT + + /** + * @internal + */ + void setParseAllInput(UNumberFormatAttributeValue value); + +#endif + +#endif /* U_HIDE_INTERNAL_API */ + + private: + + /** + * Internal constructor for DecimalFormat; sets up internal fields. All public constructors should + * call this constructor. + */ + DecimalFormat(const DecimalFormatSymbols* symbolsToAdopt, UErrorCode& status); + + public: + + /** + * Set an integer attribute on this DecimalFormat. + * May return U_UNSUPPORTED_ERROR if this instance does not support + * the specified attribute. + * @param attr the attribute to set + * @param newValue new value + * @param status the error type + * @return *this - for chaining (example: format.setAttribute(...).setAttribute(...) ) + * @stable ICU 51 + */ + virtual DecimalFormat& setAttribute(UNumberFormatAttribute attr, int32_t newValue, UErrorCode& status); + + /** + * Get an integer + * May return U_UNSUPPORTED_ERROR if this instance does not support + * the specified attribute. + * @param attr the attribute to set + * @param status the error type + * @return the attribute value. Undefined if there is an error. + * @stable ICU 51 + */ + virtual int32_t getAttribute(UNumberFormatAttribute attr, UErrorCode& status) const; + + + /** + * Set whether or not grouping will be used in this format. + * @param newValue True, grouping will be used in this format. + * @see getGroupingUsed + * @stable ICU 53 + */ + void setGroupingUsed(UBool newValue) override; + + /** + * Sets whether or not numbers should be parsed as integers only. + * @param value set True, this format will parse numbers as integers + * only. + * @see isParseIntegerOnly + * @stable ICU 53 + */ + void setParseIntegerOnly(UBool value) override; + + /** + * Sets whether lenient parsing should be enabled (it is off by default). + * + * @param enable \c true if lenient parsing should be used, + * \c false otherwise. + * @stable ICU 4.8 + */ + void setLenient(UBool enable) override; + + /** + * Create a DecimalFormat from the given pattern and symbols. + * Use this constructor when you need to completely customize the + * behavior of the format. + *

+ * To obtain standard formats for a given + * locale, use the factory methods on NumberFormat such as + * createInstance or createCurrencyInstance. If you need only minor adjustments + * to a standard format, you can modify the format returned by + * a NumberFormat factory method. + *

+ * NOTE: New users are strongly encouraged to use + * #icu::number::NumberFormatter instead of DecimalFormat. + * + * @param pattern a non-localized pattern string + * @param symbolsToAdopt the set of symbols to be used. The caller should not + * delete this object after making this call. + * @param parseError Output param to receive errors occurred during parsing + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @stable ICU 2.0 + */ + DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt, + UParseError& parseError, UErrorCode& status); + + /** + * Create a DecimalFormat from the given pattern and symbols. + * Use this constructor when you need to completely customize the + * behavior of the format. + *

+ * To obtain standard formats for a given + * locale, use the factory methods on NumberFormat such as + * createInstance or createCurrencyInstance. If you need only minor adjustments + * to a standard format, you can modify the format returned by + * a NumberFormat factory method. + *

+ * NOTE: New users are strongly encouraged to use + * #icu::number::NumberFormatter instead of DecimalFormat. + * + * @param pattern a non-localized pattern string + * @param symbols the set of symbols to be used + * @param status Output param set to success/failure code. If the + * pattern is invalid this will be set to a failure code. + * @stable ICU 2.0 + */ + DecimalFormat(const UnicodeString& pattern, const DecimalFormatSymbols& symbols, UErrorCode& status); + + /** + * Copy constructor. + * + * @param source the DecimalFormat object to be copied from. + * @stable ICU 2.0 + */ + DecimalFormat(const DecimalFormat& source); + + /** + * Assignment operator. + * + * @param rhs the DecimalFormat object to be copied. + * @stable ICU 2.0 + */ + DecimalFormat& operator=(const DecimalFormat& rhs); + + /** + * Destructor. + * @stable ICU 2.0 + */ + ~DecimalFormat() override; + + /** + * Clone this Format object polymorphically. The caller owns the + * result and should delete it when done. + * + * @return a polymorphic copy of this DecimalFormat. + * @stable ICU 2.0 + */ + DecimalFormat* clone() const override; + + /** + * Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.0 + */ + bool operator==(const Format& other) const override; + + + using NumberFormat::format; + + /** + * Format a double or long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(double number, UnicodeString& appendTo, FieldPosition& pos) const override; + +#ifndef U_HIDE_INTERNAL_API + /** + * Format a double or long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status + * @return Reference to 'appendTo' parameter. + * @internal + */ + UnicodeString& format(double number, UnicodeString& appendTo, FieldPosition& pos, + UErrorCode& status) const override; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Format a double or long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(double number, UnicodeString& appendTo, FieldPositionIterator* posIter, + UErrorCode& status) const override; + + /** + * Format a long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(int32_t number, UnicodeString& appendTo, FieldPosition& pos) const override; + +#ifndef U_HIDE_INTERNAL_API + /** + * Format a long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + UnicodeString& format(int32_t number, UnicodeString& appendTo, FieldPosition& pos, + UErrorCode& status) const override; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Format a long number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(int32_t number, UnicodeString& appendTo, FieldPositionIterator* posIter, + UErrorCode& status) const override; + + /** + * Format an int64 number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.8 + */ + UnicodeString& format(int64_t number, UnicodeString& appendTo, FieldPosition& pos) const override; + +#ifndef U_HIDE_INTERNAL_API + /** + * Format an int64 number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + UnicodeString& format(int64_t number, UnicodeString& appendTo, FieldPosition& pos, + UErrorCode& status) const override; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Format an int64 number using base-10 representation. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(int64_t number, UnicodeString& appendTo, FieldPositionIterator* posIter, + UErrorCode& status) const override; + + /** + * Format a decimal number. + * The syntax of the unformatted number is a "numeric string" + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * @param number The unformatted number, as a string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(StringPiece number, UnicodeString& appendTo, FieldPositionIterator* posIter, + UErrorCode& status) const override; + +#ifndef U_HIDE_INTERNAL_API + + /** + * Format a decimal number. + * The number is a DecimalQuantity wrapper onto a floating point decimal number. + * The default implementation in NumberFormat converts the decimal number + * to a double and formats that. + * + * @param number The number, a DecimalQuantity format Decimal Floating Point. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + UnicodeString& format(const number::impl::DecimalQuantity& number, UnicodeString& appendTo, + FieldPositionIterator* posIter, UErrorCode& status) const override; + + /** + * Format a decimal number. + * The number is a DecimalQuantity wrapper onto a floating point decimal number. + * The default implementation in NumberFormat converts the decimal number + * to a double and formats that. + * + * @param number The number, a DecimalQuantity format Decimal Floating Point. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + UnicodeString& format(const number::impl::DecimalQuantity& number, UnicodeString& appendTo, + FieldPosition& pos, UErrorCode& status) const override; + +#endif // U_HIDE_INTERNAL_API + + using NumberFormat::parse; + + /** + * Parse the given string using this object's choices. The method + * does string comparisons to try to find an optimal match. + * If no object can be parsed, index is unchanged, and nullptr is + * returned. The result is returned as the most parsimonious + * type of Formattable that will accommodate all of the + * necessary precision. For example, if the result is exactly 12, + * it will be returned as a long. However, if it is 1.5, it will + * be returned as a double. + * + * @param text The text to be parsed. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parsePosition The position to start parsing at on input. + * On output, moved to after the last successfully + * parse character. On parse failure, does not change. + * @see Formattable + * @stable ICU 2.0 + */ + void parse(const UnicodeString& text, Formattable& result, + ParsePosition& parsePosition) const override; + + /** + * Parses text from the given string as a currency amount. Unlike + * the parse() method, this method will attempt to parse a generic + * currency name, searching for a match of this object's locale's + * currency display names, or for a 3-letter ISO currency code. + * This method will fail if this format is not a currency format, + * that is, if it does not contain the currency pattern symbol + * (U+00A4) in its prefix or suffix. + * + * @param text the string to parse + * @param pos input-output position; on input, the position within text + * to match; must have 0 <= pos.getIndex() < text.length(); + * on output, the position after the last matched character. + * If the parse fails, the position in unchanged upon output. + * @return if parse succeeds, a pointer to a newly-created CurrencyAmount + * object (owned by the caller) containing information about + * the parsed currency; if parse fails, this is nullptr. + * @stable ICU 49 + */ + CurrencyAmount* parseCurrency(const UnicodeString& text, ParsePosition& pos) const override; + + /** + * Returns the decimal format symbols, which is generally not changed + * by the programmer or user. + * @return desired DecimalFormatSymbols + * @see DecimalFormatSymbols + * @stable ICU 2.0 + */ + virtual const DecimalFormatSymbols* getDecimalFormatSymbols(void) const; + + /** + * Sets the decimal format symbols, which is generally not changed + * by the programmer or user. + * @param symbolsToAdopt DecimalFormatSymbols to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt); + + /** + * Sets the decimal format symbols, which is generally not changed + * by the programmer or user. + * @param symbols DecimalFormatSymbols. + * @stable ICU 2.0 + */ + virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols); + + + /** + * Returns the currency plural format information, + * which is generally not changed by the programmer or user. + * @return desired CurrencyPluralInfo + * @stable ICU 4.2 + */ + virtual const CurrencyPluralInfo* getCurrencyPluralInfo(void) const; + + /** + * Sets the currency plural format information, + * which is generally not changed by the programmer or user. + * @param toAdopt CurrencyPluralInfo to be adopted. + * @stable ICU 4.2 + */ + virtual void adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt); + + /** + * Sets the currency plural format information, + * which is generally not changed by the programmer or user. + * @param info Currency Plural Info. + * @stable ICU 4.2 + */ + virtual void setCurrencyPluralInfo(const CurrencyPluralInfo& info); + + + /** + * Get the positive prefix. + * + * @param result Output param which will receive the positive prefix. + * @return A reference to 'result'. + * Examples: +123, $123, sFr123 + * @stable ICU 2.0 + */ + UnicodeString& getPositivePrefix(UnicodeString& result) const; + + /** + * Set the positive prefix. + * + * @param newValue the new value of the the positive prefix to be set. + * Examples: +123, $123, sFr123 + * @stable ICU 2.0 + */ + virtual void setPositivePrefix(const UnicodeString& newValue); + + /** + * Get the negative prefix. + * + * @param result Output param which will receive the negative prefix. + * @return A reference to 'result'. + * Examples: -123, ($123) (with negative suffix), sFr-123 + * @stable ICU 2.0 + */ + UnicodeString& getNegativePrefix(UnicodeString& result) const; + + /** + * Set the negative prefix. + * + * @param newValue the new value of the the negative prefix to be set. + * Examples: -123, ($123) (with negative suffix), sFr-123 + * @stable ICU 2.0 + */ + virtual void setNegativePrefix(const UnicodeString& newValue); + + /** + * Get the positive suffix. + * + * @param result Output param which will receive the positive suffix. + * @return A reference to 'result'. + * Example: 123% + * @stable ICU 2.0 + */ + UnicodeString& getPositiveSuffix(UnicodeString& result) const; + + /** + * Set the positive suffix. + * + * @param newValue the new value of the positive suffix to be set. + * Example: 123% + * @stable ICU 2.0 + */ + virtual void setPositiveSuffix(const UnicodeString& newValue); + + /** + * Get the negative suffix. + * + * @param result Output param which will receive the negative suffix. + * @return A reference to 'result'. + * Examples: -123%, ($123) (with positive suffixes) + * @stable ICU 2.0 + */ + UnicodeString& getNegativeSuffix(UnicodeString& result) const; + + /** + * Set the negative suffix. + * + * @param newValue the new value of the negative suffix to be set. + * Examples: 123% + * @stable ICU 2.0 + */ + virtual void setNegativeSuffix(const UnicodeString& newValue); + + /** + * Whether to show the plus sign on positive (non-negative) numbers; for example, "+12" + * + * For more control over sign display, use NumberFormatter. + * + * @return Whether the sign is shown on positive numbers and zero. + * @stable ICU 64 + */ + UBool isSignAlwaysShown() const; + + /** + * Set whether to show the plus sign on positive (non-negative) numbers; for example, "+12". + * + * For more control over sign display, use NumberFormatter. + * + * @param value true to always show a sign; false to hide the sign on positive numbers and zero. + * @stable ICU 64 + */ + void setSignAlwaysShown(UBool value); + + /** + * Get the multiplier for use in percent, permill, etc. + * For a percentage, set the suffixes to have "%" and the multiplier to be 100. + * (For Arabic, use arabic percent symbol). + * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000. + * + * The number may also be multiplied by a power of ten; see getMultiplierScale(). + * + * @return the multiplier for use in percent, permill, etc. + * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 + * @stable ICU 2.0 + */ + int32_t getMultiplier(void) const; + + /** + * Set the multiplier for use in percent, permill, etc. + * For a percentage, set the suffixes to have "%" and the multiplier to be 100. + * (For Arabic, use arabic percent symbol). + * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000. + * + * This method only supports integer multipliers. To multiply by a non-integer, pair this + * method with setMultiplierScale(). + * + * @param newValue the new value of the multiplier for use in percent, permill, etc. + * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 + * @stable ICU 2.0 + */ + virtual void setMultiplier(int32_t newValue); + + /** + * Gets the power of ten by which number should be multiplied before formatting, which + * can be combined with setMultiplier() to multiply by any arbitrary decimal value. + * + * A multiplier scale of 2 corresponds to multiplication by 100, and a multiplier scale + * of -2 corresponds to multiplication by 0.01. + * + * This method is analogous to UNUM_SCALE in getAttribute. + * + * @return the current value of the power-of-ten multiplier. + * @stable ICU 62 + */ + int32_t getMultiplierScale(void) const; + + /** + * Sets a power of ten by which number should be multiplied before formatting, which + * can be combined with setMultiplier() to multiply by any arbitrary decimal value. + * + * A multiplier scale of 2 corresponds to multiplication by 100, and a multiplier scale + * of -2 corresponds to multiplication by 0.01. + * + * For example, to multiply numbers by 0.5 before formatting, you can do: + * + *

+     * df.setMultiplier(5);
+     * df.setMultiplierScale(-1);
+     * 
+ * + * This method is analogous to UNUM_SCALE in setAttribute. + * + * @param newValue the new value of the power-of-ten multiplier. + * @stable ICU 62 + */ + void setMultiplierScale(int32_t newValue); + + /** + * Get the rounding increment. + * @return A positive rounding increment, or 0.0 if a custom rounding + * increment is not in effect. + * @see #setRoundingIncrement + * @see #getRoundingMode + * @see #setRoundingMode + * @stable ICU 2.0 + */ + virtual double getRoundingIncrement(void) const; + + /** + * Set the rounding increment. In the absence of a rounding increment, + * numbers will be rounded to the number of digits displayed. + * @param newValue A positive rounding increment, or 0.0 to + * use the default rounding increment. + * Negative increments are equivalent to 0.0. + * @see #getRoundingIncrement + * @see #getRoundingMode + * @see #setRoundingMode + * @stable ICU 2.0 + */ + virtual void setRoundingIncrement(double newValue); + + /** + * Get the rounding mode. + * @return A rounding mode + * @see #setRoundingIncrement + * @see #getRoundingIncrement + * @see #setRoundingMode + * @stable ICU 2.0 + */ + virtual ERoundingMode getRoundingMode(void) const override; + + /** + * Set the rounding mode. + * @param roundingMode A rounding mode + * @see #setRoundingIncrement + * @see #getRoundingIncrement + * @see #getRoundingMode + * @stable ICU 2.0 + */ + virtual void setRoundingMode(ERoundingMode roundingMode) override; + + /** + * Get the width to which the output of format() is padded. + * The width is counted in 16-bit code units. + * @return the format width, or zero if no padding is in effect + * @see #setFormatWidth + * @see #getPadCharacterString + * @see #setPadCharacter + * @see #getPadPosition + * @see #setPadPosition + * @stable ICU 2.0 + */ + virtual int32_t getFormatWidth(void) const; + + /** + * Set the width to which the output of format() is padded. + * The width is counted in 16-bit code units. + * This method also controls whether padding is enabled. + * @param width the width to which to pad the result of + * format(), or zero to disable padding. A negative + * width is equivalent to 0. + * @see #getFormatWidth + * @see #getPadCharacterString + * @see #setPadCharacter + * @see #getPadPosition + * @see #setPadPosition + * @stable ICU 2.0 + */ + virtual void setFormatWidth(int32_t width); + + /** + * Get the pad character used to pad to the format width. The + * default is ' '. + * @return a string containing the pad character. This will always + * have a length of one 32-bit code point. + * @see #setFormatWidth + * @see #getFormatWidth + * @see #setPadCharacter + * @see #getPadPosition + * @see #setPadPosition + * @stable ICU 2.0 + */ + virtual UnicodeString getPadCharacterString() const; + + /** + * Set the character used to pad to the format width. If padding + * is not enabled, then this will take effect if padding is later + * enabled. + * @param padChar a string containing the pad character. If the string + * has length 0, then the pad character is set to ' '. Otherwise + * padChar.char32At(0) will be used as the pad character. + * @see #setFormatWidth + * @see #getFormatWidth + * @see #getPadCharacterString + * @see #getPadPosition + * @see #setPadPosition + * @stable ICU 2.0 + */ + virtual void setPadCharacter(const UnicodeString& padChar); + + /** + * Get the position at which padding will take place. This is the location + * at which padding will be inserted if the result of format() + * is shorter than the format width. + * @return the pad position, one of kPadBeforePrefix, + * kPadAfterPrefix, kPadBeforeSuffix, or + * kPadAfterSuffix. + * @see #setFormatWidth + * @see #getFormatWidth + * @see #setPadCharacter + * @see #getPadCharacterString + * @see #setPadPosition + * @see #EPadPosition + * @stable ICU 2.0 + */ + virtual EPadPosition getPadPosition(void) const; + + /** + * Set the position at which padding will take place. This is the location + * at which padding will be inserted if the result of format() + * is shorter than the format width. This has no effect unless padding is + * enabled. + * @param padPos the pad position, one of kPadBeforePrefix, + * kPadAfterPrefix, kPadBeforeSuffix, or + * kPadAfterSuffix. + * @see #setFormatWidth + * @see #getFormatWidth + * @see #setPadCharacter + * @see #getPadCharacterString + * @see #getPadPosition + * @see #EPadPosition + * @stable ICU 2.0 + */ + virtual void setPadPosition(EPadPosition padPos); + + /** + * Return whether or not scientific notation is used. + * @return true if this object formats and parses scientific notation + * @see #setScientificNotation + * @see #getMinimumExponentDigits + * @see #setMinimumExponentDigits + * @see #isExponentSignAlwaysShown + * @see #setExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual UBool isScientificNotation(void) const; + + /** + * Set whether or not scientific notation is used. When scientific notation + * is used, the effective maximum number of integer digits is <= 8. If the + * maximum number of integer digits is set to more than 8, the effective + * maximum will be 1. This allows this call to generate a 'default' scientific + * number format without additional changes. + * @param useScientific true if this object formats and parses scientific + * notation + * @see #isScientificNotation + * @see #getMinimumExponentDigits + * @see #setMinimumExponentDigits + * @see #isExponentSignAlwaysShown + * @see #setExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual void setScientificNotation(UBool useScientific); + + /** + * Return the minimum exponent digits that will be shown. + * @return the minimum exponent digits that will be shown + * @see #setScientificNotation + * @see #isScientificNotation + * @see #setMinimumExponentDigits + * @see #isExponentSignAlwaysShown + * @see #setExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual int8_t getMinimumExponentDigits(void) const; + + /** + * Set the minimum exponent digits that will be shown. This has no + * effect unless scientific notation is in use. + * @param minExpDig a value >= 1 indicating the fewest exponent digits + * that will be shown. Values less than 1 will be treated as 1. + * @see #setScientificNotation + * @see #isScientificNotation + * @see #getMinimumExponentDigits + * @see #isExponentSignAlwaysShown + * @see #setExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual void setMinimumExponentDigits(int8_t minExpDig); + + /** + * Return whether the exponent sign is always shown. + * @return true if the exponent is always prefixed with either the + * localized minus sign or the localized plus sign, false if only negative + * exponents are prefixed with the localized minus sign. + * @see #setScientificNotation + * @see #isScientificNotation + * @see #setMinimumExponentDigits + * @see #getMinimumExponentDigits + * @see #setExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual UBool isExponentSignAlwaysShown(void) const; + + /** + * Set whether the exponent sign is always shown. This has no effect + * unless scientific notation is in use. + * @param expSignAlways true if the exponent is always prefixed with either + * the localized minus sign or the localized plus sign, false if only + * negative exponents are prefixed with the localized minus sign. + * @see #setScientificNotation + * @see #isScientificNotation + * @see #setMinimumExponentDigits + * @see #getMinimumExponentDigits + * @see #isExponentSignAlwaysShown + * @stable ICU 2.0 + */ + virtual void setExponentSignAlwaysShown(UBool expSignAlways); + + /** + * Return the grouping size. Grouping size is the number of digits between + * grouping separators in the integer portion of a number. For example, + * in the number "123,456.78", the grouping size is 3. + * + * @return the grouping size. + * @see setGroupingSize + * @see NumberFormat::isGroupingUsed + * @see DecimalFormatSymbols::getGroupingSeparator + * @stable ICU 2.0 + */ + int32_t getGroupingSize(void) const; + + /** + * Set the grouping size. Grouping size is the number of digits between + * grouping separators in the integer portion of a number. For example, + * in the number "123,456.78", the grouping size is 3. + * + * @param newValue the new value of the grouping size. + * @see getGroupingSize + * @see NumberFormat::setGroupingUsed + * @see DecimalFormatSymbols::setGroupingSeparator + * @stable ICU 2.0 + */ + virtual void setGroupingSize(int32_t newValue); + + /** + * Return the secondary grouping size. In some locales one + * grouping interval is used for the least significant integer + * digits (the primary grouping size), and another is used for all + * others (the secondary grouping size). A formatter supporting a + * secondary grouping size will return a positive integer unequal + * to the primary grouping size returned by + * getGroupingSize(). For example, if the primary + * grouping size is 4, and the secondary grouping size is 2, then + * the number 123456789 formats as "1,23,45,6789", and the pattern + * appears as "#,##,###0". + * @return the secondary grouping size, or a value less than + * one if there is none + * @see setSecondaryGroupingSize + * @see NumberFormat::isGroupingUsed + * @see DecimalFormatSymbols::getGroupingSeparator + * @stable ICU 2.4 + */ + int32_t getSecondaryGroupingSize(void) const; + + /** + * Set the secondary grouping size. If set to a value less than 1, + * then secondary grouping is turned off, and the primary grouping + * size is used for all intervals, not just the least significant. + * + * @param newValue the new value of the secondary grouping size. + * @see getSecondaryGroupingSize + * @see NumberFormat#setGroupingUsed + * @see DecimalFormatSymbols::setGroupingSeparator + * @stable ICU 2.4 + */ + virtual void setSecondaryGroupingSize(int32_t newValue); + + /** + * Returns the minimum number of grouping digits. + * Grouping separators are output if there are at least this many + * digits to the left of the first (rightmost) grouping separator, + * that is, there are at least (minimum grouping + grouping size) integer digits. + * (Subject to isGroupingUsed().) + * + * For example, if this value is 2, and the grouping size is 3, then + * 9999 -> "9999" and 10000 -> "10,000" + * + * The default value for this attribute is 0. + * A value of 1, 0, or lower, means that the use of grouping separators + * only depends on the grouping size (and on isGroupingUsed()). + * + * NOTE: The CLDR data is used in NumberFormatter but not in DecimalFormat. + * This is for backwards compatibility reasons. + * + * For more control over grouping strategies, use NumberFormatter. + * + * @see setMinimumGroupingDigits + * @see getGroupingSize + * @stable ICU 64 + */ + int32_t getMinimumGroupingDigits() const; + + /** + * Sets the minimum grouping digits. Setting the value to + * - 1: Turns off minimum grouping digits. + * - 0 or -1: The behavior is undefined. + * - UNUM_MINIMUM_GROUPING_DIGITS_AUTO: Display grouping using the default + * strategy for all locales. + * - UNUM_MINIMUM_GROUPING_DIGITS_MIN2: Display grouping using locale + * defaults, except do not show grouping on values smaller than 10000 + * (such that there is a minimum of two digits before the first + * separator). + * + * For more control over grouping strategies, use NumberFormatter. + * + * @param newValue the new value of minimum grouping digits. + * @see getMinimumGroupingDigits + * @stable ICU 64 + */ + void setMinimumGroupingDigits(int32_t newValue); + + /** + * Allows you to get the behavior of the decimal separator with integers. + * (The decimal separator will always appear with decimals.) + * + * @return true if the decimal separator always appear with decimals. + * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 + * @stable ICU 2.0 + */ + UBool isDecimalSeparatorAlwaysShown(void) const; + + /** + * Allows you to set the behavior of the decimal separator with integers. + * (The decimal separator will always appear with decimals.) + * + * @param newValue set true if the decimal separator will always appear with decimals. + * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 + * @stable ICU 2.0 + */ + virtual void setDecimalSeparatorAlwaysShown(UBool newValue); + + /** + * Allows you to get the parse behavior of the pattern decimal mark. + * + * @return true if input must contain a match to decimal mark in pattern + * @stable ICU 54 + */ + UBool isDecimalPatternMatchRequired(void) const; + + /** + * Allows you to set the parse behavior of the pattern decimal mark. + * + * if true, the input must have a decimal mark if one was specified in the pattern. When + * false the decimal mark may be omitted from the input. + * + * @param newValue set true if input must contain a match to decimal mark in pattern + * @stable ICU 54 + */ + virtual void setDecimalPatternMatchRequired(UBool newValue); + + /** + * Returns whether to ignore exponents when parsing. + * + * @return Whether to ignore exponents when parsing. + * @see #setParseNoExponent + * @stable ICU 64 + */ + UBool isParseNoExponent() const; + + /** + * Specifies whether to stop parsing when an exponent separator is encountered. For + * example, parses "123E4" to 123 (with parse position 3) instead of 1230000 (with parse position + * 5). + * + * @param value true to prevent exponents from being parsed; false to allow them to be parsed. + * @stable ICU 64 + */ + void setParseNoExponent(UBool value); + + /** + * Returns whether parsing is sensitive to case (lowercase/uppercase). + * + * @return Whether parsing is case-sensitive. + * @see #setParseCaseSensitive + * @stable ICU 64 + */ + UBool isParseCaseSensitive() const; + + /** + * Whether to pay attention to case when parsing; default is to ignore case (perform + * case-folding). For example, "A" == "a" in case-insensitive but not case-sensitive mode. + * + * Currency symbols are never case-folded. For example, "us$1.00" will not parse in case-insensitive + * mode, even though "US$1.00" parses. + * + * @param value true to enable case-sensitive parsing (the default); false to force + * case-sensitive parsing behavior. + * @stable ICU 64 + */ + void setParseCaseSensitive(UBool value); + + /** + * Returns whether truncation of high-order integer digits should result in an error. + * By default, setMaximumIntegerDigits truncates high-order digits silently. + * + * @return Whether an error code is set if high-order digits are truncated. + * @see setFormatFailIfMoreThanMaxDigits + * @stable ICU 64 + */ + UBool isFormatFailIfMoreThanMaxDigits() const; + + /** + * Sets whether truncation of high-order integer digits should result in an error. + * By default, setMaximumIntegerDigits truncates high-order digits silently. + * + * @param value Whether to set an error code if high-order digits are truncated. + * @stable ICU 64 + */ + void setFormatFailIfMoreThanMaxDigits(UBool value); + + /** + * Synthesizes a pattern string that represents the current state + * of this Format object. + * + * @param result Output param which will receive the pattern. + * Previous contents are deleted. + * @return A reference to 'result'. + * @see applyPattern + * @stable ICU 2.0 + */ + virtual UnicodeString& toPattern(UnicodeString& result) const; + + /** + * Synthesizes a localized pattern string that represents the current + * state of this Format object. + * + * @param result Output param which will receive the localized pattern. + * Previous contents are deleted. + * @return A reference to 'result'. + * @see applyPattern + * @stable ICU 2.0 + */ + virtual UnicodeString& toLocalizedPattern(UnicodeString& result) const; + + /** + * Apply the given pattern to this Format object. A pattern is a + * short-hand specification for the various formatting properties. + * These properties can also be changed individually through the + * various setter methods. + *

+ * There is no limit to integer digits are set + * by this routine, since that is the typical end-user desire; + * use setMaximumInteger if you want to set a real value. + * For negative numbers, use a second pattern, separated by a semicolon + *

+     * .      Example "#,#00.0#" -> 1,234.56
+     * 
+ * This means a minimum of 2 integer digits, 1 fraction digit, and + * a maximum of 2 fraction digits. + *
+     * .      Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses.
+     * 
+ * In negative patterns, the minimum and maximum counts are ignored; + * these are presumed to be set in the positive pattern. + * + * @param pattern The pattern to be applied. + * @param parseError Struct to receive information on position + * of error if an error is encountered + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern, UParseError& parseError, UErrorCode& status); + + /** + * Sets the pattern. + * @param pattern The pattern to be applied. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern, UErrorCode& status); + + /** + * Apply the given pattern to this Format object. The pattern + * is assumed to be in a localized notation. A pattern is a + * short-hand specification for the various formatting properties. + * These properties can also be changed individually through the + * various setter methods. + *

+ * There is no limit to integer digits are set + * by this routine, since that is the typical end-user desire; + * use setMaximumInteger if you want to set a real value. + * For negative numbers, use a second pattern, separated by a semicolon + *

+     * .      Example "#,#00.0#" -> 1,234.56
+     * 
+ * This means a minimum of 2 integer digits, 1 fraction digit, and + * a maximum of 2 fraction digits. + * + * Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses. + * + * In negative patterns, the minimum and maximum counts are ignored; + * these are presumed to be set in the positive pattern. + * + * @param pattern The localized pattern to be applied. + * @param parseError Struct to receive information on position + * of error if an error is encountered + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyLocalizedPattern(const UnicodeString& pattern, UParseError& parseError, + UErrorCode& status); + + /** + * Apply the given pattern to this Format object. + * + * @param pattern The localized pattern to be applied. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyLocalizedPattern(const UnicodeString& pattern, UErrorCode& status); + + + /** + * Sets the maximum number of digits allowed in the integer portion of a + * number. This override limits the integer digit count to 309. + * + * @param newValue the new value of the maximum number of digits + * allowed in the integer portion of a number. + * @see NumberFormat#setMaximumIntegerDigits + * @stable ICU 2.0 + */ + void setMaximumIntegerDigits(int32_t newValue) override; + + /** + * Sets the minimum number of digits allowed in the integer portion of a + * number. This override limits the integer digit count to 309. + * + * @param newValue the new value of the minimum number of digits + * allowed in the integer portion of a number. + * @see NumberFormat#setMinimumIntegerDigits + * @stable ICU 2.0 + */ + void setMinimumIntegerDigits(int32_t newValue) override; + + /** + * Sets the maximum number of digits allowed in the fraction portion of a + * number. This override limits the fraction digit count to 340. + * + * @param newValue the new value of the maximum number of digits + * allowed in the fraction portion of a number. + * @see NumberFormat#setMaximumFractionDigits + * @stable ICU 2.0 + */ + void setMaximumFractionDigits(int32_t newValue) override; + + /** + * Sets the minimum number of digits allowed in the fraction portion of a + * number. This override limits the fraction digit count to 340. + * + * @param newValue the new value of the minimum number of digits + * allowed in the fraction portion of a number. + * @see NumberFormat#setMinimumFractionDigits + * @stable ICU 2.0 + */ + void setMinimumFractionDigits(int32_t newValue) override; + + /** + * Returns the minimum number of significant digits that will be + * displayed. This value has no effect unless areSignificantDigitsUsed() + * returns true. + * @return the fewest significant digits that will be shown + * @stable ICU 3.0 + */ + int32_t getMinimumSignificantDigits() const; + + /** + * Returns the maximum number of significant digits that will be + * displayed. This value has no effect unless areSignificantDigitsUsed() + * returns true. + * @return the most significant digits that will be shown + * @stable ICU 3.0 + */ + int32_t getMaximumSignificantDigits() const; + + /** + * Sets the minimum number of significant digits that will be + * displayed. If min is less than one then it is set + * to one. If the maximum significant digits count is less than + * min, then it is set to min. + * This function also enables the use of significant digits + * by this formatter - areSignificantDigitsUsed() will return true. + * @see #areSignificantDigitsUsed + * @param min the fewest significant digits to be shown + * @stable ICU 3.0 + */ + void setMinimumSignificantDigits(int32_t min); + + /** + * Sets the maximum number of significant digits that will be + * displayed. If max is less than one then it is set + * to one. If the minimum significant digits count is greater + * than max, then it is set to max. + * This function also enables the use of significant digits + * by this formatter - areSignificantDigitsUsed() will return true. + * @see #areSignificantDigitsUsed + * @param max the most significant digits to be shown + * @stable ICU 3.0 + */ + void setMaximumSignificantDigits(int32_t max); + + /** + * Returns true if significant digits are in use, or false if + * integer and fraction digit counts are in use. + * @return true if significant digits are in use + * @stable ICU 3.0 + */ + UBool areSignificantDigitsUsed() const; + + /** + * Sets whether significant digits are in use, or integer and + * fraction digit counts are in use. + * @param useSignificantDigits true to use significant digits, or + * false to use integer and fraction digit counts + * @stable ICU 3.0 + */ + void setSignificantDigitsUsed(UBool useSignificantDigits); + + /** + * Sets the currency used to display currency + * amounts. This takes effect immediately, if this format is a + * currency format. If this format is not a currency format, then + * the currency is used if and when this object becomes a + * currency format through the application of a new pattern. + * @param theCurrency a 3-letter ISO code indicating new currency + * to use. It need not be null-terminated. May be the empty + * string or nullptr to indicate no currency. + * @param ec input-output error code + * @stable ICU 3.0 + */ + void setCurrency(const char16_t* theCurrency, UErrorCode& ec) override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Sets the currency used to display currency amounts. See + * setCurrency(const char16_t*, UErrorCode&). + * @deprecated ICU 3.0. Use setCurrency(const char16_t*, UErrorCode&). + */ + virtual void setCurrency(const char16_t* theCurrency); +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Sets the `Currency Usage` object used to display currency. + * This takes effect immediately, if this format is a + * currency format. + * @param newUsage new currency usage object to use. + * @param ec input-output error code + * @stable ICU 54 + */ + void setCurrencyUsage(UCurrencyUsage newUsage, UErrorCode* ec); + + /** + * Returns the `Currency Usage` object used to display currency + * @stable ICU 54 + */ + UCurrencyUsage getCurrencyUsage() const; + +#ifndef U_HIDE_INTERNAL_API + + /** + * Format a number and save it into the given DecimalQuantity. + * Internal, not intended for public use. + * @internal + */ + void formatToDecimalQuantity(double number, number::impl::DecimalQuantity& output, + UErrorCode& status) const; + + /** + * Get a DecimalQuantity corresponding to a formattable as it would be + * formatted by this DecimalFormat. + * Internal, not intended for public use. + * @internal + */ + void formatToDecimalQuantity(const Formattable& number, number::impl::DecimalQuantity& output, + UErrorCode& status) const; + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Converts this DecimalFormat to a (Localized)NumberFormatter. Starting + * in ICU 60, NumberFormatter is the recommended way to format numbers. + * You can use the returned LocalizedNumberFormatter to format numbers and + * get a FormattedNumber, which contains a string as well as additional + * annotations about the formatted value. + * + * If a memory allocation failure occurs, the return value of this method + * might be null. If you are concerned about correct recovery from + * out-of-memory situations, use this pattern: + * + *
+     * FormattedNumber result;
+     * if (auto* ptr = df->toNumberFormatter(status)) {
+     *     result = ptr->formatDouble(123, status);
+     * }
+     * 
+ * + * If you are not concerned about out-of-memory situations, or if your + * environment throws exceptions when memory allocation failure occurs, + * you can chain the methods, like this: + * + *
+     * FormattedNumber result = df
+     *     ->toNumberFormatter(status)
+     *     ->formatDouble(123, status);
+     * 
+ * + * NOTE: The returned LocalizedNumberFormatter is owned by this DecimalFormat. + * If a non-const method is called on the DecimalFormat, or if the DecimalFormat + * is deleted, the object becomes invalid. If you plan to keep the return value + * beyond the lifetime of the DecimalFormat, copy it to a local variable: + * + *
+     * LocalizedNumberFormatter lnf;
+     * if (auto* ptr = df->toNumberFormatter(status)) {
+     *     lnf = *ptr;
+     * }
+     * 
+ * + * @param status Set on failure, like U_MEMORY_ALLOCATION_ERROR. + * @return A pointer to an internal object, or nullptr on failure. + * Do not delete the return value! + * @stable ICU 64 + */ + const number::LocalizedNumberFormatter* toNumberFormatter(UErrorCode& status) const; + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + *
+     * .      Base* polymorphic_pointer = createPolymorphicObject();
+     * .      if (polymorphic_pointer->getDynamicClassID() ==
+     * .          Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. + * This method is to implement a simple version of RTTI, since not all + * C++ compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + UClassID getDynamicClassID(void) const override; + + private: + + /** Rebuilds the formatter object from the property bag. */ + void touch(UErrorCode& status); + + /** Rebuilds the formatter object, ignoring any error code. */ + void touchNoError(); + + /** + * Updates the property bag with settings from the given pattern. + * + * @param pattern The pattern string to parse. + * @param ignoreRounding Whether to leave out rounding information (minFrac, maxFrac, and rounding + * increment) when parsing the pattern. This may be desirable if a custom rounding mode, such + * as CurrencyUsage, is to be used instead. One of {@link + * PatternStringParser#IGNORE_ROUNDING_ALWAYS}, {@link PatternStringParser#IGNORE_ROUNDING_IF_CURRENCY}, + * or {@link PatternStringParser#IGNORE_ROUNDING_NEVER}. + * @see PatternAndPropertyUtils#parseToExistingProperties + */ + void setPropertiesFromPattern(const UnicodeString& pattern, int32_t ignoreRounding, + UErrorCode& status); + + const numparse::impl::NumberParserImpl* getParser(UErrorCode& status) const; + + const numparse::impl::NumberParserImpl* getCurrencyParser(UErrorCode& status) const; + + static void fieldPositionHelper( + const number::impl::UFormattedNumberData& formatted, + FieldPosition& fieldPosition, + int32_t offset, + UErrorCode& status); + + static void fieldPositionIteratorHelper( + const number::impl::UFormattedNumberData& formatted, + FieldPositionIterator* fpi, + int32_t offset, + UErrorCode& status); + + void setupFastFormat(); + + bool fastFormatDouble(double input, UnicodeString& output) const; + + bool fastFormatInt64(int64_t input, UnicodeString& output) const; + + void doFastFormatInt32(int32_t input, bool isNegative, UnicodeString& output) const; + + //=====================================================================================// + // INSTANCE FIELDS // + //=====================================================================================// + + + // One instance field for the implementation, keep all fields inside of an implementation + // class defined in number_mapper.h + number::impl::DecimalFormatFields* fields = nullptr; + + // Allow child class CompactDecimalFormat to access fProperties: + friend class CompactDecimalFormat; + + // Allow MeasureFormat to use fieldPositionHelper: + friend class MeasureFormat; + +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _DECIMFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/displayoptions.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/displayoptions.h new file mode 100644 index 0000000000000000000000000000000000000000..7bc763bbacd146449026a7f3a56c1c7e9235a669 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/displayoptions.h @@ -0,0 +1,274 @@ +// © 2022 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __DISPLAYOPTIONS_H__ +#define __DISPLAYOPTIONS_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +/** + * \file + * \brief C++ API: Display options class + * + * This class is designed as a more modern version of the UDisplayContext mechanism. + */ + +#include "unicode/udisplayoptions.h" +#include "unicode/uversion.h" + +U_NAMESPACE_BEGIN + +#ifndef U_HIDE_DRAFT_API + +/** + * Represents all the display options that are supported by CLDR such as grammatical case, noun + * class, ... etc. It currently supports enums, but may be extended in the future to have other + * types of data. It replaces a DisplayContext[] as a method parameter. + * + * NOTE: This class is Immutable, and uses a Builder interface. + * + * For example: + * ``` + * DisplayOptions x = + * DisplayOptions::builder(). + * .setGrammaticalCase(UDISPOPT_GRAMMATICAL_CASE_DATIVE) + * .setPluralCategory(UDISPOPT_PLURAL_CATEGORY_FEW) + * .build(); + * ``` + * + * @draft ICU 72 + */ +class U_I18N_API DisplayOptions { +public: + /** + * Responsible for building `DisplayOptions`. + * + * @draft ICU 72 + */ + class U_I18N_API Builder { + public: + /** + * Sets the grammatical case. + * + * @param grammaticalCase The grammatical case. + * @return Builder + * @draft ICU 72 + */ + Builder &setGrammaticalCase(UDisplayOptionsGrammaticalCase grammaticalCase) { + this->grammaticalCase = grammaticalCase; + return *this; + } + + /** + * Sets the noun class. + * + * @param nounClass The noun class. + * @return Builder + * @draft ICU 72 + */ + Builder &setNounClass(UDisplayOptionsNounClass nounClass) { + this->nounClass = nounClass; + return *this; + } + + /** + * Sets the plural category. + * + * @param pluralCategory The plural category. + * @return Builder + * @draft ICU 72 + */ + Builder &setPluralCategory(UDisplayOptionsPluralCategory pluralCategory) { + this->pluralCategory = pluralCategory; + return *this; + } + + /** + * Sets the capitalization. + * + * @param capitalization The capitalization. + * @return Builder + * @draft ICU 72 + */ + Builder &setCapitalization(UDisplayOptionsCapitalization capitalization) { + this->capitalization = capitalization; + return *this; + } + + /** + * Sets the dialect handling. + * + * @param nameStyle The name style. + * @return Builder + * @draft ICU 72 + */ + Builder &setNameStyle(UDisplayOptionsNameStyle nameStyle) { + this->nameStyle = nameStyle; + return *this; + } + + /** + * Sets the display length. + * + * @param displayLength The display length. + * @return Builder + * @draft ICU 72 + */ + Builder &setDisplayLength(UDisplayOptionsDisplayLength displayLength) { + this->displayLength = displayLength; + return *this; + } + + /** + * Sets the substitute handling. + * + * @param substituteHandling The substitute handling. + * @return Builder + * @draft ICU 72 + */ + Builder &setSubstituteHandling(UDisplayOptionsSubstituteHandling substituteHandling) { + this->substituteHandling = substituteHandling; + return *this; + } + + /** + * Builds the display options. + * + * @return DisplayOptions + * @draft ICU 72 + */ + DisplayOptions build() { return DisplayOptions(*this); } + + private: + friend DisplayOptions; + + Builder(); + Builder(const DisplayOptions &displayOptions); + + UDisplayOptionsGrammaticalCase grammaticalCase; + UDisplayOptionsNounClass nounClass; + UDisplayOptionsPluralCategory pluralCategory; + UDisplayOptionsCapitalization capitalization; + UDisplayOptionsNameStyle nameStyle; + UDisplayOptionsDisplayLength displayLength; + UDisplayOptionsSubstituteHandling substituteHandling; + }; + + /** + * Creates a builder with the `UNDEFINED` values for all the parameters. + * + * @return Builder + * @draft ICU 72 + */ + static Builder builder(); + /** + * Creates a builder with the same parameters from this object. + * + * @return Builder + * @draft ICU 72 + */ + Builder copyToBuilder() const; + /** + * Gets the grammatical case. + * + * @return UDisplayOptionsGrammaticalCase + * @draft ICU 72 + */ + UDisplayOptionsGrammaticalCase getGrammaticalCase() const { return grammaticalCase; } + + /** + * Gets the noun class. + * + * @return UDisplayOptionsNounClass + * @draft ICU 72 + */ + UDisplayOptionsNounClass getNounClass() const { return nounClass; } + + /** + * Gets the plural category. + * + * @return UDisplayOptionsPluralCategory + * @draft ICU 72 + */ + UDisplayOptionsPluralCategory getPluralCategory() const { return pluralCategory; } + + /** + * Gets the capitalization. + * + * @return UDisplayOptionsCapitalization + * @draft ICU 72 + */ + UDisplayOptionsCapitalization getCapitalization() const { return capitalization; } + + /** + * Gets the dialect handling. + * + * @return UDisplayOptionsNameStyle + * @draft ICU 72 + */ + UDisplayOptionsNameStyle getNameStyle() const { return nameStyle; } + + /** + * Gets the display length. + * + * @return UDisplayOptionsDisplayLength + * @draft ICU 72 + */ + UDisplayOptionsDisplayLength getDisplayLength() const { return displayLength; } + + /** + * Gets the substitute handling. + * + * @return UDisplayOptionsSubstituteHandling + * @draft ICU 72 + */ + UDisplayOptionsSubstituteHandling getSubstituteHandling() const { return substituteHandling; } + + /** + * Copies the DisplayOptions. + * + * @param other The options to copy. + * @draft ICU 72 + */ + DisplayOptions &operator=(const DisplayOptions &other) = default; + + /** + * Moves the DisplayOptions. + * + * @param other The options to move from. + * @draft ICU 72 + */ + DisplayOptions &operator=(DisplayOptions &&other) noexcept = default; + + /** + * Copies the DisplayOptions. + * + * @param other The options to copy. + * @draft ICU 72 + */ + DisplayOptions(const DisplayOptions &other) = default; + +private: + DisplayOptions(const Builder &builder); + UDisplayOptionsGrammaticalCase grammaticalCase; + UDisplayOptionsNounClass nounClass; + UDisplayOptionsPluralCategory pluralCategory; + UDisplayOptionsCapitalization capitalization; + UDisplayOptionsNameStyle nameStyle; + UDisplayOptionsDisplayLength displayLength; + UDisplayOptionsSubstituteHandling substituteHandling; +}; + +#endif // U_HIDE_DRAFT_API + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __DISPLAYOPTIONS_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/docmain.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/docmain.h new file mode 100644 index 0000000000000000000000000000000000000000..1349f49703c112ae9f4f6a5f3b36fde526feb108 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/docmain.h @@ -0,0 +1,237 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/******************************************************************** + * COPYRIGHT: + * Copyright (c) 1997-2012, International Business Machines Corporation and + * others. All Rights Reserved. + * + * FILE NAME: DOCMAIN.h + * + * Date Name Description + * 12/11/2000 Ram Creation. + */ + +/** + * \file + * \brief (Non API- contains Doxygen definitions) + * + * This file contains documentation for Doxygen and does not have + * any significance with respect to C or C++ API + */ + +/*! \mainpage + * + * \section API API Reference Usage + * + *

C++ Programmers:

+ *

Use Class Hierarchy or Alphabetical List + * or Compound List + * to find the class you are interested in. For example, to find BreakIterator, + * you can go to the Alphabetical List, then click on + * "BreakIterator". Once you are at the class, you will find an inheritance + * chart, a list of the public members, a detailed description of the class, + * then detailed member descriptions.

+ * + *

C Programmers:

+ *

Use Module List or File Members + * to find a list of all the functions and constants. + * For example, to find BreakIterator functions you would click on + * File List, + * then find "ubrk.h" and click on it. You will find descriptions of Defines, + * Typedefs, Enumerations, and Functions, with detailed descriptions below. + * If you want to find a specific function, such as ubrk_next(), then click + * first on File Members, then use your browser + * Find dialog to search for "ubrk_next()".

+ * + * + *

API References for Previous Releases

+ *

The API References for each release of ICU are also available as + * a zip file from the ICU + * download page.

+ * + *
+ * + *

Architecture (User's Guide)

+ * + * + *
+ *\htmlonly

Module List

\endhtmlonly + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Module NameCC++
Basic Types and Constantsutypes.hutypes.h
Strings and Character Iterationustring.h, utf8.h, utf16.h, icu::StringPiece, UText, UCharIterator, icu::ByteSinkicu::UnicodeString, icu::CharacterIterator, icu::Appendable, icu::StringPiece,icu::ByteSink
Unicode Character
Properties and Names
uchar.h, uscript.hC API
Sets of Unicode Code Points and Stringsuset.hicu::UnicodeSet
Maps from Unicode Code Points to Integer Valuesucptrie.h, umutablecptrie.hC API
Maps from Strings to Integer Values(no C API)icu::BytesTrie, icu::UCharsTrie
Codepage Conversionucnv.h, ucnvsel.hC API
Codepage Detectionucsdet.hC API
Unicode Text Compressionucnv.h
(encoding name "SCSU" or "BOCU-1")
C API
Locales uloc.hicu::Locale, icu::LocaleBuilder, icu::LocaleMatcher
Resource Bundlesures.hicu::ResourceBundle
Normalizationunorm2.hicu::Normalizer2
Calendars and Time Zonesucal.hicu::Calendar, icu::TimeZone
Date and Time Formattingudat.hicu::DateFormat
Message Formattingumsg.hicu::MessageFormat
List Formattingulistformatter.hicu::ListFormatter
Number Formatting
(includes currency and unit formatting)
unumberformatter.h, unum.h, usimplenumberformatter.hicu::number::NumberFormatter (ICU 60+) or icu::NumberFormat (older versions)
icu::number::SimpleNumberFormatter (ICU 73+)
Number Range Formatting
(includes currency and unit ranges)
unumberrangeformatter.hicu::number::NumberRangeFormatter
Number Spellout
(Rule Based Number Formatting)
unum.h
(use UNUM_SPELLOUT)
icu::RuleBasedNumberFormat
Text Transformation
(Transliteration)
utrans.hicu::Transliterator
Bidirectional Algorithmubidi.h, ubiditransform.hC API
Arabic Shapingushape.hC API
Collationucol.hicu::Collator
String Searchingusearch.hicu::StringSearch
Index Characters/
Bucketing for Sorted Lists
(no C API)icu::AlphabeticIndex
Text Boundary Analysis
(Break Iteration)
ubrk.hicu::BreakIterator
Regular Expressionsuregex.hicu::RegexPattern, icu::RegexMatcher
StringPrepusprep.hC API
International Domain Names in Applications:
+ * UTS #46 in C/C++, IDNA2003 only via C API
uidna.hidna.h
Identifier Spoofing & Confusabilityuspoof.hC API
Universal Time Scaleutmscale.hC API
Paragraph Layout / Complex Text Layoutplayout.hicu::ParagraphLayout
ICU I/Oustdio.hustream.h
+ * This main page is generated from docmain.h + */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtfmtsym.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtfmtsym.h new file mode 100644 index 0000000000000000000000000000000000000000..3cd54092e0e3a7bc917dc66d60f638337f182973 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtfmtsym.h @@ -0,0 +1,1032 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File DTFMTSYM.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 07/21/98 stephen Added getZoneIndex() +* Changed to match C++ conventions +******************************************************************************** +*/ + +#ifndef DTFMTSYM_H +#define DTFMTSYM_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/calendar.h" +#include "unicode/strenum.h" +#include "unicode/uobject.h" +#include "unicode/locid.h" +#include "unicode/udat.h" +#include "unicode/ures.h" + +/** + * \file + * \brief C++ API: Symbols for formatting dates. + */ + +U_NAMESPACE_BEGIN + +/* forward declaration */ +class SimpleDateFormat; +class Hashtable; + +/** + * DateFormatSymbols is a public class for encapsulating localizable date-time + * formatting data -- including timezone data. DateFormatSymbols is used by + * DateFormat and SimpleDateFormat. + *

+ * Rather than first creating a DateFormatSymbols to get a date-time formatter + * by using a SimpleDateFormat constructor, clients are encouraged to create a + * date-time formatter using the getTimeInstance(), getDateInstance(), or + * getDateTimeInstance() method in DateFormat. Each of these methods can return a + * date/time formatter initialized with a default format pattern along with the + * date-time formatting data for a given or default locale. After a formatter is + * created, clients may modify the format pattern using the setPattern function + * as so desired. For more information on using these formatter factory + * functions, see DateFormat. + *

+ * If clients decide to create a date-time formatter with a particular format + * pattern and locale, they can do so with new SimpleDateFormat(aPattern, + * new DateFormatSymbols(aLocale)). This will load the appropriate date-time + * formatting data from the locale. + *

+ * DateFormatSymbols objects are clonable. When clients obtain a + * DateFormatSymbols object, they can feel free to modify the date-time + * formatting data as necessary. For instance, clients can + * replace the localized date-time format pattern characters with the ones that + * they feel easy to remember. Or they can change the representative cities + * originally picked by default to using their favorite ones. + *

+ * DateFormatSymbols are not expected to be subclassed. Data for a calendar is + * loaded out of resource bundles. The 'type' parameter indicates the type of + * calendar, for example, "gregorian" or "japanese". If the type is not gregorian + * (or nullptr, or an empty string) then the type is appended to the resource name, + * for example, 'Eras_japanese' instead of 'Eras'. If the resource 'Eras_japanese' did + * not exist (even in root), then this class will fall back to just 'Eras', that is, + * Gregorian data. Therefore, the calendar implementor MUST ensure that the root + * locale at least contains any resources that are to be particularized for the + * calendar type. + */ +class U_I18N_API DateFormatSymbols final : public UObject { +public: + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the default locale, in the default calendar (Gregorian). + *

+ * NOTE: This constructor will never fail; if it cannot get resource + * data for the default locale, it will return a last-resort object + * based on hard-coded strings. + * + * @param status Status code. Failure + * results if the resources for the default cannot be + * found or cannot be loaded + * @stable ICU 2.0 + */ + DateFormatSymbols(UErrorCode& status); + + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the given locale, in the default calendar (Gregorian). + * + * @param locale Locale to load format data from. + * @param status Status code. Failure + * results if the resources for the locale cannot be + * found or cannot be loaded + * @stable ICU 2.0 + */ + DateFormatSymbols(const Locale& locale, + UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the default locale, in the default calendar (Gregorian). + *

+ * NOTE: This constructor will never fail; if it cannot get resource + * data for the default locale, it will return a last-resort object + * based on hard-coded strings. + * + * @param type Type of calendar (as returned by Calendar::getType). + * Will be used to access the correct set of strings. + * (nullptr or empty string defaults to "gregorian".) + * @param status Status code. Failure + * results if the resources for the default cannot be + * found or cannot be loaded + * @internal + */ + DateFormatSymbols(const char *type, UErrorCode& status); + + /** + * Construct a DateFormatSymbols object by loading format data from + * resources for the given locale, in the default calendar (Gregorian). + * + * @param locale Locale to load format data from. + * @param type Type of calendar (as returned by Calendar::getType). + * Will be used to access the correct set of strings. + * (nullptr or empty string defaults to "gregorian".) + * @param status Status code. Failure + * results if the resources for the locale cannot be + * found or cannot be loaded + * @internal + */ + DateFormatSymbols(const Locale& locale, + const char *type, + UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + DateFormatSymbols(const DateFormatSymbols&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + DateFormatSymbols& operator=(const DateFormatSymbols&); + + /** + * Destructor. This is nonvirtual because this class is not designed to be + * subclassed. + * @stable ICU 2.0 + */ + virtual ~DateFormatSymbols(); + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the DateFormatSymbols object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 2.0 + */ + bool operator==(const DateFormatSymbols& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the DateFormatSymbols object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 2.0 + */ + bool operator!=(const DateFormatSymbols& other) const { return !operator==(other); } + + /** + * Gets abbreviated era strings. For example: "AD" and "BC". + * + * @param count Filled in with length of the array. + * @return the era strings. + * @stable ICU 2.0 + */ + const UnicodeString* getEras(int32_t& count) const; + + /** + * Sets abbreviated era strings. For example: "AD" and "BC". + * @param eras Array of era strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setEras(const UnicodeString* eras, int32_t count); + + /** + * Gets era name strings. For example: "Anno Domini" and "Before Christ". + * + * @param count Filled in with length of the array. + * @return the era name strings. + * @stable ICU 3.4 + */ + const UnicodeString* getEraNames(int32_t& count) const; + + /** + * Sets era name strings. For example: "Anno Domini" and "Before Christ". + * @param eraNames Array of era name strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 3.6 + */ + void setEraNames(const UnicodeString* eraNames, int32_t count); + + /** + * Gets narrow era strings. For example: "A" and "B". + * + * @param count Filled in with length of the array. + * @return the narrow era strings. + * @stable ICU 4.2 + */ + const UnicodeString* getNarrowEras(int32_t& count) const; + + /** + * Sets narrow era strings. For example: "A" and "B". + * @param narrowEras Array of narrow era strings (DateFormatSymbols retains ownership.) + * @param count Filled in with length of the array. + * @stable ICU 4.2 + */ + void setNarrowEras(const UnicodeString* narrowEras, int32_t count); + + /** + * Gets month strings. For example: "January", "February", etc. + * @param count Filled in with length of the array. + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getMonths(int32_t& count) const; + + /** + * Sets month strings. For example: "January", "February", etc. + * + * @param months the new month strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setMonths(const UnicodeString* months, int32_t count); + + /** + * Gets short month strings. For example: "Jan", "Feb", etc. + * + * @param count Filled in with length of the array. + * @return the short month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getShortMonths(int32_t& count) const; + + /** + * Sets short month strings. For example: "Jan", "Feb", etc. + * @param count Filled in with length of the array. + * @param shortMonths the new short month strings. (not adopted; caller retains ownership) + * @stable ICU 2.0 + */ + void setShortMonths(const UnicodeString* shortMonths, int32_t count); + + /** + * Selector for date formatting context + * @stable ICU 3.6 + */ + enum DtContextType { + FORMAT, + STANDALONE, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal DtContextType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + DT_CONTEXT_COUNT +#endif // U_HIDE_DEPRECATED_API + }; + + /** + * Selector for date formatting width + * @stable ICU 3.6 + */ + enum DtWidthType { + ABBREVIATED, + WIDE, + NARROW, + /** + * Short width is currently only supported for weekday names. + * @stable ICU 51 + */ + SHORT, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal DtWidthType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + DT_WIDTH_COUNT = 4 +#endif // U_HIDE_DEPRECATED_API + }; + + /** + * Gets month strings by width and context. For example: "January", "February", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.4 + */ + const UnicodeString* getMonths(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets month strings by width and context. For example: "January", "February", etc. + * + * @param months The new month strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @stable ICU 3.6 + */ + void setMonths(const UnicodeString* months, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets wide weekday strings. For example: "Sunday", "Monday", etc. + * @param count Filled in with length of the array. + * @return the weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getWeekdays(int32_t& count) const; + + + /** + * Sets wide weekday strings. For example: "Sunday", "Monday", etc. + * @param weekdays the new weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setWeekdays(const UnicodeString* weekdays, int32_t count); + + /** + * Gets abbreviated weekday strings. For example: "Sun", "Mon", etc. (Note: The method name is + * misleading; it does not get the CLDR-style "short" weekday strings, e.g. "Su", "Mo", etc.) + * @param count Filled in with length of the array. + * @return the abbreviated weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getShortWeekdays(int32_t& count) const; + + /** + * Sets abbreviated weekday strings. For example: "Sun", "Mon", etc. (Note: The method name is + * misleading; it does not set the CLDR-style "short" weekday strings, e.g. "Su", "Mo", etc.) + * @param abbrevWeekdays the new abbreviated weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setShortWeekdays(const UnicodeString* abbrevWeekdays, int32_t count); + + /** + * Gets weekday strings by width and context. For example: "Sunday", "Monday", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, SHORT, or NARROW + * @return the month strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.4 + */ + const UnicodeString* getWeekdays(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets weekday strings by width and context. For example: "Sunday", "Monday", etc. + * @param weekdays The new weekday strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, SHORT, or NARROW + * @stable ICU 3.6 + */ + void setWeekdays(const UnicodeString* weekdays, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @return the quarter strings. (DateFormatSymbols retains ownership.) + * @stable ICU 3.6 + */ + const UnicodeString* getQuarters(int32_t& count, DtContextType context, DtWidthType width) const; + + /** + * Sets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. + * + * @param quarters The new quarter strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @param context The formatting context, either FORMAT or STANDALONE + * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. + * @stable ICU 3.6 + */ + void setQuarters(const UnicodeString* quarters, int32_t count, DtContextType context, DtWidthType width); + + /** + * Gets AM/PM strings. For example: "AM" and "PM". + * @param count Filled in with length of the array. + * @return the weekday strings. (DateFormatSymbols retains ownership.) + * @stable ICU 2.0 + */ + const UnicodeString* getAmPmStrings(int32_t& count) const; + + /** + * Sets ampm strings. For example: "AM" and "PM". + * @param ampms the new ampm strings. (not adopted; caller retains ownership) + * @param count Filled in with length of the array. + * @stable ICU 2.0 + */ + void setAmPmStrings(const UnicodeString* ampms, int32_t count); + +#ifndef U_HIDE_INTERNAL_API + /** + * This default time separator is used for formatting when the locale + * doesn't specify any time separator, and always recognized when parsing. + * @internal + */ + static const char16_t DEFAULT_TIME_SEPARATOR = 0x003a; // ':' + + /** + * This alternate time separator is always recognized when parsing. + * @internal + */ + static const char16_t ALTERNATE_TIME_SEPARATOR = 0x002e; // '.' + + /** + * Gets the time separator string. For example: ":". + * @param result Output param which will receive the time separator string. + * @return A reference to 'result'. + * @internal + */ + UnicodeString& getTimeSeparatorString(UnicodeString& result) const; + + /** + * Sets the time separator string. For example: ":". + * @param newTimeSeparator the new time separator string. + * @internal + */ + void setTimeSeparatorString(const UnicodeString& newTimeSeparator); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Gets cyclic year name strings if the calendar has them, by width and context. + * For example: "jia-zi", "yi-chou", etc. + * @param count Filled in with length of the array. + * @param context The usage context: FORMAT, STANDALONE. + * @param width The requested name width: WIDE, ABBREVIATED, NARROW. + * @return The year name strings (DateFormatSymbols retains ownership), + * or null if they are not available for this calendar. + * @stable ICU 54 + */ + const UnicodeString* getYearNames(int32_t& count, + DtContextType context, DtWidthType width) const; + + /** + * Sets cyclic year name strings by width and context. For example: "jia-zi", "yi-chou", etc. + * + * @param yearNames The new cyclic year name strings (not adopted; caller retains ownership). + * @param count The length of the array. + * @param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported). + * @param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported). + * @stable ICU 54 + */ + void setYearNames(const UnicodeString* yearNames, int32_t count, + DtContextType context, DtWidthType width); + + /** + * Gets calendar zodiac name strings if the calendar has them, by width and context. + * For example: "Rat", "Ox", "Tiger", etc. + * @param count Filled in with length of the array. + * @param context The usage context: FORMAT, STANDALONE. + * @param width The requested name width: WIDE, ABBREVIATED, NARROW. + * @return The zodiac name strings (DateFormatSymbols retains ownership), + * or null if they are not available for this calendar. + * @stable ICU 54 + */ + const UnicodeString* getZodiacNames(int32_t& count, + DtContextType context, DtWidthType width) const; + + /** + * Sets calendar zodiac name strings by width and context. For example: "Rat", "Ox", "Tiger", etc. + * + * @param zodiacNames The new zodiac name strings (not adopted; caller retains ownership). + * @param count The length of the array. + * @param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported). + * @param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported). + * @stable ICU 54 + */ + void setZodiacNames(const UnicodeString* zodiacNames, int32_t count, + DtContextType context, DtWidthType width); + +#ifndef U_HIDE_INTERNAL_API + /** + * Somewhat temporary constants for leap month pattern types, adequate for supporting + * just leap month patterns as needed for Chinese lunar calendar. + * Eventually we will add full support for different month pattern types (needed for + * other calendars such as Hindu) at which point this approach will be replaced by a + * more complete approach. + * @internal + */ + enum EMonthPatternType + { + kLeapMonthPatternFormatWide, + kLeapMonthPatternFormatAbbrev, + kLeapMonthPatternFormatNarrow, + kLeapMonthPatternStandaloneWide, + kLeapMonthPatternStandaloneAbbrev, + kLeapMonthPatternStandaloneNarrow, + kLeapMonthPatternNumeric, + kMonthPatternsCount + }; + + /** + * Somewhat temporary function for getting complete set of leap month patterns for all + * contexts & widths, indexed by EMonthPatternType values. Returns nullptr if calendar + * does not have leap month patterns. Note, there is currently no setter for this. + * Eventually we will add full support for different month pattern types (needed for + * other calendars such as Hindu) at which point this approach will be replaced by a + * more complete approach. + * @param count Filled in with length of the array (may be 0). + * @return The leap month patterns (DateFormatSymbols retains ownership). + * May be nullptr if there are no leap month patterns for this calendar. + * @internal + */ + const UnicodeString* getLeapMonthPatterns(int32_t& count) const; + +#endif /* U_HIDE_INTERNAL_API */ + +#ifndef U_HIDE_DEPRECATED_API + /** + * Gets timezone strings. These strings are stored in a 2-dimensional array. + * @param rowCount Output param to receive number of rows. + * @param columnCount Output param to receive number of columns. + * @return The timezone strings as a 2-d array. (DateFormatSymbols retains ownership.) + * @deprecated ICU 3.6 + */ + const UnicodeString** getZoneStrings(int32_t& rowCount, int32_t& columnCount) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Sets timezone strings. These strings are stored in a 2-dimensional array. + *

Note: SimpleDateFormat no longer use the zone strings stored in + * a DateFormatSymbols. Therefore, the time zone strings set by this method + * have no effects in an instance of SimpleDateFormat for formatting time + * zones. + * @param strings The timezone strings as a 2-d array to be copied. (not adopted; caller retains ownership) + * @param rowCount The number of rows (count of first index). + * @param columnCount The number of columns (count of second index). + * @stable ICU 2.0 + */ + void setZoneStrings(const UnicodeString* const* strings, int32_t rowCount, int32_t columnCount); + + /** + * Get the non-localized date-time pattern characters. + * @return the non-localized date-time pattern characters + * @stable ICU 2.0 + */ + static const char16_t * U_EXPORT2 getPatternUChars(void); + + /** + * Gets localized date-time pattern characters. For example: 'u', 't', etc. + *

+ * Note: ICU no longer provides localized date-time pattern characters for a locale + * starting ICU 3.8. This method returns the non-localized date-time pattern + * characters unless user defined localized data is set by setLocalPatternChars. + * @param result Output param which will receive the localized date-time pattern characters. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getLocalPatternChars(UnicodeString& result) const; + + /** + * Sets localized date-time pattern characters. For example: 'u', 't', etc. + * @param newLocalPatternChars the new localized date-time + * pattern characters. + * @stable ICU 2.0 + */ + void setLocalPatternChars(const UnicodeString& newLocalPatternChars); + + /** + * Returns the locale for this object. Two flavors are available: + * valid and actual locale. + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; + + /* The following type and kCapContextUsageTypeCount cannot be #ifndef U_HIDE_INTERNAL_API, + they are needed for .h file declarations. */ + /** + * Constants for capitalization context usage types. + * @internal + */ + enum ECapitalizationContextUsageType + { +#ifndef U_HIDE_INTERNAL_API + kCapContextUsageOther = 0, + kCapContextUsageMonthFormat, /* except narrow */ + kCapContextUsageMonthStandalone, /* except narrow */ + kCapContextUsageMonthNarrow, + kCapContextUsageDayFormat, /* except narrow */ + kCapContextUsageDayStandalone, /* except narrow */ + kCapContextUsageDayNarrow, + kCapContextUsageEraWide, + kCapContextUsageEraAbbrev, + kCapContextUsageEraNarrow, + kCapContextUsageZoneLong, + kCapContextUsageZoneShort, + kCapContextUsageMetazoneLong, + kCapContextUsageMetazoneShort, +#endif /* U_HIDE_INTERNAL_API */ + kCapContextUsageTypeCount = 14 + }; + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + + friend class SimpleDateFormat; + friend class DateFormatSymbolsSingleSetter; // see udat.cpp + + /** + * Abbreviated era strings. For example: "AD" and "BC". + */ + UnicodeString* fEras; + int32_t fErasCount; + + /** + * Era name strings. For example: "Anno Domini" and "Before Christ". + */ + UnicodeString* fEraNames; + int32_t fEraNamesCount; + + /** + * Narrow era strings. For example: "A" and "B". + */ + UnicodeString* fNarrowEras; + int32_t fNarrowErasCount; + + /** + * Month strings. For example: "January", "February", etc. + */ + UnicodeString* fMonths; + int32_t fMonthsCount; + + /** + * Short month strings. For example: "Jan", "Feb", etc. + */ + UnicodeString* fShortMonths; + int32_t fShortMonthsCount; + + /** + * Narrow month strings. For example: "J", "F", etc. + */ + UnicodeString* fNarrowMonths; + int32_t fNarrowMonthsCount; + + /** + * Standalone Month strings. For example: "January", "February", etc. + */ + UnicodeString* fStandaloneMonths; + int32_t fStandaloneMonthsCount; + + /** + * Standalone Short month strings. For example: "Jan", "Feb", etc. + */ + UnicodeString* fStandaloneShortMonths; + int32_t fStandaloneShortMonthsCount; + + /** + * Standalone Narrow month strings. For example: "J", "F", etc. + */ + UnicodeString* fStandaloneNarrowMonths; + int32_t fStandaloneNarrowMonthsCount; + + /** + * CLDR-style format wide weekday strings. For example: "Sunday", "Monday", etc. + */ + UnicodeString* fWeekdays; + int32_t fWeekdaysCount; + + /** + * CLDR-style format abbreviated (not short) weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fShortWeekdays; + int32_t fShortWeekdaysCount; + + /** + * CLDR-style format short weekday strings. For example: "Su", "Mo", etc. + */ + UnicodeString* fShorterWeekdays; + int32_t fShorterWeekdaysCount; + + /** + * CLDR-style format narrow weekday strings. For example: "S", "M", etc. + */ + UnicodeString* fNarrowWeekdays; + int32_t fNarrowWeekdaysCount; + + /** + * CLDR-style standalone wide weekday strings. For example: "Sunday", "Monday", etc. + */ + UnicodeString* fStandaloneWeekdays; + int32_t fStandaloneWeekdaysCount; + + /** + * CLDR-style standalone abbreviated (not short) weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fStandaloneShortWeekdays; + int32_t fStandaloneShortWeekdaysCount; + + /** + * CLDR-style standalone short weekday strings. For example: "Su", "Mo", etc. + */ + UnicodeString* fStandaloneShorterWeekdays; + int32_t fStandaloneShorterWeekdaysCount; + + /** + * Standalone Narrow weekday strings. For example: "Sun", "Mon", etc. + */ + UnicodeString* fStandaloneNarrowWeekdays; + int32_t fStandaloneNarrowWeekdaysCount; + + /** + * Ampm strings. For example: "AM" and "PM". + */ + UnicodeString* fAmPms; + int32_t fAmPmsCount; + + /** + * Narrow Ampm strings. For example: "a" and "p". + */ + UnicodeString* fNarrowAmPms; + int32_t fNarrowAmPmsCount; + + /** + * Time separator string. For example: ":". + */ + UnicodeString fTimeSeparator; + + /** + * Quarter strings. For example: "1st quarter", "2nd quarter", etc. + */ + UnicodeString *fQuarters; + int32_t fQuartersCount; + + /** + * Short quarters. For example: "Q1", "Q2", etc. + */ + UnicodeString *fShortQuarters; + int32_t fShortQuartersCount; + + /** + * Narrow quarters. For example: "1", "2", etc. + * (In many, but not all, locales, this is the same as "Q", but there are locales for which this isn't true.) + */ + UnicodeString *fNarrowQuarters; + int32_t fNarrowQuartersCount; + + /** + * Standalone quarter strings. For example: "1st quarter", "2nd quarter", etc. + */ + UnicodeString *fStandaloneQuarters; + int32_t fStandaloneQuartersCount; + + /** + * Standalone short quarter strings. For example: "Q1", "Q2", etc. + */ + UnicodeString *fStandaloneShortQuarters; + int32_t fStandaloneShortQuartersCount; + + /** + * Standalone narrow quarter strings. For example: "1", "2", etc. + * (In many, but not all, locales, this is the same as "q", but there are locales for which this isn't true.) + */ + UnicodeString *fStandaloneNarrowQuarters; + int32_t fStandaloneNarrowQuartersCount; + + /** + * All leap month patterns, for example "{0}bis". + */ + UnicodeString *fLeapMonthPatterns; + int32_t fLeapMonthPatternsCount; + + /** + * Cyclic year names, for example: "jia-zi", "yi-chou", ... "gui-hai"; + * currently we only have data for format/abbreviated. + * For the others, just get from format/abbreviated, ignore set. + */ + UnicodeString *fShortYearNames; + int32_t fShortYearNamesCount; + + /** + * Cyclic zodiac names, for example "Rat", "Ox", "Tiger", etc.; + * currently we only have data for format/abbreviated. + * For the others, just get from format/abbreviated, ignore set. + */ + UnicodeString *fShortZodiacNames; + int32_t fShortZodiacNamesCount; + + /** + * Localized names of time zones in this locale. This is a + * two-dimensional array of strings of size n by m, + * where m is at least 5 and up to 7. Each of the n rows is an + * entry containing the localized names for a single TimeZone. + * + * Each such row contains (with i ranging from 0..n-1): + * + * zoneStrings[i][0] - time zone ID + * example: America/Los_Angeles + * zoneStrings[i][1] - long name of zone in standard time + * example: Pacific Standard Time + * zoneStrings[i][2] - short name of zone in standard time + * example: PST + * zoneStrings[i][3] - long name of zone in daylight savings time + * example: Pacific Daylight Time + * zoneStrings[i][4] - short name of zone in daylight savings time + * example: PDT + * zoneStrings[i][5] - location name of zone + * example: United States (Los Angeles) + * zoneStrings[i][6] - long generic name of zone + * example: Pacific Time + * zoneStrings[i][7] - short generic of zone + * example: PT + * + * The zone ID is not localized; it corresponds to the ID + * value associated with a system time zone object. All other entries + * are localized names. If a zone does not implement daylight savings + * time, the daylight savings time names are ignored. + * + * Note:CLDR 1.5 introduced metazone and its historical mappings. + * This simple two-dimensional array is no longer sufficient to represent + * localized names and its historic changes. Since ICU 3.8.1, localized + * zone names extracted from ICU locale data is stored in a ZoneStringFormat + * instance. But we still need to support the old way of customizing + * localized zone names, so we keep this field for the purpose. + */ + UnicodeString **fZoneStrings; // Zone string array set by setZoneStrings + UnicodeString **fLocaleZoneStrings; // Zone string array created by the locale + int32_t fZoneStringsRowCount; + int32_t fZoneStringsColCount; + + Locale fZSFLocale; // Locale used for getting ZoneStringFormat + + /** + * Localized date-time pattern characters. For example: use 'u' as 'y'. + */ + UnicodeString fLocalPatternChars; + + /** + * Capitalization transforms. For each usage type, the first array element indicates + * whether to titlecase for uiListOrMenu context, the second indicates whether to + * titlecase for stand-alone context. + */ + UBool fCapitalization[kCapContextUsageTypeCount][2]; + + /** + * Abbreviated (== short) day period strings. + */ + UnicodeString *fAbbreviatedDayPeriods; + int32_t fAbbreviatedDayPeriodsCount; + + /** + * Wide day period strings. + */ + UnicodeString *fWideDayPeriods; + int32_t fWideDayPeriodsCount; + + /** + * Narrow day period strings. + */ + UnicodeString *fNarrowDayPeriods; + int32_t fNarrowDayPeriodsCount; + + /** + * Stand-alone abbreviated (== short) day period strings. + */ + UnicodeString *fStandaloneAbbreviatedDayPeriods; + int32_t fStandaloneAbbreviatedDayPeriodsCount; + + /** + * Stand-alone wide day period strings. + */ + UnicodeString *fStandaloneWideDayPeriods; + int32_t fStandaloneWideDayPeriodsCount; + + /** + * Stand-alone narrow day period strings. + */ + UnicodeString *fStandaloneNarrowDayPeriods; + int32_t fStandaloneNarrowDayPeriodsCount; + +private: + /** valid/actual locale information + * these are always ICU locales, so the length should not be a problem + */ + char validLocale[ULOC_FULLNAME_CAPACITY]; + char actualLocale[ULOC_FULLNAME_CAPACITY]; + + DateFormatSymbols() = delete; // default constructor not implemented + + /** + * Called by the constructors to actually load data from the resources + * + * @param locale The locale to get symbols for. + * @param type Calendar Type (as from Calendar::getType()) + * @param status Input/output parameter, set to success or + * failure code upon return. + * @param useLastResortData determine if use last resort data + */ + void initializeData(const Locale& locale, const char *type, + UErrorCode& status, UBool useLastResortData = false); + + /** + * Copy or alias an array in another object, as appropriate. + * + * @param dstArray the copy destination array. + * @param dstCount fill in with the length of 'dstArray'. + * @param srcArray the source array to be copied. + * @param srcCount the length of items to be copied from the 'srcArray'. + */ + static void assignArray(UnicodeString*& dstArray, + int32_t& dstCount, + const UnicodeString* srcArray, + int32_t srcCount); + + /** + * Return true if the given arrays' contents are equal, or if the arrays are + * identical (pointers are equal). + * + * @param array1 one array to be compared with. + * @param array2 another array to be compared with. + * @param count the length of items to be copied. + * @return true if the given arrays' contents are equal, or if the arrays are + * identical (pointers are equal). + */ + static UBool arrayCompare(const UnicodeString* array1, + const UnicodeString* array2, + int32_t count); + + /** + * Create a copy, in fZoneStrings, of the given zone strings array. The + * member variables fZoneStringsRowCount and fZoneStringsColCount should be + * set already by the caller. + */ + void createZoneStrings(const UnicodeString *const * otherStrings); + + /** + * Delete all the storage owned by this object. + */ + void dispose(void); + + /** + * Copy all of the other's data to this. + * @param other the object to be copied. + */ + void copyData(const DateFormatSymbols& other); + + /** + * Create zone strings array by locale if not yet available + */ + void initZoneStringsArray(void); + + /** + * Delete just the zone strings. + */ + void disposeZoneStrings(void); + + /** + * Returns the date format field index of the pattern character c, + * or UDAT_FIELD_COUNT if c is not a pattern character. + */ + static UDateFormatField U_EXPORT2 getPatternCharIndex(char16_t c); + + /** + * Returns true if f (with its pattern character repeated count times) is a numeric field. + */ + static UBool U_EXPORT2 isNumericField(UDateFormatField f, int32_t count); + + /** + * Returns true if c (repeated count times) is the pattern character for a numeric field. + */ + static UBool U_EXPORT2 isNumericPatternChar(char16_t c, int32_t count); +public: +#ifndef U_HIDE_INTERNAL_API + /** + * Gets a DateFormatSymbols by locale. + * Unlike the constructors which always use gregorian calendar, this + * method uses the calendar in the locale. If the locale contains no + * explicit calendar, this method uses the default calendar for that + * locale. + * @param locale the locale. + * @param status error returned here. + * @return the new DateFormatSymbols which the caller owns. + * @internal For ICU use only. + */ + static DateFormatSymbols * U_EXPORT2 createForLocale( + const Locale &locale, UErrorCode &status); +#endif /* U_HIDE_INTERNAL_API */ +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _DTFMTSYM +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtintrv.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtintrv.h new file mode 100644 index 0000000000000000000000000000000000000000..8c172eb7a59accdf07be0b597ba6404368da7c9b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtintrv.h @@ -0,0 +1,164 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2008-2009, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File DTINTRV.H +* +******************************************************************************* +*/ + +#ifndef __DTINTRV_H__ +#define __DTINTRV_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Date Interval data type + */ + +U_NAMESPACE_BEGIN + + +/** + * This class represents a date interval. + * It is a pair of UDate representing from UDate 1 to UDate 2. + * @stable ICU 4.0 +**/ +class U_COMMON_API DateInterval : public UObject { +public: + + /** + * Construct a DateInterval given a from date and a to date. + * @param fromDate The from date in date interval. + * @param toDate The to date in date interval. + * @stable ICU 4.0 + */ + DateInterval(UDate fromDate, UDate toDate); + + /** + * destructor + * @stable ICU 4.0 + */ + virtual ~DateInterval(); + + /** + * Get the from date. + * @return the from date in dateInterval. + * @stable ICU 4.0 + */ + inline UDate getFromDate() const; + + /** + * Get the to date. + * @return the to date in dateInterval. + * @stable ICU 4.0 + */ + inline UDate getToDate() const; + + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 4.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 4.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + + /** + * Copy constructor. + * @stable ICU 4.0 + */ + DateInterval(const DateInterval& other); + + /** + * Default assignment operator + * @stable ICU 4.0 + */ + DateInterval& operator=(const DateInterval&); + + /** + * Equality operator. + * @return true if the two DateIntervals are the same + * @stable ICU 4.0 + */ + virtual bool operator==(const DateInterval& other) const; + + /** + * Non-equality operator + * @return true if the two DateIntervals are not the same + * @stable ICU 4.0 + */ + inline bool operator!=(const DateInterval& other) const; + + + /** + * clone this object. + * The caller owns the result and should delete it when done. + * @return a cloned DateInterval + * @stable ICU 4.0 + */ + virtual DateInterval* clone() const; + +private: + /** + * Default constructor, not implemented. + */ + DateInterval() = delete; + + UDate fromDate; + UDate toDate; + +} ;// end class DateInterval + + +inline UDate +DateInterval::getFromDate() const { + return fromDate; +} + + +inline UDate +DateInterval::getToDate() const { + return toDate; +} + + +inline bool +DateInterval::operator!=(const DateInterval& other) const { + return ( !operator==(other) ); +} + + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..b4dc8cabf04572e54c0fef22a3faf755557221ac --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvfmt.h @@ -0,0 +1,1212 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/******************************************************************************** +* Copyright (C) 2008-2016, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File DTITVFMT.H +* +******************************************************************************* +*/ + +#ifndef __DTITVFMT_H__ +#define __DTITVFMT_H__ + + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Format and parse date interval in a language-independent manner. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/ucal.h" +#include "unicode/smpdtfmt.h" +#include "unicode/dtintrv.h" +#include "unicode/dtitvinf.h" +#include "unicode/dtptngen.h" +#include "unicode/formattedvalue.h" +#include "unicode/udisplaycontext.h" + +U_NAMESPACE_BEGIN + + +class FormattedDateIntervalData; +class DateIntervalFormat; + +/** + * An immutable class containing the result of a date interval formatting operation. + * + * Instances of this class are immutable and thread-safe. + * + * When calling nextPosition(): + * The fields are returned from left to right. The special field category + * UFIELD_CATEGORY_DATE_INTERVAL_SPAN is used to indicate which datetime + * primitives came from which arguments: 0 means fromCalendar, and 1 means + * toCalendar. The span category will always occur before the + * corresponding fields in UFIELD_CATEGORY_DATE + * in the nextPosition() iterator. + * + * Not intended for public subclassing. + * + * @stable ICU 64 + */ +class U_I18N_API FormattedDateInterval : public UMemory, public FormattedValue { + public: + /** + * Default constructor; makes an empty FormattedDateInterval. + * @stable ICU 64 + */ + FormattedDateInterval() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} + + /** + * Move constructor: Leaves the source FormattedDateInterval in an undefined state. + * @stable ICU 64 + */ + FormattedDateInterval(FormattedDateInterval&& src) noexcept; + + /** + * Destruct an instance of FormattedDateInterval. + * @stable ICU 64 + */ + virtual ~FormattedDateInterval() override; + + /** Copying not supported; use move constructor instead. */ + FormattedDateInterval(const FormattedDateInterval&) = delete; + + /** Copying not supported; use move assignment instead. */ + FormattedDateInterval& operator=(const FormattedDateInterval&) = delete; + + /** + * Move assignment: Leaves the source FormattedDateInterval in an undefined state. + * @stable ICU 64 + */ + FormattedDateInterval& operator=(FormattedDateInterval&& src) noexcept; + + /** @copydoc FormattedValue::toString() */ + UnicodeString toString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::toTempString() */ + UnicodeString toTempString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::appendTo() */ + Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override; + + /** @copydoc FormattedValue::nextPosition() */ + UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; + + private: + FormattedDateIntervalData *fData; + UErrorCode fErrorCode; + explicit FormattedDateInterval(FormattedDateIntervalData *results) + : fData(results), fErrorCode(U_ZERO_ERROR) {} + explicit FormattedDateInterval(UErrorCode errorCode) + : fData(nullptr), fErrorCode(errorCode) {} + friend class DateIntervalFormat; +}; + + +/** + * DateIntervalFormat is a class for formatting and parsing date + * intervals in a language-independent manner. + * Only formatting is supported, parsing is not supported. + * + *

+ * Date interval means from one date to another date, + * for example, from "Jan 11, 2008" to "Jan 18, 2008". + * We introduced class DateInterval to represent it. + * DateInterval is a pair of UDate, which is + * the standard milliseconds since 24:00 GMT, Jan 1, 1970. + * + *

+ * DateIntervalFormat formats a DateInterval into + * text as compactly as possible. + * For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008" + * is "Jan 11-18, 2008" for English. + * And it parses text into DateInterval, + * although initially, parsing is not supported. + * + *

+ * There is no structural information in date time patterns. + * For any punctuations and string literals inside a date time pattern, + * we do not know whether it is just a separator, or a prefix, or a suffix. + * Without such information, so, it is difficult to generate a sub-pattern + * (or super-pattern) by algorithm. + * So, formatting a DateInterval is pattern-driven. It is very + * similar to formatting in SimpleDateFormat. + * We introduce class DateIntervalInfo to save date interval + * patterns, similar to date time pattern in SimpleDateFormat. + * + *

+ * Logically, the interval patterns are mappings + * from (skeleton, the_largest_different_calendar_field) + * to (date_interval_pattern). + * + *

+ * A skeleton + *

    + *
  1. + * only keeps the field pattern letter and ignores all other parts + * in a pattern, such as space, punctuations, and string literals. + *
  2. + *
  3. + * hides the order of fields. + *
  4. + *
  5. + * might hide a field's pattern letter length. + *
  6. + *
+ * + * For those non-digit calendar fields, the pattern letter length is + * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, + * and the field's pattern letter length is honored. + * + * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, + * the field pattern length is ignored and the best match, which is defined + * in date time patterns, will be returned without honor the field pattern + * letter length in skeleton. + * + *

+ * The calendar fields we support for interval formatting are: + * year, month, date, day-of-week, am-pm, hour, hour-of-day, minute, second, + * and millisecond. + * (though we do not currently have specific intervalFormat date for skeletons + * with seconds and millisecond). + * Those calendar fields can be defined in the following order: + * year > month > date > hour (in day) > minute > second > millisecond + * + * The largest different calendar fields between 2 calendars is the + * first different calendar field in above order. + * + * For example: the largest different calendar fields between "Jan 10, 2007" + * and "Feb 20, 2008" is year. + * + *

+ * For other calendar fields, the compact interval formatting is not + * supported. And the interval format will be fall back to fall-back + * patterns, which is mostly "{date0} - {date1}". + * + *

+ * There is a set of pre-defined static skeleton strings. + * There are pre-defined interval patterns for those pre-defined skeletons + * in locales' resource files. + * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd", + * in en_US, if the largest different calendar field between date1 and date2 + * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", + * such as "Jan 10, 2007 - Jan 10, 2008". + * If the largest different calendar field between date1 and date2 is "month", + * the date interval pattern is "MMM d - MMM d, yyyy", + * such as "Jan 10 - Feb 10, 2007". + * If the largest different calendar field between date1 and date2 is "day", + * the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007". + * + * For date skeleton, the interval patterns when year, or month, or date is + * different are defined in resource files. + * For time skeleton, the interval patterns when am/pm, or hour, or minute is + * different are defined in resource files. + * + *

+ * If a skeleton is not found in a locale's DateIntervalInfo, which means + * the interval patterns for the skeleton is not defined in resource file, + * the interval pattern will falls back to the interval "fallback" pattern + * defined in resource file. + * If the interval "fallback" pattern is not defined, the default fall-back + * is "{date0} - {data1}". + * + *

+ * For the combination of date and time, + * The rule to generate interval patterns are: + *

    + *
  1. + * when the year, month, or day differs, falls back to fall-back + * interval pattern, which mostly is the concatenate the two original + * expressions with a separator between, + * For example, interval pattern from "Jan 10, 2007 10:10 am" + * to "Jan 11, 2007 10:10am" is + * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" + *
  2. + *
  3. + * otherwise, present the date followed by the range expression + * for the time. + * For example, interval pattern from "Jan 10, 2007 10:10 am" + * to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am" + *
  4. + *
+ * + * + *

+ * If two dates are the same, the interval pattern is the single date pattern. + * For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is + * "Jan 10, 2007". + * + * Or if the presenting fields between 2 dates have the exact same values, + * the interval pattern is the single date pattern. + * For example, if user only requests year and month, + * the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007". + * + *

+ * DateIntervalFormat needs the following information for correct + * formatting: time zone, calendar type, pattern, date format symbols, + * and date interval patterns. + * It can be instantiated in 2 ways: + *

    + *
  1. + * create an instance using default or given locale plus given skeleton. + * Users are encouraged to created date interval formatter this way and + * to use the pre-defined skeleton macros, such as + * UDAT_YEAR_NUM_MONTH, which consists the calendar fields and + * the format style. + *
  2. + *
  3. + * create an instance using default or given locale plus given skeleton + * plus a given DateIntervalInfo. + * This factory method is for powerful users who want to provide their own + * interval patterns. + * Locale provides the timezone, calendar, and format symbols information. + * Local plus skeleton provides full pattern information. + * DateIntervalInfo provides the date interval patterns. + *
  4. + *
+ * + *

+ * For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc. + * DateIntervalFormat uses the same syntax as that of + * DateTime format. + * + *

+ * Code Sample: general usage + *

+ * \code
+ *   // the date interval object which the DateIntervalFormat formats on
+ *   // and parses into
+ *   DateInterval*  dtInterval = new DateInterval(1000*3600*24, 1000*3600*24*2);
+ *   UErrorCode status = U_ZERO_ERROR;
+ *   DateIntervalFormat* dtIntervalFmt = DateIntervalFormat::createInstance(
+ *                           UDAT_YEAR_MONTH_DAY,
+ *                           Locale("en", "GB", ""), status);
+ *   UnicodeUnicodeString dateIntervalString;
+ *   FieldPosition pos = 0;
+ *   // formatting
+ *   dtIntervalFmt->format(dtInterval, dateIntervalUnicodeString, pos, status);
+ *   delete dtIntervalFmt;
+ * \endcode
+ * 
+ */ +class U_I18N_API DateIntervalFormat : public Format { +public: + + /** + * Construct a DateIntervalFormat from skeleton and the default locale. + * + * This is a convenient override of + * createInstance(const UnicodeString& skeleton, const Locale& locale, + * UErrorCode&) + * with the value of locale as default locale. + * + * @param skeleton the skeleton on which interval format based. + * @param status output param set to success/failure code on exit + * @return a date time interval formatter which the caller owns. + * @stable ICU 4.0 + */ + static DateIntervalFormat* U_EXPORT2 createInstance( + const UnicodeString& skeleton, + UErrorCode& status); + + /** + * Construct a DateIntervalFormat from skeleton and a given locale. + *

+ * In this factory method, + * the date interval pattern information is load from resource files. + * Users are encouraged to created date interval formatter this way and + * to use the pre-defined skeleton macros. + * + *

+ * There are pre-defined skeletons (defined in udate.h) having predefined + * interval patterns in resource files. + * Users are encouraged to use those macros. + * For example: + * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) + * + * The given Locale provides the interval patterns. + * For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY, + * which is "yMMMEEEd", + * the interval patterns defined in resource file to above skeleton are: + * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs, + * "EEE, d MMM - EEE, d MMM, yyyy" for month differs, + * "EEE, d - EEE, d MMM, yyyy" for day differs, + * @param skeleton the skeleton on which the interval format is based. + * @param locale the given locale + * @param status output param set to success/failure code on exit + * @return a date time interval formatter which the caller owns. + * @stable ICU 4.0 + *

+ *

Sample code

+ * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined1 + * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined + *

+ */ + + static DateIntervalFormat* U_EXPORT2 createInstance( + const UnicodeString& skeleton, + const Locale& locale, + UErrorCode& status); + + /** + * Construct a DateIntervalFormat from skeleton + * DateIntervalInfo, and default locale. + * + * This is a convenient override of + * createInstance(const UnicodeString& skeleton, const Locale& locale, + * const DateIntervalInfo& dtitvinf, UErrorCode&) + * with the locale value as default locale. + * + * @param skeleton the skeleton on which interval format based. + * @param dtitvinf the DateIntervalInfo object. + * @param status output param set to success/failure code on exit + * @return a date time interval formatter which the caller owns. + * @stable ICU 4.0 + */ + static DateIntervalFormat* U_EXPORT2 createInstance( + const UnicodeString& skeleton, + const DateIntervalInfo& dtitvinf, + UErrorCode& status); + + /** + * Construct a DateIntervalFormat from skeleton + * a DateIntervalInfo, and the given locale. + * + *

+ * In this factory method, user provides its own date interval pattern + * information, instead of using those pre-defined data in resource file. + * This factory method is for powerful users who want to provide their own + * interval patterns. + *

+ * There are pre-defined skeletons (defined in udate.h) having predefined + * interval patterns in resource files. + * Users are encouraged to use those macros. + * For example: + * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) + * + * The DateIntervalInfo provides the interval patterns. + * and the DateIntervalInfo ownership remains to the caller. + * + * User are encouraged to set default interval pattern in DateIntervalInfo + * as well, if they want to set other interval patterns ( instead of + * reading the interval patterns from resource files). + * When the corresponding interval pattern for a largest calendar different + * field is not found ( if user not set it ), interval format fallback to + * the default interval pattern. + * If user does not provide default interval pattern, it fallback to + * "{date0} - {date1}" + * + * @param skeleton the skeleton on which interval format based. + * @param locale the given locale + * @param dtitvinf the DateIntervalInfo object. + * @param status output param set to success/failure code on exit + * @return a date time interval formatter which the caller owns. + * @stable ICU 4.0 + *

+ *

Sample code

+ * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined1 + * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtCustomized + *

+ */ + static DateIntervalFormat* U_EXPORT2 createInstance( + const UnicodeString& skeleton, + const Locale& locale, + const DateIntervalInfo& dtitvinf, + UErrorCode& status); + + /** + * Destructor. + * @stable ICU 4.0 + */ + virtual ~DateIntervalFormat(); + + /** + * Clone this Format object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 4.0 + */ + virtual DateIntervalFormat* clone() const override; + + /** + * Return true if the given Format objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 4.0 + */ + virtual bool operator==(const Format& other) const override; + + /** + * Return true if the given Format objects are not semantically equal. + * Objects of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are not semantically equal. + * @stable ICU 4.0 + */ + bool operator!=(const Format& other) const; + + + using Format::format; + + /** + * Format an object to produce a string. This method handles Formattable + * objects with a DateInterval type. + * If a the Formattable object type is not a DateInterval, + * then it returns a failing UErrorCode. + * + * @param obj The object to format. + * Must be a DateInterval. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * There may be multiple instances of a given field type + * in an interval format; in this case the fieldPosition + * offsets refer to the first instance. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& fieldPosition, + UErrorCode& status) const override; + + + + /** + * Format a DateInterval to produce a string. + * + * @param dtInterval DateInterval to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * There may be multiple instances of a given field type + * in an interval format; in this case the fieldPosition + * offsets refer to the first instance. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.0 + */ + UnicodeString& format(const DateInterval* dtInterval, + UnicodeString& appendTo, + FieldPosition& fieldPosition, + UErrorCode& status) const ; + + /** + * Format a DateInterval to produce a FormattedDateInterval. + * + * The FormattedDateInterval exposes field information about the formatted string. + * + * @param dtInterval DateInterval to be formatted. + * @param status Set if an error occurs. + * @return A FormattedDateInterval containing the format result. + * @stable ICU 64 + */ + FormattedDateInterval formatToValue( + const DateInterval& dtInterval, + UErrorCode& status) const; + + /** + * Format 2 Calendars to produce a string. + * + * Note: "fromCalendar" and "toCalendar" are not const, + * since calendar is not const in SimpleDateFormat::format(Calendar&), + * + * @param fromCalendar calendar set to the from date in date interval + * to be formatted into date interval string + * @param toCalendar calendar set to the to date in date interval + * to be formatted into date interval string + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param fieldPosition On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * There may be multiple instances of a given field type + * in an interval format; in this case the fieldPosition + * offsets refer to the first instance. + * @param status Output param filled with success/failure status. + * Caller needs to make sure it is SUCCESS + * at the function entrance + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.0 + */ + UnicodeString& format(Calendar& fromCalendar, + Calendar& toCalendar, + UnicodeString& appendTo, + FieldPosition& fieldPosition, + UErrorCode& status) const ; + + /** + * Format 2 Calendars to produce a FormattedDateInterval. + * + * The FormattedDateInterval exposes field information about the formatted string. + * + * Note: "fromCalendar" and "toCalendar" are not const, + * since calendar is not const in SimpleDateFormat::format(Calendar&), + * + * @param fromCalendar calendar set to the from date in date interval + * to be formatted into date interval string + * @param toCalendar calendar set to the to date in date interval + * to be formatted into date interval string + * @param status Set if an error occurs. + * @return A FormattedDateInterval containing the format result. + * @stable ICU 64 + */ + FormattedDateInterval formatToValue( + Calendar& fromCalendar, + Calendar& toCalendar, + UErrorCode& status) const; + + /** + * Date interval parsing is not supported. Please do not use. + *

+ * This method should handle parsing of + * date time interval strings into Formattable objects with + * DateInterval type, which is a pair of UDate. + *

+ * Before calling, set parse_pos.index to the offset you want to start + * parsing at in the source. After calling, parse_pos.index is the end of + * the text you parsed. If error occurs, index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with a successful parse), + * while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Since no parsing + * is supported, upon return this param is unchanged. + * @return A newly created Formattable* object, or nullptr + * on failure. The caller owns this and should + * delete it when done. + * @internal ICU 4.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const override; + + + /** + * Gets the date time interval patterns. + * @return the date time interval patterns associated with + * this date interval formatter. + * @stable ICU 4.0 + */ + const DateIntervalInfo* getDateIntervalInfo(void) const; + + + /** + * Set the date time interval patterns. + * @param newIntervalPatterns the given interval patterns to copy. + * @param status output param set to success/failure code on exit + * @stable ICU 4.0 + */ + void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns, + UErrorCode& status); + + + /** + * Gets the date formatter. The DateIntervalFormat instance continues to own + * the returned DateFormatter object, and will use and possibly modify it + * during format operations. In a multi-threaded environment, the returned + * DateFormat can only be used if it is certain that no other threads are + * concurrently using this DateIntervalFormatter, even for nominally const + * functions. + * + * @return the date formatter associated with this date interval formatter. + * @stable ICU 4.0 + */ + const DateFormat* getDateFormat(void) const; + + /** + * Returns a reference to the TimeZone used by this DateIntervalFormat's calendar. + * @return the time zone associated with the calendar of DateIntervalFormat. + * @stable ICU 4.8 + */ + virtual const TimeZone& getTimeZone(void) const; + + /** + * Sets the time zone for the calendar used by this DateIntervalFormat object. The + * caller no longer owns the TimeZone object and should not delete it after this call. + * @param zoneToAdopt the TimeZone to be adopted. + * @stable ICU 4.8 + */ + virtual void adoptTimeZone(TimeZone* zoneToAdopt); + + /** + * Sets the time zone for the calendar used by this DateIntervalFormat object. + * @param zone the new time zone. + * @stable ICU 4.8 + */ + virtual void setTimeZone(const TimeZone& zone); + + /** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. This causes the formatted + * result to be capitalized appropriately for the context in which + * it is intended to be used, considering both the locale and the + * type of field at the beginning of the formatted result. + * @param value The UDisplayContext value to set. + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @stable ICU 68 + */ + virtual void setContext(UDisplayContext value, UErrorCode& status); + + /** + * Get the formatter's UDisplayContext value for the specified UDisplayContextType, + * such as UDISPCTX_TYPE_CAPITALIZATION. + * @param type The UDisplayContextType whose value to return + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @return The UDisplayContextValue for the specified type. + * @stable ICU 68 + */ + virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 4.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 4.0 + */ + virtual UClassID getDynamicClassID(void) const override; + +protected: + + /** + * Copy constructor. + * @stable ICU 4.0 + */ + DateIntervalFormat(const DateIntervalFormat&); + + /** + * Assignment operator. + * @stable ICU 4.0 + */ + DateIntervalFormat& operator=(const DateIntervalFormat&); + +private: + + /* + * This is for ICU internal use only. Please do not use. + * Save the interval pattern information. + * Interval pattern consists of 2 single date patterns and the separator. + * For example, interval pattern "MMM d - MMM d, yyyy" consists + * a single date pattern "MMM d", another single date pattern "MMM d, yyyy", + * and a separator "-". + * The pattern is divided into 2 parts. For above example, + * the first part is "MMM d - ", and the second part is "MMM d, yyyy". + * Also, the first date appears in an interval pattern could be + * the earlier date or the later date. + * And such information is saved in the interval pattern as well. + */ + struct PatternInfo { + UnicodeString firstPart; + UnicodeString secondPart; + /** + * Whether the first date in interval pattern is later date or not. + * Fallback format set the default ordering. + * And for a particular interval pattern, the order can be + * overridden by prefixing the interval pattern with "latestFirst:" or + * "earliestFirst:" + * For example, given 2 date, Jan 10, 2007 to Feb 10, 2007. + * if the fallback format is "{0} - {1}", + * and the pattern is "d MMM - d MMM yyyy", the interval format is + * "10 Jan - 10 Feb, 2007". + * If the pattern is "latestFirst:d MMM - d MMM yyyy", + * the interval format is "10 Feb - 10 Jan, 2007" + */ + UBool laterDateFirst; + }; + + + /** + * default constructor + * @internal (private) + */ + DateIntervalFormat(); + + /** + * Construct a DateIntervalFormat from DateFormat, + * a DateIntervalInfo, and skeleton. + * DateFormat provides the timezone, calendar, + * full pattern, and date format symbols information. + * It should be a SimpleDateFormat object which + * has a pattern in it. + * the DateIntervalInfo provides the interval patterns. + * + * Note: the DateIntervalFormat takes ownership of both + * DateFormat and DateIntervalInfo objects. + * Caller should not delete them. + * + * @param locale the locale of this date interval formatter. + * @param dtItvInfo the DateIntervalInfo object to be adopted. + * @param skeleton the skeleton of the date formatter + * @param status output param set to success/failure code on exit + */ + DateIntervalFormat(const Locale& locale, DateIntervalInfo* dtItvInfo, + const UnicodeString* skeleton, UErrorCode& status); + + + /** + * Construct a DateIntervalFormat from DateFormat + * and a DateIntervalInfo. + * + * It is a wrapper of the constructor. + * + * @param locale the locale of this date interval formatter. + * @param dtitvinf the DateIntervalInfo object to be adopted. + * @param skeleton the skeleton of this formatter. + * @param status Output param set to success/failure code. + * @return a date time interval formatter which the caller owns. + */ + static DateIntervalFormat* U_EXPORT2 create(const Locale& locale, + DateIntervalInfo* dtitvinf, + const UnicodeString* skeleton, + UErrorCode& status); + + /** + * Below are for generating interval patterns local to the formatter + */ + + /** Like fallbackFormat, but only formats the range part of the fallback. */ + void fallbackFormatRange( + Calendar& fromCalendar, + Calendar& toCalendar, + UnicodeString& appendTo, + int8_t& firstIndex, + FieldPositionHandler& fphandler, + UErrorCode& status) const; + + /** + * Format 2 Calendars using fall-back interval pattern + * + * The full pattern used in this fall-back format is the + * full pattern of the date formatter. + * + * gFormatterMutex must already be locked when calling this function. + * + * @param fromCalendar calendar set to the from date in date interval + * to be formatted into date interval string + * @param toCalendar calendar set to the to date in date interval + * to be formatted into date interval string + * @param fromToOnSameDay true iff from and to dates are on the same day + * (any difference is in ampm/hours or below) + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param firstIndex See formatImpl for more information. + * @param fphandler See formatImpl for more information. + * @param status output param set to success/failure code on exit + * @return Reference to 'appendTo' parameter. + * @internal (private) + */ + UnicodeString& fallbackFormat(Calendar& fromCalendar, + Calendar& toCalendar, + UBool fromToOnSameDay, + UnicodeString& appendTo, + int8_t& firstIndex, + FieldPositionHandler& fphandler, + UErrorCode& status) const; + + + + /** + * Initialize interval patterns locale to this formatter + * + * This code is a bit complicated since + * 1. the interval patterns saved in resource bundle files are interval + * patterns based on date or time only. + * It does not have interval patterns based on both date and time. + * Interval patterns on both date and time are algorithm generated. + * + * For example, it has interval patterns on skeleton "dMy" and "hm", + * but it does not have interval patterns on skeleton "dMyhm". + * + * The rule to generate interval patterns for both date and time skeleton are + * 1) when the year, month, or day differs, concatenate the two original + * expressions with a separator between, + * For example, interval pattern from "Jan 10, 2007 10:10 am" + * to "Jan 11, 2007 10:10am" is + * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" + * + * 2) otherwise, present the date followed by the range expression + * for the time. + * For example, interval pattern from "Jan 10, 2007 10:10 am" + * to "Jan 10, 2007 11:10am" is + * "Jan 10, 2007 10:10 am - 11:10am" + * + * 2. even a pattern does not request a certain calendar field, + * the interval pattern needs to include such field if such fields are + * different between 2 dates. + * For example, a pattern/skeleton is "hm", but the interval pattern + * includes year, month, and date when year, month, and date differs. + * + * + * @param status output param set to success/failure code on exit + */ + void initializePattern(UErrorCode& status); + + + + /** + * Set fall back interval pattern given a calendar field, + * a skeleton, and a date time pattern generator. + * @param field the largest different calendar field + * @param skeleton a skeleton + * @param status output param set to success/failure code on exit + */ + void setFallbackPattern(UCalendarDateFields field, + const UnicodeString& skeleton, + UErrorCode& status); + + + + /** + * Converts special hour metacharacters (such as 'j') in the skeleton into locale-appropriate + * pattern characters. + * + * + * @param skeleton The skeleton to convert + * @return A copy of the skeleton, which "j" and any other special hour metacharacters converted to the regular ones. + * + */ + UnicodeString normalizeHourMetacharacters(const UnicodeString& skeleton) const; + + + + /** + * get separated date and time skeleton from a combined skeleton. + * + * The difference between date skeleton and normalizedDateSkeleton are: + * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton + * 2. 'E' and 'EE' are normalized into 'EEE' + * 3. 'MM' is normalized into 'M' + * + ** the difference between time skeleton and normalizedTimeSkeleton are: + * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton, + * 2. 'a' is omitted in normalized time skeleton. + * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time + * skeleton + * + * + * @param skeleton given combined skeleton. + * @param date Output parameter for date only skeleton. + * @param normalizedDate Output parameter for normalized date only + * + * @param time Output parameter for time only skeleton. + * @param normalizedTime Output parameter for normalized time only + * skeleton. + * + */ + static void U_EXPORT2 getDateTimeSkeleton(const UnicodeString& skeleton, + UnicodeString& date, + UnicodeString& normalizedDate, + UnicodeString& time, + UnicodeString& normalizedTime); + + + + /** + * Generate date or time interval pattern from resource, + * and set them into the interval pattern locale to this formatter. + * + * It needs to handle the following: + * 1. need to adjust field width. + * For example, the interval patterns saved in DateIntervalInfo + * includes "dMMMy", but not "dMMMMy". + * Need to get interval patterns for dMMMMy from dMMMy. + * Another example, the interval patterns saved in DateIntervalInfo + * includes "hmv", but not "hmz". + * Need to get interval patterns for "hmz' from 'hmv' + * + * 2. there might be no pattern for 'y' differ for skeleton "Md", + * in order to get interval patterns for 'y' differ, + * need to look for it from skeleton 'yMd' + * + * @param dateSkeleton normalized date skeleton + * @param timeSkeleton normalized time skeleton + * @return whether the resource is found for the skeleton. + * true if interval pattern found for the skeleton, + * false otherwise. + */ + UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton, + const UnicodeString& timeSkeleton); + + + + + /** + * Generate interval pattern from existing resource + * + * It not only save the interval patterns, + * but also return the extended skeleton and its best match skeleton. + * + * @param field largest different calendar field + * @param skeleton skeleton + * @param bestSkeleton the best match skeleton which has interval pattern + * defined in resource + * @param differenceInfo the difference between skeleton and best skeleton + * 0 means the best matched skeleton is the same as input skeleton + * 1 means the fields are the same, but field width are different + * 2 means the only difference between fields are v/z, + * -1 means there are other fields difference + * + * @param extendedSkeleton extended skeleton + * @param extendedBestSkeleton extended best match skeleton + * @return whether the interval pattern is found + * through extending skeleton or not. + * true if interval pattern is found by + * extending skeleton, false otherwise. + */ + UBool setIntervalPattern(UCalendarDateFields field, + const UnicodeString* skeleton, + const UnicodeString* bestSkeleton, + int8_t differenceInfo, + UnicodeString* extendedSkeleton = nullptr, + UnicodeString* extendedBestSkeleton = nullptr); + + /** + * Adjust field width in best match interval pattern to match + * the field width in input skeleton. + * + * TODO (xji) make a general solution + * The adjusting rule can be: + * 1. always adjust + * 2. never adjust + * 3. default adjust, which means adjust according to the following rules + * 3.1 always adjust string, such as MMM and MMMM + * 3.2 never adjust between string and numeric, such as MM and MMM + * 3.3 always adjust year + * 3.4 do not adjust 'd', 'h', or 'm' if h presents + * 3.5 do not adjust 'M' if it is numeric(?) + * + * Since date interval format is well-formed format, + * date and time skeletons are normalized previously, + * till this stage, the adjust here is only "adjust strings, such as MMM + * and MMMM, EEE and EEEE. + * + * @param inputSkeleton the input skeleton + * @param bestMatchSkeleton the best match skeleton + * @param bestMatchIntervalPattern the best match interval pattern + * @param differenceInfo the difference between 2 skeletons + * 1 means only field width differs + * 2 means v/z exchange + * @param suppressDayPeriodField if true, remove the day period field from the pattern, if there is one + * @param adjustedIntervalPattern adjusted interval pattern + */ + static void U_EXPORT2 adjustFieldWidth( + const UnicodeString& inputSkeleton, + const UnicodeString& bestMatchSkeleton, + const UnicodeString& bestMatchIntervalPattern, + int8_t differenceInfo, + UBool suppressDayPeriodField, + UnicodeString& adjustedIntervalPattern); + + /** + * Does the same thing as UnicodeString::findAndReplace(), except that it won't perform + * the substitution inside quoted literal text. + * @param targetString The string to perform the find-replace operation on. + * @param strToReplace The string to search for and replace in the target string. + * @param strToReplaceWith The string to substitute in wherever `stringToReplace` was found. + */ + static void U_EXPORT2 findReplaceInPattern(UnicodeString& targetString, + const UnicodeString& strToReplace, + const UnicodeString& strToReplaceWith); + + /** + * Concat a single date pattern with a time interval pattern, + * set it into the intervalPatterns, while field is time field. + * This is used to handle time interval patterns on skeleton with + * both time and date. Present the date followed by + * the range expression for the time. + * @param format date and time format + * @param datePattern date pattern + * @param field time calendar field: AM_PM, HOUR, MINUTE + * @param status output param set to success/failure code on exit + */ + void concatSingleDate2TimeInterval(UnicodeString& format, + const UnicodeString& datePattern, + UCalendarDateFields field, + UErrorCode& status); + + /** + * check whether a calendar field present in a skeleton. + * @param field calendar field need to check + * @param skeleton given skeleton on which to check the calendar field + * @return true if field present in a skeleton. + */ + static UBool U_EXPORT2 fieldExistsInSkeleton(UCalendarDateFields field, + const UnicodeString& skeleton); + + + /** + * Split interval patterns into 2 part. + * @param intervalPattern interval pattern + * @return the index in interval pattern which split the pattern into 2 part + */ + static int32_t U_EXPORT2 splitPatternInto2Part(const UnicodeString& intervalPattern); + + + /** + * Break interval patterns as 2 part and save them into pattern info. + * @param field calendar field + * @param intervalPattern interval pattern + */ + void setIntervalPattern(UCalendarDateFields field, + const UnicodeString& intervalPattern); + + + /** + * Break interval patterns as 2 part and save them into pattern info. + * @param field calendar field + * @param intervalPattern interval pattern + * @param laterDateFirst whether later date appear first in interval pattern + */ + void setIntervalPattern(UCalendarDateFields field, + const UnicodeString& intervalPattern, + UBool laterDateFirst); + + + /** + * Set pattern information. + * + * @param field calendar field + * @param firstPart the first part in interval pattern + * @param secondPart the second part in interval pattern + * @param laterDateFirst whether the first date in intervalPattern + * is earlier date or later date + */ + void setPatternInfo(UCalendarDateFields field, + const UnicodeString* firstPart, + const UnicodeString* secondPart, + UBool laterDateFirst); + + /** + * Format 2 Calendars to produce a string. + * Implementation of the similar public format function. + * Must be called with gFormatterMutex already locked. + * + * Note: "fromCalendar" and "toCalendar" are not const, + * since calendar is not const in SimpleDateFormat::format(Calendar&), + * + * @param fromCalendar calendar set to the from date in date interval + * to be formatted into date interval string + * @param toCalendar calendar set to the to date in date interval + * to be formatted into date interval string + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param firstIndex 0 if the first output date is fromCalendar; + * 1 if it corresponds to toCalendar; + * -1 if there is only one date printed. + * @param fphandler Handler for field position information. + * The fields will be from the UDateFormatField enum. + * @param status Output param filled with success/failure status. + * Caller needs to make sure it is SUCCESS + * at the function entrance + * @return Reference to 'appendTo' parameter. + * @internal (private) + */ + UnicodeString& formatImpl(Calendar& fromCalendar, + Calendar& toCalendar, + UnicodeString& appendTo, + int8_t& firstIndex, + FieldPositionHandler& fphandler, + UErrorCode& status) const ; + + /** Version of formatImpl for DateInterval. */ + UnicodeString& formatIntervalImpl(const DateInterval& dtInterval, + UnicodeString& appendTo, + int8_t& firstIndex, + FieldPositionHandler& fphandler, + UErrorCode& status) const; + + + // from calendar field to pattern letter + static const char16_t fgCalendarFieldToPatternLetter[]; + + + /** + * The interval patterns for this locale. + */ + DateIntervalInfo* fInfo; + + /** + * The DateFormat object used to format single pattern + */ + SimpleDateFormat* fDateFormat; + + /** + * The 2 calendars with the from and to date. + * could re-use the calendar in fDateFormat, + * but keeping 2 calendars make it clear and clean. + */ + Calendar* fFromCalendar; + Calendar* fToCalendar; + + Locale fLocale; + + /** + * Following are interval information relevant (locale) to this formatter. + */ + UnicodeString fSkeleton; + PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX]; + + /** + * Patterns for fallback formatting. + */ + UnicodeString* fDatePattern; + UnicodeString* fTimePattern; + UnicodeString* fDateTimeFormat; + + /** + * Other formatting information + */ + UDisplayContext fCapitalizationContext; +}; + +inline bool +DateIntervalFormat::operator!=(const Format& other) const { + return !operator==(other); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _DTITVFMT_H__ +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvinf.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvinf.h new file mode 100644 index 0000000000000000000000000000000000000000..5b9a45351c2630ad99a71691c2d70fa8886b8b02 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtitvinf.h @@ -0,0 +1,524 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2008-2016, International Business Machines Corporation and + * others. All Rights Reserved. + ******************************************************************************* + * + * File DTITVINF.H + * + ******************************************************************************* + */ + +#ifndef __DTITVINF_H__ +#define __DTITVINF_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Date/Time interval patterns for formatting date/time interval + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/udat.h" +#include "unicode/locid.h" +#include "unicode/ucal.h" +#include "unicode/dtptngen.h" + +U_NAMESPACE_BEGIN + +/** + * DateIntervalInfo is a public class for encapsulating localizable + * date time interval patterns. It is used by DateIntervalFormat. + * + *

+ * For most users, ordinary use of DateIntervalFormat does not need to create + * DateIntervalInfo object directly. + * DateIntervalFormat will take care of it when creating a date interval + * formatter when user pass in skeleton and locale. + * + *

+ * For power users, who want to create their own date interval patterns, + * or want to re-set date interval patterns, they could do so by + * directly creating DateIntervalInfo and manipulating it. + * + *

+ * Logically, the interval patterns are mappings + * from (skeleton, the_largest_different_calendar_field) + * to (date_interval_pattern). + * + *

+ * A skeleton + *

    + *
  1. + * only keeps the field pattern letter and ignores all other parts + * in a pattern, such as space, punctuations, and string literals. + *
  2. + * hides the order of fields. + *
  3. + * might hide a field's pattern letter length. + * + * For those non-digit calendar fields, the pattern letter length is + * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, + * and the field's pattern letter length is honored. + * + * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, + * the field pattern length is ignored and the best match, which is defined + * in date time patterns, will be returned without honor the field pattern + * letter length in skeleton. + *
+ * + *

+ * The calendar fields we support for interval formatting are: + * year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute. + * Those calendar fields can be defined in the following order: + * year > month > date > am-pm > hour > minute + * + * The largest different calendar fields between 2 calendars is the + * first different calendar field in above order. + * + * For example: the largest different calendar fields between "Jan 10, 2007" + * and "Feb 20, 2008" is year. + * + *

+ * There is a set of pre-defined static skeleton strings. + * There are pre-defined interval patterns for those pre-defined skeletons + * in locales' resource files. + * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd", + * in en_US, if the largest different calendar field between date1 and date2 + * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", + * such as "Jan 10, 2007 - Jan 10, 2008". + * If the largest different calendar field between date1 and date2 is "month", + * the date interval pattern is "MMM d - MMM d, yyyy", + * such as "Jan 10 - Feb 10, 2007". + * If the largest different calendar field between date1 and date2 is "day", + * the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007". + * + * For date skeleton, the interval patterns when year, or month, or date is + * different are defined in resource files. + * For time skeleton, the interval patterns when am/pm, or hour, or minute is + * different are defined in resource files. + * + * + *

+ * There are 2 dates in interval pattern. For most locales, the first date + * in an interval pattern is the earlier date. There might be a locale in which + * the first date in an interval pattern is the later date. + * We use fallback format for the default order for the locale. + * For example, if the fallback format is "{0} - {1}", it means + * the first date in the interval pattern for this locale is earlier date. + * If the fallback format is "{1} - {0}", it means the first date is the + * later date. + * For a particular interval pattern, the default order can be overridden + * by prefixing "latestFirst:" or "earliestFirst:" to the interval pattern. + * For example, if the fallback format is "{0}-{1}", + * but for skeleton "yMMMd", the interval pattern when day is different is + * "latestFirst:d-d MMM yy", it means by default, the first date in interval + * pattern is the earlier date. But for skeleton "yMMMd", when day is different, + * the first date in "d-d MMM yy" is the later date. + * + *

+ * The recommended way to create a DateIntervalFormat object is to pass in + * the locale. + * By using a Locale parameter, the DateIntervalFormat object is + * initialized with the pre-defined interval patterns for a given or + * default locale. + *

+ * Users can also create DateIntervalFormat object + * by supplying their own interval patterns. + * It provides flexibility for power users. + * + *

+ * After a DateIntervalInfo object is created, clients may modify + * the interval patterns using setIntervalPattern function as so desired. + * Currently, users can only set interval patterns when the following + * calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, + * DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND. + * Interval patterns when other calendar fields are different is not supported. + *

+ * DateIntervalInfo objects are cloneable. + * When clients obtain a DateIntervalInfo object, + * they can feel free to modify it as necessary. + *

+ * DateIntervalInfo are not expected to be subclassed. + * Data for a calendar is loaded out of resource bundles. + * Through ICU 4.4, date interval patterns are only supported in the Gregorian + * calendar; non-Gregorian calendars are supported from ICU 4.4.1. + * @stable ICU 4.0 +**/ +class U_I18N_API DateIntervalInfo final : public UObject { +public: + /** + * Default constructor. + * It does not initialize any interval patterns except + * that it initialize default fall-back pattern as "{0} - {1}", + * which can be reset by setFallbackIntervalPattern(). + * It should be followed by setFallbackIntervalPattern() and + * setIntervalPattern(), + * and is recommended to be used only for power users who + * wants to create their own interval patterns and use them to create + * date interval formatter. + * @param status output param set to success/failure code on exit + * @internal ICU 4.0 + */ + DateIntervalInfo(UErrorCode& status); + + + /** + * Construct DateIntervalInfo for the given locale, + * @param locale the interval patterns are loaded from the appropriate calendar + * data (specified calendar or default calendar) in this locale. + * @param status output param set to success/failure code on exit + * @stable ICU 4.0 + */ + DateIntervalInfo(const Locale& locale, UErrorCode& status); + + + /** + * Copy constructor. + * @stable ICU 4.0 + */ + DateIntervalInfo(const DateIntervalInfo&); + + /** + * Assignment operator + * @stable ICU 4.0 + */ + DateIntervalInfo& operator=(const DateIntervalInfo&); + + /** + * Clone this object polymorphically. + * The caller owns the result and should delete it when done. + * @return a copy of the object + * @stable ICU 4.0 + */ + virtual DateIntervalInfo* clone() const; + + /** + * Destructor. + * It is virtual to be safe, but it is not designed to be subclassed. + * @stable ICU 4.0 + */ + virtual ~DateIntervalInfo(); + + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the DateIntervalInfo object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 4.0 + */ + virtual bool operator==(const DateIntervalInfo& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the DateIntervalInfo object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 4.0 + */ + bool operator!=(const DateIntervalInfo& other) const; + + + + /** + * Provides a way for client to build interval patterns. + * User could construct DateIntervalInfo by providing a list of skeletons + * and their patterns. + *

+ * For example: + *

+     * UErrorCode status = U_ZERO_ERROR;
+     * DateIntervalInfo dIntervalInfo = new DateIntervalInfo();
+     * dIntervalInfo->setFallbackIntervalPattern("{0} ~ {1}");
+     * dIntervalInfo->setIntervalPattern("yMd", UCAL_YEAR, "'from' yyyy-M-d 'to' yyyy-M-d", status);
+     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_MONTH, "'from' yyyy MMM d 'to' MMM d", status);
+     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_DAY, "yyyy MMM d-d", status, status);
+     * 
+ * + * Restriction: + * Currently, users can only set interval patterns when the following + * calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, + * DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND and MILLISECOND. + * Interval patterns when other calendar fields are different are + * not supported. + * + * @param skeleton the skeleton on which interval pattern based + * @param lrgDiffCalUnit the largest different calendar unit. + * @param intervalPattern the interval pattern on the largest different + * calendar unit. + * For example, if lrgDiffCalUnit is + * "year", the interval pattern for en_US when year + * is different could be "'from' yyyy 'to' yyyy". + * @param status output param set to success/failure code on exit + * @stable ICU 4.0 + */ + void setIntervalPattern(const UnicodeString& skeleton, + UCalendarDateFields lrgDiffCalUnit, + const UnicodeString& intervalPattern, + UErrorCode& status); + + /** + * Get the interval pattern given skeleton and + * the largest different calendar field. + * @param skeleton the skeleton + * @param field the largest different calendar field + * @param result output param to receive the pattern + * @param status output param set to success/failure code on exit + * @return a reference to 'result' + * @stable ICU 4.0 + */ + UnicodeString& getIntervalPattern(const UnicodeString& skeleton, + UCalendarDateFields field, + UnicodeString& result, + UErrorCode& status) const; + + /** + * Get the fallback interval pattern. + * @param result output param to receive the pattern + * @return a reference to 'result' + * @stable ICU 4.0 + */ + UnicodeString& getFallbackIntervalPattern(UnicodeString& result) const; + + + /** + * Re-set the fallback interval pattern. + * + * In construction, default fallback pattern is set as "{0} - {1}". + * And constructor taking locale as parameter will set the + * fallback pattern as what defined in the locale resource file. + * + * This method provides a way for user to replace the fallback pattern. + * + * @param fallbackPattern fall-back interval pattern. + * @param status output param set to success/failure code on exit + * @stable ICU 4.0 + */ + void setFallbackIntervalPattern(const UnicodeString& fallbackPattern, + UErrorCode& status); + + + /** Get default order -- whether the first date in pattern is later date + or not. + * return default date ordering in interval pattern. true if the first date + * in pattern is later date, false otherwise. + * @stable ICU 4.0 + */ + UBool getDefaultOrder() const; + + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 4.0 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 4.0 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + +private: + /** + * DateIntervalFormat will need access to + * getBestSkeleton(), parseSkeleton(), enum IntervalPatternIndex, + * and calendarFieldToPatternIndex(). + * + * Instead of making above public, + * make DateIntervalFormat a friend of DateIntervalInfo. + */ + friend class DateIntervalFormat; + + /** + * Internal struct used to load resource bundle data. + */ + struct U_HIDDEN DateIntervalSink; + + /** + * Following is for saving the interval patterns. + * We only support interval patterns on + * ERA, YEAR, MONTH, DAY, AM_PM, HOUR, MINUTE, SECOND and MILLISECOND. + */ + enum IntervalPatternIndex + { + kIPI_ERA, + kIPI_YEAR, + kIPI_MONTH, + kIPI_DATE, + kIPI_AM_PM, + kIPI_HOUR, + kIPI_MINUTE, + kIPI_SECOND, + kIPI_MILLISECOND, + kIPI_MAX_INDEX + }; +public: +#ifndef U_HIDE_INTERNAL_API + /** + * Max index for stored interval patterns + * @internal ICU 4.4 + */ + enum { + kMaxIntervalPatternIndex = kIPI_MAX_INDEX + }; +#endif /* U_HIDE_INTERNAL_API */ +private: + + + /** + * Initialize the DateIntervalInfo from locale + * @param locale the given locale. + * @param status output param set to success/failure code on exit + */ + void initializeData(const Locale& locale, UErrorCode& status); + + + /* Set Interval pattern. + * + * It sets interval pattern into the hash map. + * + * @param skeleton skeleton on which the interval pattern based + * @param lrgDiffCalUnit the largest different calendar unit. + * @param intervalPattern the interval pattern on the largest different + * calendar unit. + * @param status output param set to success/failure code on exit + */ + void setIntervalPatternInternally(const UnicodeString& skeleton, + UCalendarDateFields lrgDiffCalUnit, + const UnicodeString& intervalPattern, + UErrorCode& status); + + + /**given an input skeleton, get the best match skeleton + * which has pre-defined interval pattern in resource file. + * Also return the difference between the input skeleton + * and the best match skeleton. + * + * TODO (xji): set field weight or + * isolate the functionality in DateTimePatternGenerator + * @param skeleton input skeleton + * @param bestMatchDistanceInfo the difference between input skeleton + * and best match skeleton. + * 0, if there is exact match for input skeleton + * 1, if there is only field width difference between + * the best match and the input skeleton + * 2, the only field difference is 'v' and 'z' + * -1, if there is calendar field difference between + * the best match and the input skeleton + * @return best match skeleton + */ + const UnicodeString* getBestSkeleton(const UnicodeString& skeleton, + int8_t& bestMatchDistanceInfo) const; + + + /** + * Parse skeleton, save each field's width. + * It is used for looking for best match skeleton, + * and adjust pattern field width. + * @param skeleton skeleton to be parsed + * @param skeletonFieldWidth parsed skeleton field width + */ + static void U_EXPORT2 parseSkeleton(const UnicodeString& skeleton, + int32_t* skeletonFieldWidth); + + + /** + * Check whether one field width is numeric while the other is string. + * + * TODO (xji): make it general + * + * @param fieldWidth one field width + * @param anotherFieldWidth another field width + * @param patternLetter pattern letter char + * @return true if one field width is numeric and the other is string, + * false otherwise. + */ + static UBool U_EXPORT2 stringNumeric(int32_t fieldWidth, + int32_t anotherFieldWidth, + char patternLetter); + + + /** + * Convert calendar field to the interval pattern index in + * hash table. + * + * Since we only support the following calendar fields: + * ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_WEEK, + * AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND. + * We reserve only 4 interval patterns for a skeleton. + * + * @param field calendar field + * @param status output param set to success/failure code on exit + * @return interval pattern index in hash table + */ + static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex( + UCalendarDateFields field, + UErrorCode& status); + + + /** + * delete hash table (of type fIntervalPatterns). + * + * @param hTable hash table to be deleted + */ + void deleteHash(Hashtable* hTable); + + + /** + * initialize hash table (of type fIntervalPatterns). + * + * @param status output param set to success/failure code on exit + * @return hash table initialized + */ + Hashtable* initHash(UErrorCode& status); + + + + /** + * copy hash table (of type fIntervalPatterns). + * + * @param source the source to copy from + * @param target the target to copy to + * @param status output param set to success/failure code on exit + */ + void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); + + + // data members + // fallback interval pattern + UnicodeString fFallbackIntervalPattern; + // default order + UBool fFirstDateInPtnIsLaterDate; + + // HashMap + // HashMap( skeleton, pattern[largest_different_field] ) + Hashtable* fIntervalPatterns; + +};// end class DateIntervalInfo + + +inline bool +DateIntervalInfo::operator!=(const DateIntervalInfo& other) const { + return !operator==(other); +} + + +U_NAMESPACE_END + +#endif + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtptngen.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtptngen.h new file mode 100644 index 0000000000000000000000000000000000000000..8c374a3094376c3fb307df597c5e3c97ed7de920 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtptngen.h @@ -0,0 +1,668 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2016, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File DTPTNGEN.H +* +******************************************************************************* +*/ + +#ifndef __DTPTNGEN_H__ +#define __DTPTNGEN_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/datefmt.h" +#include "unicode/locid.h" +#include "unicode/udat.h" +#include "unicode/udatpg.h" +#include "unicode/unistr.h" + +U_NAMESPACE_BEGIN + +/** + * \file + * \brief C++ API: Date/Time Pattern Generator + */ + + +class CharString; +class Hashtable; +class FormatParser; +class DateTimeMatcher; +class DistanceInfo; +class PatternMap; +class PtnSkeleton; +class SharedDateTimePatternGenerator; + +/** + * This class provides flexible generation of date format patterns, like "yy-MM-dd". + * The user can build up the generator by adding successive patterns. Once that + * is done, a query can be made using a "skeleton", which is a pattern which just + * includes the desired fields and lengths. The generator will return the "best fit" + * pattern corresponding to that skeleton. + *

The main method people will use is getBestPattern(String skeleton), + * since normally this class is pre-built with data from a particular locale. + * However, generators can be built directly from other data as well. + *

Issue: may be useful to also have a function that returns the list of + * fields in a pattern, in order, since we have that internally. + * That would be useful for getting the UI order of field elements. + * @stable ICU 3.8 +**/ +class U_I18N_API DateTimePatternGenerator : public UObject { +public: + /** + * Construct a flexible generator according to default locale. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createInstance(UErrorCode& status); + + /** + * Construct a flexible generator according to data for a given locale. + * @param uLocale + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createInstance(const Locale& uLocale, UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + + /** + * For ICU use only. Skips loading the standard date/time patterns (which is done via DateFormat). + * + * @internal + */ + static DateTimePatternGenerator* U_EXPORT2 createInstanceNoStdPat(const Locale& uLocale, UErrorCode& status); + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Create an empty generator, to be constructed with addPattern(...) etc. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @stable ICU 3.8 + */ + static DateTimePatternGenerator* U_EXPORT2 createEmptyInstance(UErrorCode& status); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~DateTimePatternGenerator(); + + /** + * Clone DateTimePatternGenerator object. Clients are responsible for + * deleting the DateTimePatternGenerator object cloned. + * @stable ICU 3.8 + */ + DateTimePatternGenerator* clone() const; + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the DateTimePatternGenerator object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 3.8 + */ + bool operator==(const DateTimePatternGenerator& other) const; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the DateTimePatternGenerator object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 3.8 + */ + bool operator!=(const DateTimePatternGenerator& other) const; + + /** + * Utility to return a unique skeleton from a given pattern. For example, + * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return skeleton such as "MMMdd" + * @stable ICU 56 + */ + static UnicodeString staticGetSkeleton(const UnicodeString& pattern, UErrorCode& status); + + /** + * Utility to return a unique skeleton from a given pattern. For example, + * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". + * getSkeleton() works exactly like staticGetSkeleton(). + * Use staticGetSkeleton() instead of getSkeleton(). + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return skeleton such as "MMMdd" + * @stable ICU 3.8 + */ + UnicodeString getSkeleton(const UnicodeString& pattern, UErrorCode& status); /* { + The function is commented out because it is a stable API calling a draft API. + After staticGetSkeleton becomes stable, staticGetSkeleton can be used and + these comments and the definition of getSkeleton in dtptngen.cpp should be removed. + return staticGetSkeleton(pattern, status); + }*/ + + /** + * Utility to return a unique base skeleton from a given pattern. This is + * the same as the skeleton, except that differences in length are minimized + * so as to only preserve the difference between string and numeric form. So + * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" + * (notice the single d). + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return base skeleton, such as "MMMd" + * @stable ICU 56 + */ + static UnicodeString staticGetBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); + + /** + * Utility to return a unique base skeleton from a given pattern. This is + * the same as the skeleton, except that differences in length are minimized + * so as to only preserve the difference between string and numeric form. So + * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" + * (notice the single d). + * getBaseSkeleton() works exactly like staticGetBaseSkeleton(). + * Use staticGetBaseSkeleton() instead of getBaseSkeleton(). + * + * @param pattern Input pattern, such as "dd/MMM" + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return base skeleton, such as "MMMd" + * @stable ICU 3.8 + */ + UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); /* { + The function is commented out because it is a stable API calling a draft API. + After staticGetBaseSkeleton becomes stable, staticGetBaseSkeleton can be used and + these comments and the definition of getBaseSkeleton in dtptngen.cpp should be removed. + return staticGetBaseSkeleton(pattern, status); + }*/ + + /** + * Adds a pattern to the generator. If the pattern has the same skeleton as + * an existing pattern, and the override parameter is set, then the previous + * value is overridden. Otherwise, the previous value is retained. In either + * case, the conflicting status is set and previous vale is stored in + * conflicting pattern. + *

+ * Note that single-field patterns (like "MMM") are automatically added, and + * don't need to be added explicitly! + * + * @param pattern Input pattern, such as "dd/MMM" + * @param override When existing values are to be overridden use true, + * otherwise use false. + * @param conflictingPattern Previous pattern with the same skeleton. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return conflicting status. The value could be UDATPG_NO_CONFLICT, + * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. + * @stable ICU 3.8 + *

+ *

Sample code

+ * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 + * \snippet samples/dtptngsample/dtptngsample.cpp addPatternExample + *

+ */ + UDateTimePatternConflict addPattern(const UnicodeString& pattern, + UBool override, + UnicodeString& conflictingPattern, + UErrorCode& status); + + /** + * An AppendItem format is a pattern used to append a field if there is no + * good match. For example, suppose that the input skeleton is "GyyyyMMMd", + * and there is no matching pattern internally, but there is a pattern + * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the + * G. The way these two are conjoined is by using the AppendItemFormat for G + * (era). So if that value is, say "{0}, {1}" then the final resulting + * pattern is "d-MM-yyyy, G". + *

+ * There are actually three available variables: {0} is the pattern so far, + * {1} is the element we are adding, and {2} is the name of the element. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param field such as UDATPG_ERA_FIELD. + * @param value pattern, such as "{0}, {1}" + * @stable ICU 3.8 + */ + void setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value); + + /** + * Getter corresponding to setAppendItemFormat. Values below 0 or at or + * above UDATPG_FIELD_COUNT are illegal arguments. + * + * @param field such as UDATPG_ERA_FIELD. + * @return append pattern for field + * @stable ICU 3.8 + */ + const UnicodeString& getAppendItemFormat(UDateTimePatternField field) const; + + /** + * Sets the names of field, eg "era" in English for ERA. These are only + * used if the corresponding AppendItemFormat is used, and if it contains a + * {2} variable. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param field such as UDATPG_ERA_FIELD. + * @param value name of the field + * @stable ICU 3.8 + */ + void setAppendItemName(UDateTimePatternField field, const UnicodeString& value); + + /** + * Getter corresponding to setAppendItemNames. Values below 0 or at or above + * UDATPG_FIELD_COUNT are illegal arguments. Note: The more general method + * for getting date/time field display names is getFieldDisplayName. + * + * @param field such as UDATPG_ERA_FIELD. + * @return name for field + * @see getFieldDisplayName + * @stable ICU 3.8 + */ + const UnicodeString& getAppendItemName(UDateTimePatternField field) const; + + /** + * The general interface to get a display name for a particular date/time field, + * in one of several possible display widths. + * + * @param field The desired UDateTimePatternField, such as UDATPG_ERA_FIELD. + * @param width The desired UDateTimePGDisplayWidth, such as UDATPG_ABBREVIATED. + * @return The display name for field + * @stable ICU 61 + */ + UnicodeString getFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width) const; + + /** + * The DateTimeFormat is a message format pattern used to compose date and + * time patterns. The default pattern in the root locale is "{1} {0}", where + * {1} will be replaced by the date pattern and {0} will be replaced by the + * time pattern; however, other locales may specify patterns such as + * "{1}, {0}" or "{1} 'at' {0}", etc. + *

+ * This is used when the input skeleton contains both date and time fields, + * but there is not a close match among the added patterns. For example, + * suppose that this object was created by adding "dd-MMM" and "hh:mm", and + * its datetimeFormat is the default "{1} {0}". Then if the input skeleton + * is "MMMdhmm", there is not an exact match, so the input skeleton is + * broken up into two components "MMMd" and "hmm". There are close matches + * for those two skeletons, so the result is put together with this pattern, + * resulting in "d-MMM h:mm". + * + * There are four DateTimeFormats in a DateTimePatternGenerator object, + * corresponding to date styles UDAT_FULL..UDAT_SHORT. This method sets + * all of them to the specified pattern. To set them individually, see + * setDateTimeFormat(UDateFormatStyle style, ...). + * + * @param dateTimeFormat + * message format pattern, here {1} will be replaced by the date + * pattern and {0} will be replaced by the time pattern. + * @stable ICU 3.8 + */ + void setDateTimeFormat(const UnicodeString& dateTimeFormat); + + /** + * Getter corresponding to setDateTimeFormat. + * + * There are four DateTimeFormats in a DateTimePatternGenerator object, + * corresponding to date styles UDAT_FULL..UDAT_SHORT. This method gets + * the style for UDAT_MEDIUM (the default). To get them individually, see + * getDateTimeFormat(UDateFormatStyle style). + * + * @return DateTimeFormat. + * @stable ICU 3.8 + */ + const UnicodeString& getDateTimeFormat() const; + +#if !UCONFIG_NO_FORMATTING + /** + * dateTimeFormats are message patterns used to compose combinations of date + * and time patterns. There are four length styles, corresponding to the + * inferred style of the date pattern; these are UDateFormatStyle values: + * - UDAT_FULL (for date pattern with weekday and long month), else + * - UDAT_LONG (for a date pattern with long month), else + * - UDAT_MEDIUM (for a date pattern with abbreviated month), else + * - UDAT_SHORT (for any other date pattern). + * For details on dateTimeFormats, see + * https://www.unicode.org/reports/tr35/tr35-dates.html#dateTimeFormats. + * The default pattern in the root locale for all styles is "{1} {0}". + * + * @param style + * one of DateFormat.FULL..DateFormat.SHORT. Error if out of range. + * @param dateTimeFormat + * the new dateTimeFormat to set for the the specified style + * @param status + * in/out parameter; if no failure status is already set, + * it will be set according to result of the function (e.g. + * U_ILLEGAL_ARGUMENT_ERROR for style out of range). + * @stable ICU 71 + */ + void setDateTimeFormat(UDateFormatStyle style, const UnicodeString& dateTimeFormat, + UErrorCode& status); + + /** + * Getter corresponding to setDateTimeFormat. + * + * @param style + * one of UDAT_FULL..UDAT_SHORT. Error if out of range. + * @param status + * in/out parameter; if no failure status is already set, + * it will be set according to result of the function (e.g. + * U_ILLEGAL_ARGUMENT_ERROR for style out of range). + * @return + * the current dateTimeFormat for the the specified style, or + * empty string in case of error. The UnicodeString reference, + * or the contents of the string, may no longer be valid if + * setDateTimeFormat is called, or the DateTimePatternGenerator + * object is deleted. + * @stable ICU 71 + */ + const UnicodeString& getDateTimeFormat(UDateFormatStyle style, + UErrorCode& status) const; +#endif /* #if !UCONFIG_NO_FORMATTING */ + + /** + * Return the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return bestPattern + * The best pattern found from the given skeleton. + * @stable ICU 3.8 + *

+ *

Sample code

+ * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 + * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample + *

+ */ + UnicodeString getBestPattern(const UnicodeString& skeleton, UErrorCode& status); + + + /** + * Return the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param options + * Options for forcing the length of specified fields in the + * returned pattern to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param status + * Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return bestPattern + * The best pattern found from the given skeleton. + * @stable ICU 4.4 + */ + UnicodeString getBestPattern(const UnicodeString& skeleton, + UDateTimePatternMatchOptions options, + UErrorCode& status); + + + /** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * @param pattern Input pattern + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return pattern adjusted to match the skeleton fields widths and subtypes. + * @stable ICU 3.8 + *

+ *

Sample code

+ * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 + * \snippet samples/dtptngsample/dtptngsample.cpp replaceFieldTypesExample + *

+ */ + UnicodeString replaceFieldTypes(const UnicodeString& pattern, + const UnicodeString& skeleton, + UErrorCode& status); + + /** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * @param pattern Input pattern + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param options + * Options controlling whether the length of specified fields in the + * pattern are adjusted to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param status + * Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return pattern adjusted to match the skeleton fields widths and subtypes. + * @stable ICU 4.4 + */ + UnicodeString replaceFieldTypes(const UnicodeString& pattern, + const UnicodeString& skeleton, + UDateTimePatternMatchOptions options, + UErrorCode& status); + + /** + * Return a list of all the skeletons (in canonical form) from this class. + * + * Call getPatternForSkeleton() to get the corresponding pattern. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return StringEnumeration with the skeletons. + * The caller must delete the object. + * @stable ICU 3.8 + */ + StringEnumeration* getSkeletons(UErrorCode& status) const; + + /** + * Get the pattern corresponding to a given skeleton. + * @param skeleton + * @return pattern corresponding to a given skeleton. + * @stable ICU 3.8 + */ + const UnicodeString& getPatternForSkeleton(const UnicodeString& skeleton) const; + + /** + * Return a list of all the base skeletons (in canonical form) from this class. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return a StringEnumeration with the base skeletons. + * The caller must delete the object. + * @stable ICU 3.8 + */ + StringEnumeration* getBaseSkeletons(UErrorCode& status) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Return a list of redundant patterns are those which if removed, make no + * difference in the resulting getBestPattern values. This method returns a + * list of them, to help check the consistency of the patterns used to build + * this generator. + * + * @param status Output param set to success/failure code on exit, + * which must not indicate a failure before the function call. + * @return a StringEnumeration with the redundant pattern. + * The caller must delete the object. + * @internal ICU 3.8 + */ + StringEnumeration* getRedundants(UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * The decimal value is used in formatting fractions of seconds. If the + * skeleton contains fractional seconds, then this is used with the + * fractional seconds. For example, suppose that the input pattern is + * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and + * the decimal string is ",". Then the resulting pattern is modified to be + * "H:mm:ss,SSSS" + * + * @param decimal + * @stable ICU 3.8 + */ + void setDecimal(const UnicodeString& decimal); + + /** + * Getter corresponding to setDecimal. + * @return UnicodeString corresponding to the decimal point + * @stable ICU 3.8 + */ + const UnicodeString& getDecimal() const; + +#if !UCONFIG_NO_FORMATTING + + /** + * Get the default hour cycle for a locale. Uses the locale that the + * DateTimePatternGenerator was initially created with. + * + * Cannot be used on an empty DateTimePatternGenerator instance. + * + * @param status Output param set to success/failure code on exit, which + * which must not indicate a failure before the function call. + * Set to U_UNSUPPORTED_ERROR if used on an empty instance. + * @return the default hour cycle. + * @stable ICU 67 + */ + UDateFormatHourCycle getDefaultHourCycle(UErrorCode& status) const; + +#endif /* #if !UCONFIG_NO_FORMATTING */ + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +private: + /** + * Constructor. + */ + DateTimePatternGenerator(UErrorCode & status); + + /** + * Constructor. + */ + DateTimePatternGenerator(const Locale& locale, UErrorCode & status, UBool skipStdPatterns = false); + + /** + * Copy constructor. + * @param other DateTimePatternGenerator to copy + */ + DateTimePatternGenerator(const DateTimePatternGenerator& other); + + /** + * Default assignment operator. + * @param other DateTimePatternGenerator to copy + */ + DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other); + + static const int32_t UDATPG_WIDTH_COUNT = UDATPG_NARROW + 1; + + Locale pLocale; // pattern locale + FormatParser *fp; + DateTimeMatcher* dtMatcher; + DistanceInfo *distanceInfo; + PatternMap *patternMap; + UnicodeString appendItemFormats[UDATPG_FIELD_COUNT]; + UnicodeString fieldDisplayNames[UDATPG_FIELD_COUNT][UDATPG_WIDTH_COUNT]; + UnicodeString dateTimeFormat[4]; + UnicodeString decimal; + DateTimeMatcher *skipMatcher; + Hashtable *fAvailableFormatKeyHash; + UnicodeString emptyString; + char16_t fDefaultHourFormatChar; + + int32_t fAllowedHourFormats[7]; // Actually an array of AllowedHourFormat enum type, ending with UNKNOWN. + + // Internal error code used for recording/reporting errors that occur during methods that do not + // have a UErrorCode parameter. For example: the Copy Constructor, or the ::clone() method. + // When this is set to an error the object is in an invalid state. + UErrorCode internalErrorCode; + + /* internal flags masks for adjustFieldTypes etc. */ + enum { + kDTPGNoFlags = 0, + kDTPGFixFractionalSeconds = 1, + kDTPGSkeletonUsesCapJ = 2 + // with #13183, no longer need flags for b, B + }; + + void initData(const Locale &locale, UErrorCode &status, UBool skipStdPatterns = false); + void addCanonicalItems(UErrorCode &status); + void addICUPatterns(const Locale& locale, UErrorCode& status); + void hackTimes(const UnicodeString& hackPattern, UErrorCode& status); + void getCalendarTypeToUse(const Locale& locale, CharString& destination, UErrorCode& err); + void consumeShortTimePattern(const UnicodeString& shortTimePattern, UErrorCode& status); + void addCLDRData(const Locale& locale, UErrorCode& status); + UDateTimePatternConflict addPatternWithSkeleton(const UnicodeString& pattern, const UnicodeString * skeletonToUse, UBool override, UnicodeString& conflictingPattern, UErrorCode& status); + void initHashtable(UErrorCode& status); + void setDateTimeFromCalendar(const Locale& locale, UErrorCode& status); + void setDecimalSymbols(const Locale& locale, UErrorCode& status); + UDateTimePatternField getAppendFormatNumber(const char* field) const; + // Note for the next 3: UDateTimePGDisplayWidth is now stable ICU 61 + UDateTimePatternField getFieldAndWidthIndices(const char* key, UDateTimePGDisplayWidth* widthP) const; + void setFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width, const UnicodeString& value); + UnicodeString& getMutableFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width); + void getAppendName(UDateTimePatternField field, UnicodeString& value); + UnicodeString mapSkeletonMetacharacters(const UnicodeString& patternForm, int32_t* flags, UErrorCode& status); + const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, UErrorCode& status, const PtnSkeleton** specifiedSkeletonPtr = 0); + UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, int32_t flags, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); + UnicodeString getBestAppending(int32_t missingFields, int32_t flags, UErrorCode& status, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); + int32_t getTopBitNumber(int32_t foundMask) const; + void setAvailableFormat(const UnicodeString &key, UErrorCode& status); + UBool isAvailableFormatSet(const UnicodeString &key) const; + void copyHashtable(Hashtable *other, UErrorCode &status); + UBool isCanonicalItem(const UnicodeString& item) const; + static void U_CALLCONV loadAllowedHourFormatsData(UErrorCode &status); + void getAllowedHourFormats(const Locale &locale, UErrorCode &status); + + struct U_HIDDEN AppendItemFormatsSink; + struct U_HIDDEN AppendItemNamesSink; + struct U_HIDDEN AvailableFormatsSink; +} ;// end class DateTimePatternGenerator + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtrule.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtrule.h new file mode 100644 index 0000000000000000000000000000000000000000..19e94bc981c81773dc573dd13760cfda393bedcf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/dtrule.h @@ -0,0 +1,256 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2008, International Business Machines Corporation and * +* others. All Rights Reserved. * +******************************************************************************* +*/ +#ifndef DTRULE_H +#define DTRULE_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Rule for specifying date and time in an year + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN +/** + * DateTimeRule is a class representing a time in a year by + * a rule specified by month, day of month, day of week and + * time in the day. + * + * @stable ICU 3.8 + */ +class U_I18N_API DateTimeRule : public UObject { +public: + + /** + * Date rule type constants. + * @stable ICU 3.8 + */ + enum DateRuleType { + DOM = 0, /**< The exact day of month, + for example, March 11. */ + DOW, /**< The Nth occurrence of the day of week, + for example, 2nd Sunday in March. */ + DOW_GEQ_DOM, /**< The first occurrence of the day of week on or after the day of monnth, + for example, first Sunday on or after March 8. */ + DOW_LEQ_DOM /**< The last occurrence of the day of week on or before the day of month, + for example, first Sunday on or before March 14. */ + }; + + /** + * Time rule type constants. + * @stable ICU 3.8 + */ + enum TimeRuleType { + WALL_TIME = 0, /**< The local wall clock time */ + STANDARD_TIME, /**< The local standard time */ + UTC_TIME /**< The UTC time */ + }; + + /** + * Constructs a DateTimeRule by the day of month and + * the time rule. The date rule type for an instance created by + * this constructor is DOM. + * + * @param month The rule month, for example, Calendar::JANUARY + * @param dayOfMonth The day of month, 1-based. + * @param millisInDay The milliseconds in the rule date. + * @param timeType The time type, WALL_TIME or STANDARD_TIME + * or UTC_TIME. + * @stable ICU 3.8 + */ + DateTimeRule(int32_t month, int32_t dayOfMonth, + int32_t millisInDay, TimeRuleType timeType); + + /** + * Constructs a DateTimeRule by the day of week and its ordinal + * number and the time rule. The date rule type for an instance created + * by this constructor is DOW. + * + * @param month The rule month, for example, Calendar::JANUARY. + * @param weekInMonth The ordinal number of the day of week. Negative number + * may be used for specifying a rule date counted from the + * end of the rule month. + * @param dayOfWeek The day of week, for example, Calendar::SUNDAY. + * @param millisInDay The milliseconds in the rule date. + * @param timeType The time type, WALL_TIME or STANDARD_TIME + * or UTC_TIME. + * @stable ICU 3.8 + */ + DateTimeRule(int32_t month, int32_t weekInMonth, int32_t dayOfWeek, + int32_t millisInDay, TimeRuleType timeType); + + /** + * Constructs a DateTimeRule by the first/last day of week + * on or after/before the day of month and the time rule. The date rule + * type for an instance created by this constructor is either + * DOM_GEQ_DOM or DOM_LEQ_DOM. + * + * @param month The rule month, for example, Calendar::JANUARY + * @param dayOfMonth The day of month, 1-based. + * @param dayOfWeek The day of week, for example, Calendar::SUNDAY. + * @param after true if the rule date is on or after the day of month. + * @param millisInDay The milliseconds in the rule date. + * @param timeType The time type, WALL_TIME or STANDARD_TIME + * or UTC_TIME. + * @stable ICU 3.8 + */ + DateTimeRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, UBool after, + int32_t millisInDay, TimeRuleType timeType); + + /** + * Copy constructor. + * @param source The DateTimeRule object to be copied. + * @stable ICU 3.8 + */ + DateTimeRule(const DateTimeRule& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + ~DateTimeRule(); + + /** + * Clone this DateTimeRule object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + DateTimeRule* clone() const; + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + DateTimeRule& operator=(const DateTimeRule& right); + + /** + * Return true if the given DateTimeRule objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given DateTimeRule objects are semantically equal. + * @stable ICU 3.8 + */ + bool operator==(const DateTimeRule& that) const; + + /** + * Return true if the given DateTimeRule objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given DateTimeRule objects are semantically unequal. + * @stable ICU 3.8 + */ + bool operator!=(const DateTimeRule& that) const; + + /** + * Gets the date rule type, such as DOM + * @return The date rule type. + * @stable ICU 3.8 + */ + DateRuleType getDateRuleType(void) const; + + /** + * Gets the time rule type + * @return The time rule type, either WALL_TIME or STANDARD_TIME + * or UTC_TIME. + * @stable ICU 3.8 + */ + TimeRuleType getTimeRuleType(void) const; + + /** + * Gets the rule month. + * @return The rule month. + * @stable ICU 3.8 + */ + int32_t getRuleMonth(void) const; + + /** + * Gets the rule day of month. When the date rule type + * is DOW, the value is always 0. + * @return The rule day of month + * @stable ICU 3.8 + */ + int32_t getRuleDayOfMonth(void) const; + + /** + * Gets the rule day of week. When the date rule type + * is DOM, the value is always 0. + * @return The rule day of week. + * @stable ICU 3.8 + */ + int32_t getRuleDayOfWeek(void) const; + + /** + * Gets the ordinal number of the occurrence of the day of week + * in the month. When the date rule type is not DOW, + * the value is always 0. + * @return The rule day of week ordinal number in the month. + * @stable ICU 3.8 + */ + int32_t getRuleWeekInMonth(void) const; + + /** + * Gets the rule time in the rule day. + * @return The time in the rule day in milliseconds. + * @stable ICU 3.8 + */ + int32_t getRuleMillisInDay(void) const; + +private: + int32_t fMonth; + int32_t fDayOfMonth; + int32_t fDayOfWeek; + int32_t fWeekInMonth; + int32_t fMillisInDay; + DateRuleType fDateRuleType; + TimeRuleType fTimeRuleType; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // DTRULE_H +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/edits.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/edits.h new file mode 100644 index 0000000000000000000000000000000000000000..dda9d3ca759cad5e4d96941e6c11de28235faab5 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/edits.h @@ -0,0 +1,531 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// edits.h +// created: 2016dec30 Markus W. Scherer + +#ifndef __EDITS_H__ +#define __EDITS_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: C++ class Edits for low-level string transformations on styled text. + */ + +U_NAMESPACE_BEGIN + +class UnicodeString; + +/** + * Records lengths of string edits but not replacement text. Supports replacements, insertions, deletions + * in linear progression. Does not support moving/reordering of text. + * + * There are two types of edits: change edits and no-change edits. Add edits to + * instances of this class using {@link #addReplace(int32_t, int32_t)} (for change edits) and + * {@link #addUnchanged(int32_t)} (for no-change edits). Change edits are retained with full granularity, + * whereas adjacent no-change edits are always merged together. In no-change edits, there is a one-to-one + * mapping between code points in the source and destination strings. + * + * After all edits have been added, instances of this class should be considered immutable, and an + * {@link Edits::Iterator} can be used for queries. + * + * There are four flavors of Edits::Iterator: + * + *
    + *
  • {@link #getFineIterator()} retains full granularity of change edits. + *
  • {@link #getFineChangesIterator()} retains full granularity of change edits, and when calling + * next() on the iterator, skips over no-change edits (unchanged regions). + *
  • {@link #getCoarseIterator()} treats adjacent change edits as a single edit. (Adjacent no-change + * edits are automatically merged during the construction phase.) + *
  • {@link #getCoarseChangesIterator()} treats adjacent change edits as a single edit, and when + * calling next() on the iterator, skips over no-change edits (unchanged regions). + *
+ * + * For example, consider the string "abcßDeF", which case-folds to "abcssdef". This string has the + * following fine edits: + *
    + *
  • abc ⇨ abc (no-change) + *
  • ß ⇨ ss (change) + *
  • D ⇨ d (change) + *
  • e ⇨ e (no-change) + *
  • F ⇨ f (change) + *
+ * and the following coarse edits (note how adjacent change edits get merged together): + *
    + *
  • abc ⇨ abc (no-change) + *
  • ßD ⇨ ssd (change) + *
  • e ⇨ e (no-change) + *
  • F ⇨ f (change) + *
+ * + * The "fine changes" and "coarse changes" iterators will step through only the change edits when their + * `Edits::Iterator::next()` methods are called. They are identical to the non-change iterators when + * their `Edits::Iterator::findSourceIndex()` or `Edits::Iterator::findDestinationIndex()` + * methods are used to walk through the string. + * + * For examples of how to use this class, see the test `TestCaseMapEditsIteratorDocs` in + * UCharacterCaseTest.java. + * + * An Edits object tracks a separate UErrorCode, but ICU string transformation functions + * (e.g., case mapping functions) merge any such errors into their API's UErrorCode. + * + * @stable ICU 59 + */ +class U_COMMON_API Edits final : public UMemory { +public: + /** + * Constructs an empty object. + * @stable ICU 59 + */ + Edits() : + array(stackArray), capacity(STACK_CAPACITY), length(0), delta(0), numChanges(0), + errorCode_(U_ZERO_ERROR) {} + /** + * Copy constructor. + * @param other source edits + * @stable ICU 60 + */ + Edits(const Edits &other) : + array(stackArray), capacity(STACK_CAPACITY), length(other.length), + delta(other.delta), numChanges(other.numChanges), + errorCode_(other.errorCode_) { + copyArray(other); + } + /** + * Move constructor, might leave src empty. + * This object will have the same contents that the source object had. + * @param src source edits + * @stable ICU 60 + */ + Edits(Edits &&src) noexcept : + array(stackArray), capacity(STACK_CAPACITY), length(src.length), + delta(src.delta), numChanges(src.numChanges), + errorCode_(src.errorCode_) { + moveArray(src); + } + + /** + * Destructor. + * @stable ICU 59 + */ + ~Edits(); + + /** + * Assignment operator. + * @param other source edits + * @return *this + * @stable ICU 60 + */ + Edits &operator=(const Edits &other); + + /** + * Move assignment operator, might leave src empty. + * This object will have the same contents that the source object had. + * The behavior is undefined if *this and src are the same object. + * @param src source edits + * @return *this + * @stable ICU 60 + */ + Edits &operator=(Edits &&src) noexcept; + + /** + * Resets the data but may not release memory. + * @stable ICU 59 + */ + void reset() noexcept; + + /** + * Adds a no-change edit: a record for an unchanged segment of text. + * Normally called from inside ICU string transformation functions, not user code. + * @stable ICU 59 + */ + void addUnchanged(int32_t unchangedLength); + /** + * Adds a change edit: a record for a text replacement/insertion/deletion. + * Normally called from inside ICU string transformation functions, not user code. + * @stable ICU 59 + */ + void addReplace(int32_t oldLength, int32_t newLength); + /** + * Sets the UErrorCode if an error occurred while recording edits. + * Preserves older error codes in the outErrorCode. + * Normally called from inside ICU string transformation functions, not user code. + * @param outErrorCode Set to an error code if it does not contain one already + * and an error occurred while recording edits. + * Otherwise unchanged. + * @return true if U_FAILURE(outErrorCode) + * @stable ICU 59 + */ + UBool copyErrorTo(UErrorCode &outErrorCode) const; + + /** + * How much longer is the new text compared with the old text? + * @return new length minus old length + * @stable ICU 59 + */ + int32_t lengthDelta() const { return delta; } + /** + * @return true if there are any change edits + * @stable ICU 59 + */ + UBool hasChanges() const { return numChanges != 0; } + + /** + * @return the number of change edits + * @stable ICU 60 + */ + int32_t numberOfChanges() const { return numChanges; } + + /** + * Access to the list of edits. + * + * At any moment in time, an instance of this class points to a single edit: a "window" into a span + * of the source string and the corresponding span of the destination string. The source string span + * starts at {@link #sourceIndex()} and runs for {@link #oldLength()} chars; the destination string + * span starts at {@link #destinationIndex()} and runs for {@link #newLength()} chars. + * + * The iterator can be moved between edits using the `next()`, `findSourceIndex(int32_t, UErrorCode &)`, + * and `findDestinationIndex(int32_t, UErrorCode &)` methods. + * Calling any of these methods mutates the iterator to make it point to the corresponding edit. + * + * For more information, see the documentation for {@link Edits}. + * + * @see getCoarseIterator + * @see getFineIterator + * @stable ICU 59 + */ + struct U_COMMON_API Iterator final : public UMemory { + /** + * Default constructor, empty iterator. + * @stable ICU 60 + */ + Iterator() : + array(nullptr), index(0), length(0), + remaining(0), onlyChanges_(false), coarse(false), + dir(0), changed(false), oldLength_(0), newLength_(0), + srcIndex(0), replIndex(0), destIndex(0) {} + /** + * Copy constructor. + * @stable ICU 59 + */ + Iterator(const Iterator &other) = default; + /** + * Assignment operator. + * @stable ICU 59 + */ + Iterator &operator=(const Iterator &other) = default; + + /** + * Advances the iterator to the next edit. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return true if there is another edit + * @stable ICU 59 + */ + UBool next(UErrorCode &errorCode) { return next(onlyChanges_, errorCode); } + + /** + * Moves the iterator to the edit that contains the source index. + * The source index may be found in a no-change edit + * even if normal iteration would skip no-change edits. + * Normal iteration can continue from a found edit. + * + * The iterator state before this search logically does not matter. + * (It may affect the performance of the search.) + * + * The iterator state after this search is undefined + * if the source index is out of bounds for the source string. + * + * @param i source index + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return true if the edit for the source index was found + * @stable ICU 59 + */ + UBool findSourceIndex(int32_t i, UErrorCode &errorCode) { + return findIndex(i, true, errorCode) == 0; + } + + /** + * Moves the iterator to the edit that contains the destination index. + * The destination index may be found in a no-change edit + * even if normal iteration would skip no-change edits. + * Normal iteration can continue from a found edit. + * + * The iterator state before this search logically does not matter. + * (It may affect the performance of the search.) + * + * The iterator state after this search is undefined + * if the source index is out of bounds for the source string. + * + * @param i destination index + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return true if the edit for the destination index was found + * @stable ICU 60 + */ + UBool findDestinationIndex(int32_t i, UErrorCode &errorCode) { + return findIndex(i, false, errorCode) == 0; + } + + /** + * Computes the destination index corresponding to the given source index. + * If the source index is inside a change edit (not at its start), + * then the destination index at the end of that edit is returned, + * since there is no information about index mapping inside a change edit. + * + * (This means that indexes to the start and middle of an edit, + * for example around a grapheme cluster, are mapped to indexes + * encompassing the entire edit. + * The alternative, mapping an interior index to the start, + * would map such an interval to an empty one.) + * + * This operation will usually but not always modify this object. + * The iterator state after this search is undefined. + * + * @param i source index + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return destination index; undefined if i is not 0..string length + * @stable ICU 60 + */ + int32_t destinationIndexFromSourceIndex(int32_t i, UErrorCode &errorCode); + + /** + * Computes the source index corresponding to the given destination index. + * If the destination index is inside a change edit (not at its start), + * then the source index at the end of that edit is returned, + * since there is no information about index mapping inside a change edit. + * + * (This means that indexes to the start and middle of an edit, + * for example around a grapheme cluster, are mapped to indexes + * encompassing the entire edit. + * The alternative, mapping an interior index to the start, + * would map such an interval to an empty one.) + * + * This operation will usually but not always modify this object. + * The iterator state after this search is undefined. + * + * @param i destination index + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return source index; undefined if i is not 0..string length + * @stable ICU 60 + */ + int32_t sourceIndexFromDestinationIndex(int32_t i, UErrorCode &errorCode); + + /** + * Returns whether the edit currently represented by the iterator is a change edit. + * + * @return true if this edit replaces oldLength() units with newLength() different ones. + * false if oldLength units remain unchanged. + * @stable ICU 59 + */ + UBool hasChange() const { return changed; } + + /** + * The length of the current span in the source string, which starts at {@link #sourceIndex}. + * + * @return the number of units in the original string which are replaced or remain unchanged. + * @stable ICU 59 + */ + int32_t oldLength() const { return oldLength_; } + + /** + * The length of the current span in the destination string, which starts at + * {@link #destinationIndex}, or in the replacement string, which starts at + * {@link #replacementIndex}. + * + * @return the number of units in the modified string, if hasChange() is true. + * Same as oldLength if hasChange() is false. + * @stable ICU 59 + */ + int32_t newLength() const { return newLength_; } + + /** + * The start index of the current span in the source string; the span has length + * {@link #oldLength}. + * + * @return the current index into the source string + * @stable ICU 59 + */ + int32_t sourceIndex() const { return srcIndex; } + + /** + * The start index of the current span in the replacement string; the span has length + * {@link #newLength}. Well-defined only if the current edit is a change edit. + * + * The *replacement string* is the concatenation of all substrings of the destination + * string corresponding to change edits. + * + * This method is intended to be used together with operations that write only replacement + * characters (e.g. operations specifying the \ref U_OMIT_UNCHANGED_TEXT option). + * The source string can then be modified in-place. + * + * @return the current index into the replacement-characters-only string, + * not counting unchanged spans + * @stable ICU 59 + */ + int32_t replacementIndex() const { + // TODO: Throw an exception if we aren't in a change edit? + return replIndex; + } + + /** + * The start index of the current span in the destination string; the span has length + * {@link #newLength}. + * + * @return the current index into the full destination string + * @stable ICU 59 + */ + int32_t destinationIndex() const { return destIndex; } + +#ifndef U_HIDE_INTERNAL_API + /** + * A string representation of the current edit represented by the iterator for debugging. You + * should not depend on the contents of the return string. + * @internal + */ + UnicodeString& toString(UnicodeString& appendTo) const; +#endif // U_HIDE_INTERNAL_API + + private: + friend class Edits; + + Iterator(const uint16_t *a, int32_t len, UBool oc, UBool crs); + + int32_t readLength(int32_t head); + void updateNextIndexes(); + void updatePreviousIndexes(); + UBool noNext(); + UBool next(UBool onlyChanges, UErrorCode &errorCode); + UBool previous(UErrorCode &errorCode); + /** @return -1: error or i<0; 0: found; 1: i>=string length */ + int32_t findIndex(int32_t i, UBool findSource, UErrorCode &errorCode); + + const uint16_t *array; + int32_t index, length; + // 0 if we are not within compressed equal-length changes. + // Otherwise the number of remaining changes, including the current one. + int32_t remaining; + UBool onlyChanges_, coarse; + + int8_t dir; // iteration direction: back(<0), initial(0), forward(>0) + UBool changed; + int32_t oldLength_, newLength_; + int32_t srcIndex, replIndex, destIndex; + }; + + /** + * Returns an Iterator for coarse-grained change edits + * (adjacent change edits are treated as one). + * Can be used to perform simple string updates. + * Skips no-change edits. + * @return an Iterator that merges adjacent changes. + * @stable ICU 59 + */ + Iterator getCoarseChangesIterator() const { + return Iterator(array, length, true, true); + } + + /** + * Returns an Iterator for coarse-grained change and no-change edits + * (adjacent change edits are treated as one). + * Can be used to perform simple string updates. + * Adjacent change edits are treated as one edit. + * @return an Iterator that merges adjacent changes. + * @stable ICU 59 + */ + Iterator getCoarseIterator() const { + return Iterator(array, length, false, true); + } + + /** + * Returns an Iterator for fine-grained change edits + * (full granularity of change edits is retained). + * Can be used for modifying styled text. + * Skips no-change edits. + * @return an Iterator that separates adjacent changes. + * @stable ICU 59 + */ + Iterator getFineChangesIterator() const { + return Iterator(array, length, true, false); + } + + /** + * Returns an Iterator for fine-grained change and no-change edits + * (full granularity of change edits is retained). + * Can be used for modifying styled text. + * @return an Iterator that separates adjacent changes. + * @stable ICU 59 + */ + Iterator getFineIterator() const { + return Iterator(array, length, false, false); + } + + /** + * Merges the two input Edits and appends the result to this object. + * + * Consider two string transformations (for example, normalization and case mapping) + * where each records Edits in addition to writing an output string.
+ * Edits ab reflect how substrings of input string a + * map to substrings of intermediate string b.
+ * Edits bc reflect how substrings of intermediate string b + * map to substrings of output string c.
+ * This function merges ab and bc such that the additional edits + * recorded in this object reflect how substrings of input string a + * map to substrings of output string c. + * + * If unrelated Edits are passed in where the output string of the first + * has a different length than the input string of the second, + * then a U_ILLEGAL_ARGUMENT_ERROR is reported. + * + * @param ab reflects how substrings of input string a + * map to substrings of intermediate string b. + * @param bc reflects how substrings of intermediate string b + * map to substrings of output string c. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return *this, with the merged edits appended + * @stable ICU 60 + */ + Edits &mergeAndAppend(const Edits &ab, const Edits &bc, UErrorCode &errorCode); + +private: + void releaseArray() noexcept; + Edits ©Array(const Edits &other); + Edits &moveArray(Edits &src) noexcept; + + void setLastUnit(int32_t last) { array[length - 1] = (uint16_t)last; } + int32_t lastUnit() const { return length > 0 ? array[length - 1] : 0xffff; } + + void append(int32_t r); + UBool growArray(); + + static const int32_t STACK_CAPACITY = 100; + uint16_t *array; + int32_t capacity; + int32_t length; + int32_t delta; + int32_t numChanges; + UErrorCode errorCode_; + uint16_t stackArray[STACK_CAPACITY]; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __EDITS_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/enumset.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/enumset.h new file mode 100644 index 0000000000000000000000000000000000000000..bde8c455c0dd2bd80f57101dc95d0ef094352b72 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/enumset.h @@ -0,0 +1,69 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 2012,2014 International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +*/ + +/** + * \file + * \brief C++: internal template EnumSet<> + */ + +#ifndef ENUMSET_H +#define ENUMSET_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/* Can't use #ifndef U_HIDE_INTERNAL_API for the entire EnumSet class, needed in .h file declarations */ +/** + * enum bitset for boolean fields. Similar to Java EnumSet<>. + * Needs to range check. Used for private instance variables. + * @internal + * \cond + */ +template +class EnumSet { +public: + inline EnumSet() : fBools(0) {} + inline EnumSet(const EnumSet& other) : fBools(other.fBools) {} + inline ~EnumSet() {} +#ifndef U_HIDE_INTERNAL_API + inline void clear() { fBools=0; } + inline void add(T toAdd) { set(toAdd, 1); } + inline void remove(T toRemove) { set(toRemove, 0); } + inline int32_t contains(T toCheck) const { return get(toCheck); } + inline void set(T toSet, int32_t v) { fBools=(fBools&(~flag(toSet)))|(v?(flag(toSet)):0); } + inline int32_t get(T toCheck) const { return (fBools & flag(toCheck))?1:0; } + inline UBool isValidEnum(T toCheck) const { return (toCheck>=minValue&&toCheck& operator=(const EnumSet& other) { + fBools = other.fBools; + return *this; + } + + inline uint32_t getAll() const { + return fBools; + } +#endif /* U_HIDE_INTERNAL_API */ + +private: + inline uint32_t flag(T toCheck) const { return (1<<(toCheck-minValue)); } +private: + uint32_t fBools; +}; + +/** \endcond */ + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ +#endif /* ENUMSET_H */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/errorcode.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/errorcode.h new file mode 100644 index 0000000000000000000000000000000000000000..fe7b5183232cd149913c929a20e8ef7f879b619c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/errorcode.h @@ -0,0 +1,144 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2009-2011, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: errorcode.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2009mar10 +* created by: Markus W. Scherer +*/ + +#ifndef __ERRORCODE_H__ +#define __ERRORCODE_H__ + +/** + * \file + * \brief C++ API: ErrorCode class intended to make it easier to use + * ICU C and C++ APIs from C++ user code. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN + +/** + * Wrapper class for UErrorCode, with conversion operators for direct use + * in ICU C and C++ APIs. + * Intended to be used as a base class, where a subclass overrides + * the handleFailure() function so that it throws an exception, + * does an assert(), logs an error, etc. + * This is not an abstract base class. This class can be used and instantiated + * by itself, although it will be more useful when subclassed. + * + * Features: + * - The constructor initializes the internal UErrorCode to U_ZERO_ERROR, + * removing one common source of errors. + * - Same use in C APIs taking a UErrorCode * (pointer) + * and C++ taking UErrorCode & (reference) via conversion operators. + * - Possible automatic checking for success when it goes out of scope. + * + * Note: For automatic checking for success in the destructor, a subclass + * must implement such logic in its own destructor because the base class + * destructor cannot call a subclass function (like handleFailure()). + * The ErrorCode base class destructor does nothing. + * + * Note also: While it is possible for a destructor to throw an exception, + * it is generally unsafe to do so. This means that in a subclass the destructor + * and the handleFailure() function may need to take different actions. + * + * Sample code: + * \code + * class IcuErrorCode: public icu::ErrorCode { + * public: + * virtual ~IcuErrorCode() { // should be defined in .cpp as "key function" + * // Safe because our handleFailure() does not throw exceptions. + * if(isFailure()) { handleFailure(); } + * } + * protected: + * virtual void handleFailure() const { + * log_failure(u_errorName(errorCode)); + * exit(errorCode); + * } + * }; + * IcuErrorCode error_code; + * UConverter *cnv = ucnv_open("Shift-JIS", error_code); + * length = ucnv_fromUChars(dest, capacity, src, length, error_code); + * ucnv_close(cnv); + * // IcuErrorCode destructor checks for success. + * \endcode + * + * @stable ICU 4.2 + */ +class U_COMMON_API ErrorCode: public UMemory { +public: + /** + * Default constructor. Initializes its UErrorCode to U_ZERO_ERROR. + * @stable ICU 4.2 + */ + ErrorCode() : errorCode(U_ZERO_ERROR) {} + /** Destructor, does nothing. See class documentation for details. @stable ICU 4.2 */ + virtual ~ErrorCode(); + /** Conversion operator, returns a reference. @stable ICU 4.2 */ + operator UErrorCode & () { return errorCode; } + /** Conversion operator, returns a pointer. @stable ICU 4.2 */ + operator UErrorCode * () { return &errorCode; } + /** Tests for U_SUCCESS(). @stable ICU 4.2 */ + UBool isSuccess() const { return U_SUCCESS(errorCode); } + /** Tests for U_FAILURE(). @stable ICU 4.2 */ + UBool isFailure() const { return U_FAILURE(errorCode); } + /** Returns the UErrorCode value. @stable ICU 4.2 */ + UErrorCode get() const { return errorCode; } + /** Sets the UErrorCode value. @stable ICU 4.2 */ + void set(UErrorCode value) { errorCode=value; } + /** Returns the UErrorCode value and resets it to U_ZERO_ERROR. @stable ICU 4.2 */ + UErrorCode reset(); + /** + * Asserts isSuccess(). + * In other words, this method checks for a failure code, + * and the base class handles it like this: + * \code + * if(isFailure()) { handleFailure(); } + * \endcode + * @stable ICU 4.4 + */ + void assertSuccess() const; + /** + * Return a string for the UErrorCode value. + * The string will be the same as the name of the error code constant + * in the UErrorCode enum. + * @stable ICU 4.4 + */ + const char* errorName() const; + +protected: + /** + * Internal UErrorCode, accessible to subclasses. + * @stable ICU 4.2 + */ + UErrorCode errorCode; + /** + * Called by assertSuccess() if isFailure() is true. + * A subclass should override this function to deal with a failure code: + * Throw an exception, log an error, terminate the program, or similar. + * @stable ICU 4.2 + */ + virtual void handleFailure() const {} +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __ERRORCODE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fieldpos.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fieldpos.h new file mode 100644 index 0000000000000000000000000000000000000000..0c092a00522935ab7672dbf5efb0cd13cbf4c714 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fieldpos.h @@ -0,0 +1,298 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************** + * Copyright (C) 1997-2006, International Business Machines + * Corporation and others. All Rights Reserved. + ******************************************************************************** + * + * File FIELDPOS.H + * + * Modification History: + * + * Date Name Description + * 02/25/97 aliu Converted from java. + * 03/17/97 clhuang Updated per Format implementation. + * 07/17/98 stephen Added default/copy ctors, and operators =, ==, != + ******************************************************************************** + */ + +// ***************************************************************************** +// This file was generated from the java source file FieldPosition.java +// ***************************************************************************** + +#ifndef FIELDPOS_H +#define FIELDPOS_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: FieldPosition identifies the fields in a formatted output. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN + +/** + * FieldPosition is a simple class used by Format + * and its subclasses to identify fields in formatted output. Fields are + * identified by constants, whose names typically end with _FIELD, + * defined in the various subclasses of Format. See + * ERA_FIELD and its friends in DateFormat for + * an example. + * + *

+ * FieldPosition keeps track of the position of the + * field within the formatted output with two indices: the index + * of the first character of the field and the index of the last + * character of the field. + * + *

+ * One version of the format method in the various + * Format classes requires a FieldPosition + * object as an argument. You use this format method + * to perform partial formatting or to get information about the + * formatted output (such as the position of a field). + * + * The FieldPosition class is not intended for public subclassing. + * + *

+ * Below is an example of using FieldPosition to aid + * alignment of an array of formatted floating-point numbers on + * their decimal points: + *

+ * \code
+ *       double doubleNum[] = {123456789.0, -12345678.9, 1234567.89, -123456.789,
+ *                  12345.6789, -1234.56789, 123.456789, -12.3456789, 1.23456789};
+ *       int dNumSize = (int)(sizeof(doubleNum)/sizeof(double));
+ *       
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       DecimalFormat* fmt = (DecimalFormat*) NumberFormat::createInstance(status);
+ *       fmt->setDecimalSeparatorAlwaysShown(true);
+ *       
+ *       const int tempLen = 20;
+ *       char temp[tempLen];
+ *       
+ *       for (int i=0; iformat(doubleNum[i], buf, pos), fmtText);
+ *           for (int j=0; j
+ * 

+ * The code will generate the following output: + *

+ * \code
+ *           123,456,789.000
+ *           -12,345,678.900
+ *             1,234,567.880
+ *              -123,456.789
+ *                12,345.678
+ *                -1,234.567
+ *                   123.456
+ *                   -12.345
+ *                     1.234
+ *  \endcode
+ * 
+ */ +class U_I18N_API FieldPosition : public UObject { +public: + /** + * DONT_CARE may be specified as the field to indicate that the + * caller doesn't need to specify a field. + * @stable ICU 2.0 + */ + enum { DONT_CARE = -1 }; + + /** + * Creates a FieldPosition object with a non-specified field. + * @stable ICU 2.0 + */ + FieldPosition() + : UObject(), fField(DONT_CARE), fBeginIndex(0), fEndIndex(0) {} + + /** + * Creates a FieldPosition object for the given field. Fields are + * identified by constants, whose names typically end with _FIELD, + * in the various subclasses of Format. + * + * @see NumberFormat#INTEGER_FIELD + * @see NumberFormat#FRACTION_FIELD + * @see DateFormat#YEAR_FIELD + * @see DateFormat#MONTH_FIELD + * @stable ICU 2.0 + */ + FieldPosition(int32_t field) + : UObject(), fField(field), fBeginIndex(0), fEndIndex(0) {} + + /** + * Copy constructor + * @param copy the object to be copied from. + * @stable ICU 2.0 + */ + FieldPosition(const FieldPosition& copy) + : UObject(copy), fField(copy.fField), fBeginIndex(copy.fBeginIndex), fEndIndex(copy.fEndIndex) {} + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~FieldPosition(); + + /** + * Assignment operator + * @param copy the object to be copied from. + * @stable ICU 2.0 + */ + FieldPosition& operator=(const FieldPosition& copy); + + /** + * Equality operator. + * @param that the object to be compared with. + * @return true if the two field positions are equal, false otherwise. + * @stable ICU 2.0 + */ + bool operator==(const FieldPosition& that) const; + + /** + * Equality operator. + * @param that the object to be compared with. + * @return true if the two field positions are not equal, false otherwise. + * @stable ICU 2.0 + */ + bool operator!=(const FieldPosition& that) const; + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + FieldPosition *clone() const; + + /** + * Retrieve the field identifier. + * @return the field identifier. + * @stable ICU 2.0 + */ + int32_t getField(void) const { return fField; } + + /** + * Retrieve the index of the first character in the requested field. + * @return the index of the first character in the requested field. + * @stable ICU 2.0 + */ + int32_t getBeginIndex(void) const { return fBeginIndex; } + + /** + * Retrieve the index of the character following the last character in the + * requested field. + * @return the index of the character following the last character in the + * requested field. + * @stable ICU 2.0 + */ + int32_t getEndIndex(void) const { return fEndIndex; } + + /** + * Set the field. + * @param f the new value of the field. + * @stable ICU 2.0 + */ + void setField(int32_t f) { fField = f; } + + /** + * Set the begin index. For use by subclasses of Format. + * @param bi the new value of the begin index + * @stable ICU 2.0 + */ + void setBeginIndex(int32_t bi) { fBeginIndex = bi; } + + /** + * Set the end index. For use by subclasses of Format. + * @param ei the new value of the end index + * @stable ICU 2.0 + */ + void setEndIndex(int32_t ei) { fEndIndex = ei; } + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + /** + * Input: Desired field to determine start and end offsets for. + * The meaning depends on the subclass of Format. + */ + int32_t fField; + + /** + * Output: Start offset of field in text. + * If the field does not occur in the text, 0 is returned. + */ + int32_t fBeginIndex; + + /** + * Output: End offset of field in text. + * If the field does not occur in the text, 0 is returned. + */ + int32_t fEndIndex; +}; + +inline FieldPosition& +FieldPosition::operator=(const FieldPosition& copy) +{ + fField = copy.fField; + fEndIndex = copy.fEndIndex; + fBeginIndex = copy.fBeginIndex; + return *this; +} + +inline bool +FieldPosition::operator==(const FieldPosition& copy) const +{ + return (fField == copy.fField && + fEndIndex == copy.fEndIndex && + fBeginIndex == copy.fBeginIndex); +} + +inline bool +FieldPosition::operator!=(const FieldPosition& copy) const +{ + return !operator==(copy); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _FIELDPOS +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/filteredbrk.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/filteredbrk.h new file mode 100644 index 0000000000000000000000000000000000000000..8b07e39ae12bb61bdf56d3e5d682d84a959c92ff --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/filteredbrk.h @@ -0,0 +1,152 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2015, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +*/ + +#ifndef FILTEREDBRK_H +#define FILTEREDBRK_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/brkiter.h" + +#if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION + +U_NAMESPACE_BEGIN + +/** + * \file + * \brief C++ API: FilteredBreakIteratorBuilder + */ + +/** + * The BreakIteratorFilter is used to modify the behavior of a BreakIterator + * by constructing a new BreakIterator which suppresses certain segment boundaries. + * See http://www.unicode.org/reports/tr35/tr35-general.html#Segmentation_Exceptions . + * For example, a typical English Sentence Break Iterator would break on the space + * in the string "Mr. Smith" (resulting in two segments), + * but with "Mr." as an exception, a filtered break iterator + * would consider the string "Mr. Smith" to be a single segment. + * + * @stable ICU 56 + */ +class U_COMMON_API FilteredBreakIteratorBuilder : public UObject { + public: + /** + * destructor. + * @stable ICU 56 + */ + virtual ~FilteredBreakIteratorBuilder(); + + /** + * Construct a FilteredBreakIteratorBuilder based on rules in a locale. + * The rules are taken from CLDR exception data for the locale, + * see http://www.unicode.org/reports/tr35/tr35-general.html#Segmentation_Exceptions + * This is the equivalent of calling createInstance(UErrorCode&) + * and then repeatedly calling addNoBreakAfter(...) with the contents + * of the CLDR exception data. + * @param where the locale. + * @param status The error code. + * @return the new builder + * @stable ICU 56 + */ + static FilteredBreakIteratorBuilder *createInstance(const Locale& where, UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * This function has been deprecated in favor of createEmptyInstance, which has + * identical behavior. + * @param status The error code. + * @return the new builder + * @deprecated ICU 60 use createEmptyInstance instead + * @see createEmptyInstance() + */ + static FilteredBreakIteratorBuilder *createInstance(UErrorCode &status); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Construct an empty FilteredBreakIteratorBuilder. + * In this state, it will not suppress any segment boundaries. + * @param status The error code. + * @return the new builder + * @stable ICU 60 + */ + static FilteredBreakIteratorBuilder *createEmptyInstance(UErrorCode &status); + + /** + * Suppress a certain string from being the end of a segment. + * For example, suppressing "Mr.", then segments ending in "Mr." will not be returned + * by the iterator. + * @param string the string to suppress, such as "Mr." + * @param status error code + * @return returns true if the string was not present and now added, + * false if the call was a no-op because the string was already being suppressed. + * @stable ICU 56 + */ + virtual UBool suppressBreakAfter(const UnicodeString& string, UErrorCode& status) = 0; + + /** + * Stop suppressing a certain string from being the end of the segment. + * This function does not create any new segment boundaries, but only serves to un-do + * the effect of earlier calls to suppressBreakAfter, or to un-do the effect of + * locale data which may be suppressing certain strings. + * @param string the exception to remove + * @param status error code + * @return returns true if the string was present and now removed, + * false if the call was a no-op because the string was not being suppressed. + * @stable ICU 56 + */ + virtual UBool unsuppressBreakAfter(const UnicodeString& string, UErrorCode& status) = 0; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * This function has been deprecated in favor of wrapIteratorWithFilter() + * The behavior is identical. + * @param adoptBreakIterator the break iterator to adopt + * @param status error code + * @return the new BreakIterator, owned by the caller. + * @deprecated ICU 60 use wrapIteratorWithFilter() instead + * @see wrapBreakIteratorWithFilter() + */ + virtual BreakIterator *build(BreakIterator* adoptBreakIterator, UErrorCode& status) = 0; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Wrap (adopt) an existing break iterator in a new filtered instance. + * The resulting BreakIterator is owned by the caller. + * The BreakIteratorFilter may be destroyed before the BreakIterator is destroyed. + * Note that the adoptBreakIterator is adopted by the new BreakIterator + * and should no longer be used by the caller. + * The FilteredBreakIteratorBuilder may be reused. + * This function is an alias for build() + * @param adoptBreakIterator the break iterator to adopt + * @param status error code + * @return the new BreakIterator, owned by the caller. + * @stable ICU 60 + */ + inline BreakIterator *wrapIteratorWithFilter(BreakIterator* adoptBreakIterator, UErrorCode& status) { + return build(adoptBreakIterator, status); + } + + protected: + /** + * For subclass use + * @stable ICU 56 + */ + FilteredBreakIteratorBuilder(); +}; + + +U_NAMESPACE_END + +#endif // #if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // #ifndef FILTEREDBRK_H diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fmtable.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fmtable.h new file mode 100644 index 0000000000000000000000000000000000000000..6bda3576042143abd308305e128301e2e9fedeab --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fmtable.h @@ -0,0 +1,759 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2014, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File FMTABLE.H +* +* Modification History: +* +* Date Name Description +* 02/29/97 aliu Creation. +******************************************************************************** +*/ +#ifndef FMTABLE_H +#define FMTABLE_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Formattable is a thin wrapper for primitive types used for formatting and parsing + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" +#include "unicode/stringpiece.h" +#include "unicode/uformattable.h" + +U_NAMESPACE_BEGIN + +class CharString; +namespace number { +namespace impl { +class DecimalQuantity; +} +} + +/** + * Formattable objects can be passed to the Format class or + * its subclasses for formatting. Formattable is a thin wrapper + * class which interconverts between the primitive numeric types + * (double, long, etc.) as well as UDate and UnicodeString. + * + *

Internally, a Formattable object is a union of primitive types. + * As such, it can only store one flavor of data at a time. To + * determine what flavor of data it contains, use the getType method. + * + *

As of ICU 3.0, Formattable may also wrap a UObject pointer, + * which it owns. This allows an instance of any ICU class to be + * encapsulated in a Formattable. For legacy reasons and for + * efficiency, primitive numeric types are still stored directly + * within a Formattable. + * + *

The Formattable class is not suitable for subclassing. + * + *

See UFormattable for a C wrapper. + */ +class U_I18N_API Formattable : public UObject { +public: + /** + * This enum is only used to let callers distinguish between + * the Formattable(UDate) constructor and the Formattable(double) + * constructor; the compiler cannot distinguish the signatures, + * since UDate is currently typedefed to be either double or long. + * If UDate is changed later to be a bonafide class + * or struct, then we no longer need this enum. + * @stable ICU 2.4 + */ + enum ISDATE { kIsDate }; + + /** + * Default constructor + * @stable ICU 2.4 + */ + Formattable(); // Type kLong, value 0 + + /** + * Creates a Formattable object with a UDate instance. + * @param d the UDate instance. + * @param flag the flag to indicate this is a date. Always set it to kIsDate + * @stable ICU 2.0 + */ + Formattable(UDate d, ISDATE flag); + + /** + * Creates a Formattable object with a double number. + * @param d the double number. + * @stable ICU 2.0 + */ + Formattable(double d); + + /** + * Creates a Formattable object with a long number. + * @param l the long number. + * @stable ICU 2.0 + */ + Formattable(int32_t l); + + /** + * Creates a Formattable object with an int64_t number + * @param ll the int64_t number. + * @stable ICU 2.8 + */ + Formattable(int64_t ll); + +#if !UCONFIG_NO_CONVERSION + /** + * Creates a Formattable object with a char string pointer. + * Assumes that the char string is null terminated. + * @param strToCopy the char string. + * @stable ICU 2.0 + */ + Formattable(const char* strToCopy); +#endif + + /** + * Creates a Formattable object of an appropriate numeric type from a + * a decimal number in string form. The Formattable will retain the + * full precision of the input in decimal format, even when it exceeds + * what can be represented by a double or int64_t. + * + * @param number the unformatted (not localized) string representation + * of the Decimal number. + * @param status the error code. Possible errors include U_INVALID_FORMAT_ERROR + * if the format of the string does not conform to that of a + * decimal number. + * @stable ICU 4.4 + */ + Formattable(StringPiece number, UErrorCode &status); + + /** + * Creates a Formattable object with a UnicodeString object to copy from. + * @param strToCopy the UnicodeString string. + * @stable ICU 2.0 + */ + Formattable(const UnicodeString& strToCopy); + + /** + * Creates a Formattable object with a UnicodeString object to adopt from. + * @param strToAdopt the UnicodeString string. + * @stable ICU 2.0 + */ + Formattable(UnicodeString* strToAdopt); + + /** + * Creates a Formattable object with an array of Formattable objects. + * @param arrayToCopy the Formattable object array. + * @param count the array count. + * @stable ICU 2.0 + */ + Formattable(const Formattable* arrayToCopy, int32_t count); + + /** + * Creates a Formattable object that adopts the given UObject. + * @param objectToAdopt the UObject to set this object to + * @stable ICU 3.0 + */ + Formattable(UObject* objectToAdopt); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + Formattable(const Formattable&); + + /** + * Assignment operator. + * @param rhs The Formattable object to copy into this object. + * @stable ICU 2.0 + */ + Formattable& operator=(const Formattable &rhs); + + /** + * Equality comparison. + * @param other the object to be compared with. + * @return true if other are equal to this, false otherwise. + * @stable ICU 2.0 + */ + bool operator==(const Formattable &other) const; + + /** + * Equality operator. + * @param other the object to be compared with. + * @return true if other are unequal to this, false otherwise. + * @stable ICU 2.0 + */ + bool operator!=(const Formattable& other) const + { return !operator==(other); } + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~Formattable(); + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + Formattable *clone() const; + + /** + * Selector for flavor of data type contained within a + * Formattable object. Formattable is a union of several + * different types, and at any time contains exactly one type. + * @stable ICU 2.4 + */ + enum Type { + /** + * Selector indicating a UDate value. Use getDate to retrieve + * the value. + * @stable ICU 2.4 + */ + kDate, + + /** + * Selector indicating a double value. Use getDouble to + * retrieve the value. + * @stable ICU 2.4 + */ + kDouble, + + /** + * Selector indicating a 32-bit integer value. Use getLong to + * retrieve the value. + * @stable ICU 2.4 + */ + kLong, + + /** + * Selector indicating a UnicodeString value. Use getString + * to retrieve the value. + * @stable ICU 2.4 + */ + kString, + + /** + * Selector indicating an array of Formattables. Use getArray + * to retrieve the value. + * @stable ICU 2.4 + */ + kArray, + + /** + * Selector indicating a 64-bit integer value. Use getInt64 + * to retrieve the value. + * @stable ICU 2.8 + */ + kInt64, + + /** + * Selector indicating a UObject value. Use getObject to + * retrieve the value. + * @stable ICU 3.0 + */ + kObject + }; + + /** + * Gets the data type of this Formattable object. + * @return the data type of this Formattable object. + * @stable ICU 2.0 + */ + Type getType(void) const; + + /** + * Returns true if the data type of this Formattable object + * is kDouble, kLong, or kInt64 + * @return true if this is a pure numeric object + * @stable ICU 3.0 + */ + UBool isNumeric() const; + + /** + * Gets the double value of this object. If this object is not of type + * kDouble then the result is undefined. + * @return the double value of this object. + * @stable ICU 2.0 + */ + double getDouble(void) const { return fValue.fDouble; } + + /** + * Gets the double value of this object. If this object is of type + * long, int64 or Decimal Number then a conversion is performed, with + * possible loss of precision. If the type is kObject and the + * object is a Measure, then the result of + * getNumber().getDouble(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param status the error code + * @return the double value of this object. + * @stable ICU 3.0 + */ + double getDouble(UErrorCode& status) const; + + /** + * Gets the long value of this object. If this object is not of type + * kLong then the result is undefined. + * @return the long value of this object. + * @stable ICU 2.0 + */ + int32_t getLong(void) const { return (int32_t)fValue.fInt64; } + + /** + * Gets the long value of this object. If the magnitude is too + * large to fit in a long, then the maximum or minimum long value, + * as appropriate, is returned and the status is set to + * U_INVALID_FORMAT_ERROR. If this object is of type kInt64 and + * it fits within a long, then no precision is lost. If it is of + * type kDouble, then a conversion is performed, with + * truncation of any fractional part. If the type is kObject and + * the object is a Measure, then the result of + * getNumber().getLong(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param status the error code + * @return the long value of this object. + * @stable ICU 3.0 + */ + int32_t getLong(UErrorCode& status) const; + + /** + * Gets the int64 value of this object. If this object is not of type + * kInt64 then the result is undefined. + * @return the int64 value of this object. + * @stable ICU 2.8 + */ + int64_t getInt64(void) const { return fValue.fInt64; } + + /** + * Gets the int64 value of this object. If this object is of a numeric + * type and the magnitude is too large to fit in an int64, then + * the maximum or minimum int64 value, as appropriate, is returned + * and the status is set to U_INVALID_FORMAT_ERROR. If the + * magnitude fits in an int64, then a casting conversion is + * performed, with truncation of any fractional part. If the type + * is kObject and the object is a Measure, then the result of + * getNumber().getDouble(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param status the error code + * @return the int64 value of this object. + * @stable ICU 3.0 + */ + int64_t getInt64(UErrorCode& status) const; + + /** + * Gets the Date value of this object. If this object is not of type + * kDate then the result is undefined. + * @return the Date value of this object. + * @stable ICU 2.0 + */ + UDate getDate() const { return fValue.fDate; } + + /** + * Gets the Date value of this object. If the type is not a date, + * status is set to U_INVALID_FORMAT_ERROR and the return value is + * undefined. + * @param status the error code. + * @return the Date value of this object. + * @stable ICU 3.0 + */ + UDate getDate(UErrorCode& status) const; + + /** + * Gets the string value of this object. If this object is not of type + * kString then the result is undefined. + * @param result Output param to receive the Date value of this object. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getString(UnicodeString& result) const + { result=*fValue.fString; return result; } + + /** + * Gets the string value of this object. If the type is not a + * string, status is set to U_INVALID_FORMAT_ERROR and a bogus + * string is returned. + * @param result Output param to receive the Date value of this object. + * @param status the error code. + * @return A reference to 'result'. + * @stable ICU 3.0 + */ + UnicodeString& getString(UnicodeString& result, UErrorCode& status) const; + + /** + * Gets a const reference to the string value of this object. If + * this object is not of type kString then the result is + * undefined. + * @return a const reference to the string value of this object. + * @stable ICU 2.0 + */ + inline const UnicodeString& getString(void) const; + + /** + * Gets a const reference to the string value of this object. If + * the type is not a string, status is set to + * U_INVALID_FORMAT_ERROR and the result is a bogus string. + * @param status the error code. + * @return a const reference to the string value of this object. + * @stable ICU 3.0 + */ + const UnicodeString& getString(UErrorCode& status) const; + + /** + * Gets a reference to the string value of this object. If this + * object is not of type kString then the result is undefined. + * @return a reference to the string value of this object. + * @stable ICU 2.0 + */ + inline UnicodeString& getString(void); + + /** + * Gets a reference to the string value of this object. If the + * type is not a string, status is set to U_INVALID_FORMAT_ERROR + * and the result is a bogus string. + * @param status the error code. + * @return a reference to the string value of this object. + * @stable ICU 3.0 + */ + UnicodeString& getString(UErrorCode& status); + + /** + * Gets the array value and count of this object. If this object + * is not of type kArray then the result is undefined. + * @param count fill-in with the count of this object. + * @return the array value of this object. + * @stable ICU 2.0 + */ + const Formattable* getArray(int32_t& count) const + { count=fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; } + + /** + * Gets the array value and count of this object. If the type is + * not an array, status is set to U_INVALID_FORMAT_ERROR, count is + * set to 0, and the result is nullptr. + * @param count fill-in with the count of this object. + * @param status the error code. + * @return the array value of this object. + * @stable ICU 3.0 + */ + const Formattable* getArray(int32_t& count, UErrorCode& status) const; + + /** + * Accesses the specified element in the array value of this + * Formattable object. If this object is not of type kArray then + * the result is undefined. + * @param index the specified index. + * @return the accessed element in the array. + * @stable ICU 2.0 + */ + Formattable& operator[](int32_t index) { return fValue.fArrayAndCount.fArray[index]; } + + /** + * Returns a pointer to the UObject contained within this + * formattable, or nullptr if this object does not contain a UObject. + * @return a UObject pointer, or nullptr + * @stable ICU 3.0 + */ + const UObject* getObject() const; + + /** + * Returns a numeric string representation of the number contained within this + * formattable, or nullptr if this object does not contain numeric type. + * For values obtained by parsing, the returned decimal number retains + * the full precision and range of the original input, unconstrained by + * the limits of a double floating point or a 64 bit int. + * + * This function is not thread safe, and therefore is not declared const, + * even though it is logically const. + * + * Possible errors include U_MEMORY_ALLOCATION_ERROR, and + * U_INVALID_STATE if the formattable object has not been set to + * a numeric type. + * + * @param status the error code. + * @return the unformatted string representation of a number. + * @stable ICU 4.4 + */ + StringPiece getDecimalNumber(UErrorCode &status); + + /** + * Sets the double value of this object and changes the type to + * kDouble. + * @param d the new double value to be set. + * @stable ICU 2.0 + */ + void setDouble(double d); + + /** + * Sets the long value of this object and changes the type to + * kLong. + * @param l the new long value to be set. + * @stable ICU 2.0 + */ + void setLong(int32_t l); + + /** + * Sets the int64 value of this object and changes the type to + * kInt64. + * @param ll the new int64 value to be set. + * @stable ICU 2.8 + */ + void setInt64(int64_t ll); + + /** + * Sets the Date value of this object and changes the type to + * kDate. + * @param d the new Date value to be set. + * @stable ICU 2.0 + */ + void setDate(UDate d); + + /** + * Sets the string value of this object and changes the type to + * kString. + * @param stringToCopy the new string value to be set. + * @stable ICU 2.0 + */ + void setString(const UnicodeString& stringToCopy); + + /** + * Sets the array value and count of this object and changes the + * type to kArray. + * @param array the array value. + * @param count the number of array elements to be copied. + * @stable ICU 2.0 + */ + void setArray(const Formattable* array, int32_t count); + + /** + * Sets and adopts the string value and count of this object and + * changes the type to kArray. + * @param stringToAdopt the new string value to be adopted. + * @stable ICU 2.0 + */ + void adoptString(UnicodeString* stringToAdopt); + + /** + * Sets and adopts the array value and count of this object and + * changes the type to kArray. + * @stable ICU 2.0 + */ + void adoptArray(Formattable* array, int32_t count); + + /** + * Sets and adopts the UObject value of this object and changes + * the type to kObject. After this call, the caller must not + * delete the given object. + * @param objectToAdopt the UObject value to be adopted + * @stable ICU 3.0 + */ + void adoptObject(UObject* objectToAdopt); + + /** + * Sets the the numeric value from a decimal number string, and changes + * the type to to a numeric type appropriate for the number. + * The syntax of the number is a "numeric string" + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * The full precision and range of the input number will be retained, + * even when it exceeds what can be represented by a double or an int64. + * + * @param numberString a string representation of the unformatted decimal number. + * @param status the error code. Set to U_INVALID_FORMAT_ERROR if the + * incoming string is not a valid decimal number. + * @stable ICU 4.4 + */ + void setDecimalNumber(StringPiece numberString, + UErrorCode &status); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * Convert the UFormattable to a Formattable. Internally, this is a reinterpret_cast. + * @param fmt a valid UFormattable + * @return the UFormattable as a Formattable object pointer. This is an alias to the original + * UFormattable, and so is only valid while the original argument remains in scope. + * @stable ICU 52 + */ + static inline Formattable *fromUFormattable(UFormattable *fmt); + + /** + * Convert the const UFormattable to a const Formattable. Internally, this is a reinterpret_cast. + * @param fmt a valid UFormattable + * @return the UFormattable as a Formattable object pointer. This is an alias to the original + * UFormattable, and so is only valid while the original argument remains in scope. + * @stable ICU 52 + */ + static inline const Formattable *fromUFormattable(const UFormattable *fmt); + + /** + * Convert this object pointer to a UFormattable. + * @return this object as a UFormattable pointer. This is an alias to this object, + * and so is only valid while this object remains in scope. + * @stable ICU 52 + */ + inline UFormattable *toUFormattable(); + + /** + * Convert this object pointer to a UFormattable. + * @return this object as a UFormattable pointer. This is an alias to this object, + * and so is only valid while this object remains in scope. + * @stable ICU 52 + */ + inline const UFormattable *toUFormattable() const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Deprecated variant of getLong(UErrorCode&). + * @param status the error code + * @return the long value of this object. + * @deprecated ICU 3.0 use getLong(UErrorCode&) instead + */ + inline int32_t getLong(UErrorCode* status) const; +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_HIDE_INTERNAL_API + /** + * Internal function, do not use. + * TODO: figure out how to make this be non-public. + * NumberFormat::format(Formattable, ... + * needs to get at the DecimalQuantity, if it exists, for + * big decimal formatting. + * @internal + */ + number::impl::DecimalQuantity *getDecimalQuantity() const { return fDecimalQuantity;} + + /** + * Export the value of this Formattable to a DecimalQuantity. + * @internal + */ + void populateDecimalQuantity(number::impl::DecimalQuantity& output, UErrorCode& status) const; + + /** + * Adopt, and set value from, a DecimalQuantity + * Internal Function, do not use. + * @param dq the DecimalQuantity to be adopted + * @internal + */ + void adoptDecimalQuantity(number::impl::DecimalQuantity *dq); + + /** + * Internal function to return the CharString pointer. + * @param status error code + * @return pointer to the CharString - may become invalid if the object is modified + * @internal + */ + CharString *internalGetCharString(UErrorCode &status); + +#endif /* U_HIDE_INTERNAL_API */ + +private: + /** + * Cleans up the memory for unwanted values. For example, the adopted + * string or array objects. + */ + void dispose(void); + + /** + * Common initialization, for use by constructors. + */ + void init(); + + UnicodeString* getBogus() const; + + union { + UObject* fObject; + UnicodeString* fString; + double fDouble; + int64_t fInt64; + UDate fDate; + struct { + Formattable* fArray; + int32_t fCount; + } fArrayAndCount; + } fValue; + + CharString *fDecimalStr; + + number::impl::DecimalQuantity *fDecimalQuantity; + + Type fType; + UnicodeString fBogus; // Bogus string when it's needed. +}; + +inline UDate Formattable::getDate(UErrorCode& status) const { + if (fType != kDate) { + if (U_SUCCESS(status)) { + status = U_INVALID_FORMAT_ERROR; + } + return 0; + } + return fValue.fDate; +} + +inline const UnicodeString& Formattable::getString(void) const { + return *fValue.fString; +} + +inline UnicodeString& Formattable::getString(void) { + return *fValue.fString; +} + +#ifndef U_HIDE_DEPRECATED_API +inline int32_t Formattable::getLong(UErrorCode* status) const { + return getLong(*status); +} +#endif /* U_HIDE_DEPRECATED_API */ + +inline UFormattable* Formattable::toUFormattable() { + return reinterpret_cast(this); +} + +inline const UFormattable* Formattable::toUFormattable() const { + return reinterpret_cast(this); +} + +inline Formattable* Formattable::fromUFormattable(UFormattable *fmt) { + return reinterpret_cast(fmt); +} + +inline const Formattable* Formattable::fromUFormattable(const UFormattable *fmt) { + return reinterpret_cast(fmt); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif //_FMTABLE +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/format.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/format.h new file mode 100644 index 0000000000000000000000000000000000000000..a21e61ad56d85cb80b7a4191a62708b7d060b105 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/format.h @@ -0,0 +1,311 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2011, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************** +* +* File FORMAT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/17/97 clhuang Updated per C++ implementation. +* 03/27/97 helena Updated to pass the simple test after code review. +******************************************************************************** +*/ +// ***************************************************************************** +// This file was generated from the java source file Format.java +// ***************************************************************************** + +#ifndef FORMAT_H +#define FORMAT_H + + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Base class for all formats. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" +#include "unicode/fmtable.h" +#include "unicode/fieldpos.h" +#include "unicode/fpositer.h" +#include "unicode/parsepos.h" +#include "unicode/parseerr.h" +#include "unicode/locid.h" + +U_NAMESPACE_BEGIN + +/** + * Base class for all formats. This is an abstract base class which + * specifies the protocol for classes which convert other objects or + * values, such as numeric values and dates, and their string + * representations. In some cases these representations may be + * localized or contain localized characters or strings. For example, + * a numeric formatter such as DecimalFormat may convert a numeric + * value such as 12345 to the string "$12,345". It may also parse + * the string back into a numeric value. A date and time formatter + * like SimpleDateFormat may represent a specific date, encoded + * numerically, as a string such as "Wednesday, February 26, 1997 AD". + *

+ * Many of the concrete subclasses of Format employ the notion of + * a pattern. A pattern is a string representation of the rules which + * govern the interconversion between values and strings. For example, + * a DecimalFormat object may be associated with the pattern + * "$#,##0.00;($#,##0.00)", which is a common US English format for + * currency values, yielding strings such as "$1,234.45" for 1234.45, + * and "($987.65)" for 987.6543. The specific syntax of a pattern + * is defined by each subclass. + *

+ * Even though many subclasses use patterns, the notion of a pattern + * is not inherent to Format classes in general, and is not part of + * the explicit base class protocol. + *

+ * Two complex formatting classes bear mentioning. These are + * MessageFormat and ChoiceFormat. ChoiceFormat is a subclass of + * NumberFormat which allows the user to format different number ranges + * as strings. For instance, 0 may be represented as "no files", 1 as + * "one file", and any number greater than 1 as "many files". + * MessageFormat is a formatter which utilizes other Format objects to + * format a string containing with multiple values. For instance, + * A MessageFormat object might produce the string "There are no files + * on the disk MyDisk on February 27, 1997." given the arguments 0, + * "MyDisk", and the date value of 2/27/97. See the ChoiceFormat + * and MessageFormat headers for further information. + *

+ * If formatting is unsuccessful, a failing UErrorCode is returned when + * the Format cannot format the type of object, otherwise if there is + * something illformed about the the Unicode replacement character + * 0xFFFD is returned. + *

+ * If there is no match when parsing, a parse failure UErrorCode is + * returned for methods which take no ParsePosition. For the method + * that takes a ParsePosition, the index parameter is left unchanged. + *

+ * User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API Format : public UObject { +public: + + /** Destructor + * @stable ICU 2.4 + */ + virtual ~Format(); + + /** + * Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @stable ICU 2.0 + */ + virtual bool operator==(const Format& other) const = 0; + + /** + * Return true if the given Format objects are not semantically + * equal. + * @param other the object to be compared with. + * @return Return true if the given Format objects are not semantically. + * @stable ICU 2.0 + */ + bool operator!=(const Format& other) const { return !operator==(other); } + + /** + * Clone this object polymorphically. The caller is responsible + * for deleting the result when done. + * @return A copy of the object + * @stable ICU 2.0 + */ + virtual Format* clone() const = 0; + + /** + * Formats an object to produce a string. + * + * @param obj The object to format. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param status Output parameter filled in with success or failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Format an object to produce a string. This is a pure virtual method which + * subclasses must implement. This method allows polymorphic formatting + * of Formattable objects. If a subclass of Format receives a Formattable + * object type it doesn't handle (e.g., if a numeric Formattable is passed + * to a DateFormat object) then it returns a failing UErrorCode. + * + * @param obj The object to format. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const = 0; + /** + * Format an object to produce a string. Subclasses should override this + * method. This method allows polymorphic formatting of Formattable objects. + * If a subclass of Format receives a Formattable object type it doesn't + * handle (e.g., if a numeric Formattable is passed to a DateFormat object) + * then it returns a failing UErrorCode. + * + * @param obj The object to format. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Parse a string to produce an object. This is a pure virtual + * method which subclasses must implement. This method allows + * polymorphic parsing of strings into Formattable objects. + *

+ * Before calling, set parse_pos.index to the offset you want to + * start parsing at in the source. After calling, parse_pos.index + * is the end of the text you parsed. If error occurs, index is + * unchanged. + *

+ * When parsing, leading whitespace is discarded (with successful + * parse), while trailing whitespace is left as is. + *

+ * Example: + *

+ * Parsing "_12_xy" (where _ represents a space) for a number, + * with index == 0 will result in the number 12, with + * parse_pos.index updated to 3 (just before the second space). + * Parsing a second time will result in a failing UErrorCode since + * "xy" is not a number, and leave index at 3. + *

+ * Subclasses will typically supply specific parse methods that + * return different types of values. Since methods can't overload + * on return types, these will typically be named "parse", while + * this polymorphic method will always be called parseObject. Any + * parse method that does not take a parse_pos should set status + * to an error value when no text in the required format is at the + * start position. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @stable ICU 2.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const = 0; + + /** + * Parses a string to produce an object. This is a convenience method + * which calls the pure virtual parseObject() method, and returns a + * failure UErrorCode if the ParsePosition indicates failure. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param status Output param to be filled with success/failure + * result code. + * @stable ICU 2.0 + */ + void parseObject(const UnicodeString& source, + Formattable& result, + UErrorCode& status) const; + + /** Get the locale for this format object. You can choose between valid and actual locale. + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale + * @stable ICU 2.8 + */ + Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; + +#ifndef U_HIDE_INTERNAL_API + /** Get the locale for this format object. You can choose between valid and actual locale. + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale + * @internal + */ + const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const; +#endif /* U_HIDE_INTERNAL_API */ + + protected: + /** @stable ICU 2.8 */ + void setLocaleIDs(const char* valid, const char* actual); + +protected: + /** + * Default constructor for subclass use only. Does nothing. + * @stable ICU 2.0 + */ + Format(); + + /** + * @stable ICU 2.0 + */ + Format(const Format&); // Does nothing; for subclasses only + + /** + * @stable ICU 2.0 + */ + Format& operator=(const Format&); // Does nothing; for subclasses + + + /** + * Simple function for initializing a UParseError from a UnicodeString. + * + * @param pattern The pattern to copy into the parseError + * @param pos The position in pattern where the error occurred + * @param parseError The UParseError object to fill in + * @stable ICU 2.4 + */ + static void syntaxError(const UnicodeString& pattern, + int32_t pos, + UParseError& parseError); + + private: + char actualLocale[ULOC_FULLNAME_CAPACITY]; + char validLocale[ULOC_FULLNAME_CAPACITY]; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _FORMAT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattednumber.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattednumber.h new file mode 100644 index 0000000000000000000000000000000000000000..198c9d84782e2e8520153cffc736a76ca490947a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattednumber.h @@ -0,0 +1,215 @@ +// © 2022 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __FORMATTEDNUMBER_H__ +#define __FORMATTEDNUMBER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" +#include "unicode/formattedvalue.h" +#include "unicode/measunit.h" +#include "unicode/udisplayoptions.h" + +/** + * \file + * \brief C API: Formatted number result from various number formatting functions. + * + * See also {@link icu::FormattedValue} for additional things you can do with a FormattedNumber. + */ + +U_NAMESPACE_BEGIN + +class FieldPositionIteratorHandler; + +namespace number { // icu::number + +namespace impl { +class DecimalQuantity; +class UFormattedNumberData; +struct UFormattedNumberImpl; +} // icu::number::impl + + + +/** + * The result of a number formatting operation. This class allows the result to be exported in several data types, + * including a UnicodeString and a FieldPositionIterator. + * + * Instances of this class are immutable and thread-safe. + * + * @stable ICU 60 + */ +class U_I18N_API FormattedNumber : public UMemory, public FormattedValue { + public: + + /** + * Default constructor; makes an empty FormattedNumber. + * @stable ICU 64 + */ + FormattedNumber() + : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} + + /** + * Move constructor: Leaves the source FormattedNumber in an undefined state. + * @stable ICU 62 + */ + FormattedNumber(FormattedNumber&& src) noexcept; + + /** + * Destruct an instance of FormattedNumber. + * @stable ICU 60 + */ + virtual ~FormattedNumber() override; + + /** Copying not supported; use move constructor instead. */ + FormattedNumber(const FormattedNumber&) = delete; + + /** Copying not supported; use move assignment instead. */ + FormattedNumber& operator=(const FormattedNumber&) = delete; + + /** + * Move assignment: Leaves the source FormattedNumber in an undefined state. + * @stable ICU 62 + */ + FormattedNumber& operator=(FormattedNumber&& src) noexcept; + + // Copybrief: this method is older than the parent method + /** + * @copybrief FormattedValue::toString() + * + * For more information, see FormattedValue::toString() + * + * @stable ICU 62 + */ + UnicodeString toString(UErrorCode& status) const override; + + // Copydoc: this method is new in ICU 64 + /** @copydoc FormattedValue::toTempString() */ + UnicodeString toTempString(UErrorCode& status) const override; + + // Copybrief: this method is older than the parent method + /** + * @copybrief FormattedValue::appendTo() + * + * For more information, see FormattedValue::appendTo() + * + * @stable ICU 62 + */ + Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override; + + // Copydoc: this method is new in ICU 64 + /** @copydoc FormattedValue::nextPosition() */ + UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; + + /** + * Export the formatted number as a "numeric string" conforming to the + * syntax defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * This endpoint is useful for obtaining the exact number being printed + * after scaling and rounding have been applied by the number formatter. + * + * Example call site: + * + * auto decimalNumber = fn.toDecimalNumber(status); + * + * @tparam StringClass A string class compatible with StringByteSink; + * for example, std::string. + * @param status Set if an error occurs. + * @return A StringClass containing the numeric string. + * @stable ICU 65 + */ + template + inline StringClass toDecimalNumber(UErrorCode& status) const; + + /** + * Gets the resolved output unit. + * + * The output unit is dependent upon the localized preferences for the usage + * specified via NumberFormatterSettings::usage(), and may be a unit with + * UMEASURE_UNIT_MIXED unit complexity (MeasureUnit::getComplexity()), such + * as "foot-and-inch" or "hour-and-minute-and-second". + * + * @return `MeasureUnit`. + * @stable ICU 68 + */ + MeasureUnit getOutputUnit(UErrorCode& status) const; + +#ifndef U_HIDE_DRAFT_API + + /** + * Gets the noun class of the formatted output. Returns `UNDEFINED` when the noun class + * is not supported yet. + * + * @return UDisplayOptionsNounClass + * @draft ICU 72 + */ + UDisplayOptionsNounClass getNounClass(UErrorCode &status) const; + +#endif // U_HIDE_DRAFT_API + +#ifndef U_HIDE_INTERNAL_API + + /** + * Gets the raw DecimalQuantity for plural rule selection. + * @internal + */ + void getDecimalQuantity(impl::DecimalQuantity& output, UErrorCode& status) const; + + /** + * Populates the mutable builder type FieldPositionIteratorHandler. + * @internal + */ + void getAllFieldPositionsImpl(FieldPositionIteratorHandler& fpih, UErrorCode& status) const; + +#endif /* U_HIDE_INTERNAL_API */ + + private: + // Can't use LocalPointer because UFormattedNumberData is forward-declared + impl::UFormattedNumberData *fData; + + // Error code for the terminal methods + UErrorCode fErrorCode; + + /** + * Internal constructor from data type. Adopts the data pointer. + * @internal (private) + */ + explicit FormattedNumber(impl::UFormattedNumberData *results) + : fData(results), fErrorCode(U_ZERO_ERROR) {} + + explicit FormattedNumber(UErrorCode errorCode) + : fData(nullptr), fErrorCode(errorCode) {} + + void toDecimalNumber(ByteSink& sink, UErrorCode& status) const; + + // To give LocalizedNumberFormatter format methods access to this class's constructor: + friend class LocalizedNumberFormatter; + friend class SimpleNumberFormatter; + + // To give C API access to internals + friend struct impl::UFormattedNumberImpl; +}; + +template +StringClass FormattedNumber::toDecimalNumber(UErrorCode& status) const { + StringClass result; + StringByteSink sink(&result); + toDecimalNumber(sink, status); + return result; +} + +} // namespace number +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __FORMATTEDNUMBER_H__ + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattedvalue.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattedvalue.h new file mode 100644 index 0000000000000000000000000000000000000000..5febea066180a01978cdbab135d22d1d62073f74 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/formattedvalue.h @@ -0,0 +1,318 @@ +// © 2018 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __FORMATTEDVALUE_H__ +#define __FORMATTEDVALUE_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/appendable.h" +#include "unicode/fpositer.h" +#include "unicode/unistr.h" +#include "unicode/uformattedvalue.h" + +U_NAMESPACE_BEGIN + +/** + * \file + * \brief C++ API: Abstract operations for localized strings. + * + * This file contains declarations for classes that deal with formatted strings. A number + * of APIs throughout ICU use these classes for expressing their localized output. + */ + +/** + * Represents a span of a string containing a given field. + * + * This class differs from FieldPosition in the following ways: + * + * 1. It has information on the field category. + * 2. It allows you to set constraints to use when iterating over field positions. + * 3. It is used for the newer FormattedValue APIs. + * + * This class is not intended for public subclassing. + * + * @stable ICU 64 + */ +class U_I18N_API ConstrainedFieldPosition : public UMemory { + public: + + /** + * Initializes a ConstrainedFieldPosition. + * + * By default, the ConstrainedFieldPosition has no iteration constraints. + * + * @stable ICU 64 + */ + ConstrainedFieldPosition(); + + /** @stable ICU 64 */ + ~ConstrainedFieldPosition(); + + /** + * Resets this ConstrainedFieldPosition to its initial state, as if it were newly created: + * + * - Removes any constraints that may have been set on the instance. + * - Resets the iteration position. + * + * @stable ICU 64 + */ + void reset(); + + /** + * Sets a constraint on the field category. + * + * When this instance of ConstrainedFieldPosition is passed to FormattedValue#nextPosition, + * positions are skipped unless they have the given category. + * + * Any previously set constraints are cleared. + * + * For example, to loop over only the number-related fields: + * + * ConstrainedFieldPosition cfpos; + * cfpos.constrainCategory(UFIELDCATEGORY_NUMBER_FORMAT); + * while (fmtval.nextPosition(cfpos, status)) { + * // handle the number-related field position + * } + * + * Changing the constraint while in the middle of iterating over a FormattedValue + * does not generally have well-defined behavior. + * + * @param category The field category to fix when iterating. + * @stable ICU 64 + */ + void constrainCategory(int32_t category); + + /** + * Sets a constraint on the category and field. + * + * When this instance of ConstrainedFieldPosition is passed to FormattedValue#nextPosition, + * positions are skipped unless they have the given category and field. + * + * Any previously set constraints are cleared. + * + * For example, to loop over all grouping separators: + * + * ConstrainedFieldPosition cfpos; + * cfpos.constrainField(UFIELDCATEGORY_NUMBER_FORMAT, UNUM_GROUPING_SEPARATOR_FIELD); + * while (fmtval.nextPosition(cfpos, status)) { + * // handle the grouping separator position + * } + * + * Changing the constraint while in the middle of iterating over a FormattedValue + * does not generally have well-defined behavior. + * + * @param category The field category to fix when iterating. + * @param field The field to fix when iterating. + * @stable ICU 64 + */ + void constrainField(int32_t category, int32_t field); + + /** + * Gets the field category for the current position. + * + * The return value is well-defined only after + * FormattedValue#nextPosition returns true. + * + * @return The field category saved in the instance. + * @stable ICU 64 + */ + inline int32_t getCategory() const { + return fCategory; + } + + /** + * Gets the field for the current position. + * + * The return value is well-defined only after + * FormattedValue#nextPosition returns true. + * + * @return The field saved in the instance. + * @stable ICU 64 + */ + inline int32_t getField() const { + return fField; + } + + /** + * Gets the INCLUSIVE start index for the current position. + * + * The return value is well-defined only after FormattedValue#nextPosition returns true. + * + * @return The start index saved in the instance. + * @stable ICU 64 + */ + inline int32_t getStart() const { + return fStart; + } + + /** + * Gets the EXCLUSIVE end index stored for the current position. + * + * The return value is well-defined only after FormattedValue#nextPosition returns true. + * + * @return The end index saved in the instance. + * @stable ICU 64 + */ + inline int32_t getLimit() const { + return fLimit; + } + + //////////////////////////////////////////////////////////////////// + //// The following methods are for FormattedValue implementers; //// + //// most users can ignore them. //// + //////////////////////////////////////////////////////////////////// + + /** + * Gets an int64 that FormattedValue implementations may use for storage. + * + * The initial value is zero. + * + * Users of FormattedValue should not need to call this method. + * + * @return The current iteration context from {@link #setInt64IterationContext}. + * @stable ICU 64 + */ + inline int64_t getInt64IterationContext() const { + return fContext; + } + + /** + * Sets an int64 that FormattedValue implementations may use for storage. + * + * Intended to be used by FormattedValue implementations. + * + * @param context The new iteration context. + * @stable ICU 64 + */ + void setInt64IterationContext(int64_t context); + + /** + * Determines whether a given field should be included given the + * constraints. + * + * Intended to be used by FormattedValue implementations. + * + * @param category The category to test. + * @param field The field to test. + * @stable ICU 64 + */ + UBool matchesField(int32_t category, int32_t field) const; + + /** + * Sets new values for the primary public getters. + * + * Intended to be used by FormattedValue implementations. + * + * It is up to the implementation to ensure that the user-requested + * constraints are satisfied. This method does not check! + * + * @param category The new field category. + * @param field The new field. + * @param start The new inclusive start index. + * @param limit The new exclusive end index. + * @stable ICU 64 + */ + void setState( + int32_t category, + int32_t field, + int32_t start, + int32_t limit); + + private: + int64_t fContext = 0LL; + int32_t fField = 0; + int32_t fStart = 0; + int32_t fLimit = 0; + int32_t fCategory = UFIELD_CATEGORY_UNDEFINED; + int8_t fConstraint = 0; +}; + +/** + * An abstract formatted value: a string with associated field attributes. + * Many formatters format to classes implementing FormattedValue. + * + * @stable ICU 64 + */ +class U_I18N_API FormattedValue /* not : public UObject because this is an interface/mixin class */ { + public: + /** @stable ICU 64 */ + virtual ~FormattedValue(); + + /** + * Returns the formatted string as a self-contained UnicodeString. + * + * If you need the string within the current scope only, consider #toTempString. + * + * @param status Set if an error occurs. + * @return a UnicodeString containing the formatted string. + * + * @stable ICU 64 + */ + virtual UnicodeString toString(UErrorCode& status) const = 0; + + /** + * Returns the formatted string as a read-only alias to memory owned by the FormattedValue. + * + * The return value is valid only as long as this FormattedValue is present and unchanged in + * memory. If you need the string outside the current scope, consider #toString. + * + * The buffer returned by calling UnicodeString#getBuffer() on the return value is + * guaranteed to be NUL-terminated. + * + * @param status Set if an error occurs. + * @return a temporary UnicodeString containing the formatted string. + * + * @stable ICU 64 + */ + virtual UnicodeString toTempString(UErrorCode& status) const = 0; + + /** + * Appends the formatted string to an Appendable. + * + * @param appendable + * The Appendable to which to append the string output. + * @param status Set if an error occurs. + * @return The same Appendable, for chaining. + * + * @stable ICU 64 + * @see Appendable + */ + virtual Appendable& appendTo(Appendable& appendable, UErrorCode& status) const = 0; + + /** + * Iterates over field positions in the FormattedValue. This lets you determine the position + * of specific types of substrings, like a month or a decimal separator. + * + * To loop over all field positions: + * + * ConstrainedFieldPosition cfpos; + * while (fmtval.nextPosition(cfpos, status)) { + * // handle the field position; get information from cfpos + * } + * + * @param cfpos + * The object used for iteration state. This can provide constraints to iterate over + * only one specific category or field; + * see ConstrainedFieldPosition#constrainCategory + * and ConstrainedFieldPosition#constrainField. + * @param status Set if an error occurs. + * @return true if a new occurrence of the field was found; + * false otherwise or if an error was set. + * + * @stable ICU 64 + */ + virtual UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const = 0; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __FORMATTEDVALUE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fpositer.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fpositer.h new file mode 100644 index 0000000000000000000000000000000000000000..0e38d0b78b3a485661798fef55158b98c57baa98 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/fpositer.h @@ -0,0 +1,124 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 2010-2012, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************** +* +* File attiter.h +* +* Modification History: +* +* Date Name Description +* 12/15/2009 dougfelt Created +******************************************************************************** +*/ + +#ifndef FPOSITER_H +#define FPOSITER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: FieldPosition Iterator. + */ + +#if UCONFIG_NO_FORMATTING + +U_NAMESPACE_BEGIN + +/* + * Allow the declaration of APIs with pointers to FieldPositionIterator + * even when formatting is removed from the build. + */ +class FieldPositionIterator; + +U_NAMESPACE_END + +#else + +#include "unicode/fieldpos.h" +#include "unicode/umisc.h" + +U_NAMESPACE_BEGIN + +class UVector32; + +/** + * FieldPositionIterator returns the field ids and their start/limit positions generated + * by a call to Format::format. See Format, NumberFormat, DecimalFormat. + * @stable ICU 4.4 + */ +class U_I18N_API FieldPositionIterator : public UObject { +public: + /** + * Destructor. + * @stable ICU 4.4 + */ + ~FieldPositionIterator(); + + /** + * Constructs a new, empty iterator. + * @stable ICU 4.4 + */ + FieldPositionIterator(void); + + /** + * Copy constructor. If the copy failed for some reason, the new iterator will + * be empty. + * @stable ICU 4.4 + */ + FieldPositionIterator(const FieldPositionIterator&); + + /** + * Return true if another object is semantically equal to this + * one. + *

+ * Return true if this FieldPositionIterator is at the same position in an + * equal array of run values. + * @stable ICU 4.4 + */ + bool operator==(const FieldPositionIterator&) const; + + /** + * Returns the complement of the result of operator== + * @param rhs The FieldPositionIterator to be compared for inequality + * @return the complement of the result of operator== + * @stable ICU 4.4 + */ + bool operator!=(const FieldPositionIterator& rhs) const { return !operator==(rhs); } + + /** + * If the current position is valid, updates the FieldPosition values, advances the iterator, + * and returns true, otherwise returns false. + * @stable ICU 4.4 + */ + UBool next(FieldPosition& fp); + +private: + /** + * Sets the data used by the iterator, and resets the position. + * Returns U_ILLEGAL_ARGUMENT_ERROR in status if the data is not valid + * (length is not a multiple of 3, or start >= limit for any run). + */ + void setData(UVector32 *adopt, UErrorCode& status); + + friend class FieldPositionIteratorHandler; + + UVector32 *data; + int32_t pos; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // FPOSITER_H diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gender.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gender.h new file mode 100644 index 0000000000000000000000000000000000000000..c81f7c88cc4f1bcfc131d5ea0587963a545eb7df --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gender.h @@ -0,0 +1,122 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2008-2013, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* +* File GENDER.H +* +* Modification History:* +* Date Name Description +* +******************************************************************************** +*/ + +#ifndef _GENDER +#define _GENDER + +/** + * \file + * \brief C++ API: GenderInfo computes the gender of a list. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/locid.h" +#include "unicode/ugender.h" +#include "unicode/uobject.h" + +class GenderInfoTest; + +U_NAMESPACE_BEGIN + +/** \internal Forward Declaration */ +void U_CALLCONV GenderInfo_initCache(UErrorCode &status); + +/** + * GenderInfo computes the gender of a list as a whole given the gender of + * each element. + * @stable ICU 50 + */ +class U_I18N_API GenderInfo : public UObject { +public: + + /** + * Provides access to the predefined GenderInfo object for a given + * locale. + * + * @param locale The locale for which a GenderInfo object is + * returned. + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return The predefined GenderInfo object pointer for + * this locale. The returned object is immutable, so it is + * declared as const. Caller does not own the returned + * pointer, so it must not attempt to free it. + * @stable ICU 50 + */ + static const GenderInfo* U_EXPORT2 getInstance(const Locale& locale, UErrorCode& status); + + /** + * Determines the gender of a list as a whole given the gender of each + * of the elements. + * + * @param genders the gender of each element in the list. + * @param length the length of gender array. + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return the gender of the whole list. + * @stable ICU 50 + */ + UGender getListGender(const UGender* genders, int32_t length, UErrorCode& status) const; + + /** + * Destructor. + * + * @stable ICU 50 + */ + virtual ~GenderInfo(); + +private: + int32_t _style; + + /** + * Copy constructor. One object per locale invariant. Clients + * must never copy GenderInfo objects. + */ + GenderInfo(const GenderInfo& other) = delete; + + /** + * Assignment operator. Not applicable to immutable objects. + */ + GenderInfo& operator=(const GenderInfo&) = delete; + + GenderInfo(); + + static const GenderInfo* getNeutralInstance(); + + static const GenderInfo* getMixedNeutralInstance(); + + static const GenderInfo* getMaleTaintsInstance(); + + static const GenderInfo* loadInstance(const Locale& locale, UErrorCode& status); + + friend class ::GenderInfoTest; + friend void U_CALLCONV GenderInfo_initCache(UErrorCode &status); +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _GENDER +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gregocal.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gregocal.h new file mode 100644 index 0000000000000000000000000000000000000000..b85deb5ecfbb962db29cecfa680b232d15045826 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/gregocal.h @@ -0,0 +1,755 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +* Copyright (C) 1997-2013, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************** +* +* File GREGOCAL.H +* +* Modification History: +* +* Date Name Description +* 04/22/97 aliu Overhauled header. +* 07/28/98 stephen Sync with JDK 1.2 +* 09/04/98 stephen Re-sync with JDK 8/31 putback +* 09/14/98 stephen Changed type of kOneDay, kOneWeek to double. +* Fixed bug in roll() +* 10/15/99 aliu Fixed j31, incorrect WEEK_OF_YEAR computation. +* Added documentation of WEEK_OF_YEAR computation. +* 10/15/99 aliu Fixed j32, cannot set date to Feb 29 2000 AD. +* {JDK bug 4210209 4209272} +* 11/07/2003 srl Update, clean up documentation. +******************************************************************************** +*/ + +#ifndef GREGOCAL_H +#define GREGOCAL_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/calendar.h" + +/** + * \file + * \brief C++ API: Concrete class which provides the standard calendar. + */ + +U_NAMESPACE_BEGIN + +/** + * Concrete class which provides the standard calendar used by most of the world. + *

+ * The standard (Gregorian) calendar has 2 eras, BC and AD. + *

+ * This implementation handles a single discontinuity, which corresponds by default to + * the date the Gregorian calendar was originally instituted (October 15, 1582). Not all + * countries adopted the Gregorian calendar then, so this cutover date may be changed by + * the caller. + *

+ * Prior to the institution of the Gregorian Calendar, New Year's Day was March 25. To + * avoid confusion, this Calendar always uses January 1. A manual adjustment may be made + * if desired for dates that are prior to the Gregorian changeover and which fall + * between January 1 and March 24. + * + *

Values calculated for the WEEK_OF_YEAR field range from 1 to + * 53. Week 1 for a year is the first week that contains at least + * getMinimalDaysInFirstWeek() days from that year. It thus + * depends on the values of getMinimalDaysInFirstWeek(), + * getFirstDayOfWeek(), and the day of the week of January 1. + * Weeks between week 1 of one year and week 1 of the following year are + * numbered sequentially from 2 to 52 or 53 (as needed). + * + *

For example, January 1, 1998 was a Thursday. If + * getFirstDayOfWeek() is MONDAY and + * getMinimalDaysInFirstWeek() is 4 (these are the values + * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts + * on December 29, 1997, and ends on January 4, 1998. If, however, + * getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 + * starts on January 4, 1998, and ends on January 10, 1998; the first three days + * of 1998 then are part of week 53 of 1997. + * + *

Example for using GregorianCalendar: + *

+ * \code
+ *     // get the supported ids for GMT-08:00 (Pacific Standard Time)
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     const StringEnumeration *ids = TimeZone::createEnumeration(-8 * 60 * 60 * 1000, success);
+ *     // if no ids were returned, something is wrong. get out.
+ *     if (U_FAILURE(success)) {
+ *         return;
+ *     }
+ *
+ *     // begin output
+ *     cout << "Current Time" << endl;
+ *
+ *     // create a Pacific Standard Time time zone
+ *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids->unext(nullptr, success)));
+ *
+ *     // set up rules for daylight savings time
+ *     pdt->setStartRule(UCAL_MARCH, 1, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
+ *     pdt->setEndRule(UCAL_NOVEMBER, 2, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
+ *
+ *     // create a GregorianCalendar with the Pacific Daylight time zone
+ *     // and the current date and time
+ *     Calendar* calendar = new GregorianCalendar( pdt, success );
+ *
+ *     // print out a bunch of interesting things
+ *     cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
+ *     cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
+ *     cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
+ *     cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
+ *     cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
+ *     cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
+ *     cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
+ *     cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
+ *     cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
+ *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
+ *     cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
+ *     cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
+ *     cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
+ *     cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
+ *     cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
+ *     cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
+ *     cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl;
+ *     cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl;
+ *
+ *     cout << "Current Time, with hour reset to 3" << endl;
+ *     calendar->clear(UCAL_HOUR_OF_DAY); // so doesn't override
+ *     calendar->set(UCAL_HOUR, 3);
+ *     cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
+ *     cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
+ *     cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
+ *     cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
+ *     cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
+ *     cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
+ *     cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
+ *     cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
+ *     cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
+ *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
+ *     cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
+ *     cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
+ *     cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
+ *     cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
+ *     cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
+ *     cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
+ *     cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl; // in hours
+ *     cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl; // in hours
+ *
+ *     if (U_FAILURE(success)) {
+ *         cout << "An error occurred. success=" << u_errorName(success) << endl;
+ *     }
+ *
+ *     delete ids;
+ *     delete calendar; // also deletes pdt
+ * \endcode
+ * 
+ * @stable ICU 2.0 + */ +class U_I18N_API GregorianCalendar: public Calendar { +public: + + /** + * Useful constants for GregorianCalendar and TimeZone. + * @stable ICU 2.0 + */ + enum EEras { + BC, + AD + }; + + /** + * Constructs a default GregorianCalendar using the current time in the default time + * zone with the default locale. + * + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(UErrorCode& success); + + /** + * Constructs a GregorianCalendar based on the current time in the given time zone + * with the default locale. Clients are no longer responsible for deleting the given + * time zone object after it's adopted. + * + * @param zoneToAdopt The given timezone. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(TimeZone* zoneToAdopt, UErrorCode& success); + + /** + * Constructs a GregorianCalendar based on the current time in the given time zone + * with the default locale. + * + * @param zone The given timezone. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(const TimeZone& zone, UErrorCode& success); + + /** + * Constructs a GregorianCalendar based on the current time in the default time zone + * with the given locale. + * + * @param aLocale The given locale. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(const Locale& aLocale, UErrorCode& success); + + /** + * Constructs a GregorianCalendar based on the current time in the given time zone + * with the given locale. Clients are no longer responsible for deleting the given + * time zone object after it's adopted. + * + * @param zoneToAdopt The given timezone. + * @param aLocale The given locale. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success); + + /** + * Constructs a GregorianCalendar based on the current time in the given time zone + * with the given locale. + * + * @param zone The given timezone. + * @param aLocale The given locale. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); + + /** + * Constructs a GregorianCalendar with the given AD date set in the default time + * zone with the default locale. + * + * @param year The value used to set the YEAR time field in the calendar. + * @param month The value used to set the MONTH time field in the calendar. Month + * value is 0-based. e.g., 0 for January. + * @param date The value used to set the DATE time field in the calendar. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& success); + + /** + * Constructs a GregorianCalendar with the given AD date and time set for the + * default time zone with the default locale. + * + * @param year The value used to set the YEAR time field in the calendar. + * @param month The value used to set the MONTH time field in the calendar. Month + * value is 0-based. e.g., 0 for January. + * @param date The value used to set the DATE time field in the calendar. + * @param hour The value used to set the HOUR_OF_DAY time field in the calendar. + * @param minute The value used to set the MINUTE time field in the calendar. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& success); + + /** + * Constructs a GregorianCalendar with the given AD date and time set for the + * default time zone with the default locale. + * + * @param year The value used to set the YEAR time field in the calendar. + * @param month The value used to set the MONTH time field in the calendar. Month + * value is 0-based. e.g., 0 for January. + * @param date The value used to set the DATE time field in the calendar. + * @param hour The value used to set the HOUR_OF_DAY time field in the calendar. + * @param minute The value used to set the MINUTE time field in the calendar. + * @param second The value used to set the SECOND time field in the calendar. + * @param success Indicates the status of GregorianCalendar object construction. + * Returns U_ZERO_ERROR if constructed successfully. + * @stable ICU 2.0 + */ + GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& success); + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~GregorianCalendar(); + + /** + * Copy constructor + * @param source the object to be copied. + * @stable ICU 2.0 + */ + GregorianCalendar(const GregorianCalendar& source); + + /** + * Default assignment operator + * @param right the object to be copied. + * @stable ICU 2.0 + */ + GregorianCalendar& operator=(const GregorianCalendar& right); + + /** + * Create and return a polymorphic copy of this calendar. + * @return return a polymorphic copy of this calendar. + * @stable ICU 2.0 + */ + virtual GregorianCalendar* clone() const override; + + /** + * Sets the GregorianCalendar change date. This is the point when the switch from + * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October + * 15, 1582. Previous to this time and date will be Julian dates. + * + * @param date The given Gregorian cutover date. + * @param success Output param set to success/failure code on exit. + * @stable ICU 2.0 + */ + void setGregorianChange(UDate date, UErrorCode& success); + + /** + * Gets the Gregorian Calendar change date. This is the point when the switch from + * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October + * 15, 1582. Previous to this time and date will be Julian dates. + * + * @return The Gregorian cutover time for this calendar. + * @stable ICU 2.0 + */ + UDate getGregorianChange(void) const; + + /** + * Return true if the given year is a leap year. Determination of whether a year is + * a leap year is actually very complicated. We do something crude and mostly + * correct here, but for a real determination you need a lot of contextual + * information. For example, in Sweden, the change from Julian to Gregorian happened + * in a complex way resulting in missed leap years and double leap years between + * 1700 and 1753. Another example is that after the start of the Julian calendar in + * 45 B.C., the leap years did not regularize until 8 A.D. This method ignores these + * quirks, and pays attention only to the Julian onset date and the Gregorian + * cutover (which can be changed). + * + * @param year The given year. + * @return True if the given year is a leap year; false otherwise. + * @stable ICU 2.0 + */ + UBool isLeapYear(int32_t year) const; + + /** + * Returns true if the given Calendar object is equivalent to this + * one. Calendar override. + * + * @param other the Calendar to be compared with this Calendar + * @stable ICU 2.4 + */ + virtual UBool isEquivalentTo(const Calendar& other) const override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * (Overrides Calendar) Rolls up or down by the given amount in the specified field. + * For more information, see the documentation for Calendar::roll(). + * + * @param field The time field. + * @param amount Indicates amount to roll. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. + */ + virtual void roll(EDateFields field, int32_t amount, UErrorCode& status) override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * (Overrides Calendar) Rolls up or down by the given amount in the specified field. + * For more information, see the documentation for Calendar::roll(). + * + * @param field The time field. + * @param amount Indicates amount to roll. + * @param status Output param set to success/failure code on exit. If any value + * previously set in the time field is invalid, this will be set to + * an error status. + * @stable ICU 2.6. + */ + virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) override; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Return the minimum value that this field could have, given the current date. + * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). + * @param field the time field. + * @return the minimum value that this field could have, given the current date. + * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. + */ + int32_t getActualMinimum(EDateFields field) const; + + /** + * Return the minimum value that this field could have, given the current date. + * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). + * @param field the time field. + * @param status + * @return the minimum value that this field could have, given the current date. + * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. (Added to ICU 3.0 for signature consistency) + */ + int32_t getActualMinimum(EDateFields field, UErrorCode& status) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Return the minimum value that this field could have, given the current date. + * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). + * @param field the time field. + * @param status error result. + * @return the minimum value that this field could have, given the current date. + * @stable ICU 3.0 + */ + int32_t getActualMinimum(UCalendarDateFields field, UErrorCode &status) const override; + + /** + * Return the maximum value that this field could have, given the current date. + * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual + * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, + * for some years the actual maximum for MONTH is 12, and for others 13. + * @param field the time field. + * @param status returns any errors that may result from this function call. + * @return the maximum value that this field could have, given the current date. + * @stable ICU 2.6 + */ + virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const override; + +public: + + /** + * Override Calendar Returns a unique class ID POLYMORPHICALLY. Pure virtual + * override. This method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call + * this method. + * + * @return The class ID for this object. All objects of a given class have the + * same class ID. Objects of other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Return the class ID for this class. This is useful only for comparing to a return + * value from getDynamicClassID(). For example: + * + * Base* polymorphic_pointer = createPolymorphicObject(); + * if (polymorphic_pointer->getDynamicClassID() == + * Derived::getStaticClassID()) ... + * + * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns the calendar type name string for this Calendar object. + * The returned string is the legacy ICU calendar attribute value, + * for example, "gregorian" or "japanese". + * + * For more details see the Calendar::getType() documentation. + * + * @return legacy calendar type name string + * @stable ICU 49 + */ + virtual const char * getType() const override; + + private: + GregorianCalendar() = delete; // default constructor not implemented + + protected: + /** + * Return the ERA. We need a special method for this because the + * default ERA is AD, but a zero (unset) ERA is BC. + * @return the ERA. + * @internal + */ + virtual int32_t internalGetEra() const; + + /** + * Return the Julian day number of day before the first day of the + * given month in the given extended year. Subclasses should override + * this method to implement their calendar system. + * @param eyear the extended year + * @param month the zero-based month, or 0 if useMonth is false + * @param useMonth if false, compute the day before the first day of + * the given year, otherwise, compute the day before the first day of + * the given month + * @return the Julian day number of the day before the first + * day of the given month and year + * @internal + */ + virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, + UBool useMonth) const override; + + /** + * Subclasses may override this. This method calls + * handleGetMonthLength() to obtain the calendar-specific month + * length. + * @param bestField which field to use to calculate the date + * @return julian day specified by calendar fields. + * @internal + */ + virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField) override; + + /** + * Return the number of days in the given month of the given extended + * year of this calendar system. Subclasses should override this + * method if they can provide a more correct or more efficient + * implementation than the default implementation in Calendar. + * @internal + */ + virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const override; + + /** + * Return the number of days in the given extended year of this + * calendar system. Subclasses should override this method if they can + * provide a more correct or more efficient implementation than the + * default implementation in Calendar. + * @stable ICU 2.0 + */ + virtual int32_t handleGetYearLength(int32_t eyear) const override; + + /** + * return the length of the given month. + * @param month the given month. + * @return the length of the given month. + * @internal + */ + virtual int32_t monthLength(int32_t month) const; + + /** + * return the length of the month according to the given year. + * @param month the given month. + * @param year the given year. + * @return the length of the month + * @internal + */ + virtual int32_t monthLength(int32_t month, int32_t year) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * return the length of the given year. + * @param year the given year. + * @return the length of the given year. + * @internal + */ + int32_t yearLength(int32_t year) const; + + /** + * return the length of the year field. + * @return the length of the year field + * @internal + */ + int32_t yearLength(void) const; + + /** + * After adjustments such as add(MONTH), add(YEAR), we don't want the + * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar + * 3, we want it to go to Feb 28. Adjustments which might run into this + * problem call this method to retain the proper month. + * @internal + */ + void pinDayOfMonth(void); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Return the day number with respect to the epoch. January 1, 1970 (Gregorian) + * is day zero. + * @param status Fill-in parameter which receives the status of this operation. + * @return the day number with respect to the epoch. + * @internal + */ + virtual UDate getEpochDay(UErrorCode& status); + + /** + * Subclass API for defining limits of different types. + * Subclasses must implement this method to return limits for the + * following fields: + * + *
UCAL_ERA
+     * UCAL_YEAR
+     * UCAL_MONTH
+     * UCAL_WEEK_OF_YEAR
+     * UCAL_WEEK_OF_MONTH
+     * UCAL_DATE (DAY_OF_MONTH on Java)
+     * UCAL_DAY_OF_YEAR
+     * UCAL_DAY_OF_WEEK_IN_MONTH
+     * UCAL_YEAR_WOY
+     * UCAL_EXTENDED_YEAR
+ * + * @param field one of the above field numbers + * @param limitType one of MINIMUM, GREATEST_MINIMUM, + * LEAST_MAXIMUM, or MAXIMUM + * @internal + */ + virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const override; + + /** + * Return the extended year defined by the current fields. This will + * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such + * as UCAL_ERA) specific to the calendar system, depending on which set of + * fields is newer. + * @return the extended year + * @internal + */ + virtual int32_t handleGetExtendedYear() override; + + /** + * Subclasses may override this to convert from week fields + * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case + * where YEAR, EXTENDED_YEAR are not set. + * The Gregorian implementation assumes a yearWoy in gregorian format, according to the current era. + * @return the extended year, UCAL_EXTENDED_YEAR + * @internal + */ + virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy) override; + + + /** + * Subclasses may override this method to compute several fields + * specific to each calendar system. These are: + * + *
  • ERA + *
  • YEAR + *
  • MONTH + *
  • DAY_OF_MONTH + *
  • DAY_OF_YEAR + *
  • EXTENDED_YEAR
+ * + *

The GregorianCalendar implementation implements + * a calendar with the specified Julian/Gregorian cutover date. + * @internal + */ + virtual void handleComputeFields(int32_t julianDay, UErrorCode &status) override; + + private: + /** + * Compute the julian day number of the given year. + * @param isGregorian if true, using Gregorian calendar, otherwise using Julian calendar + * @param year the given year. + * @param isLeap true if the year is a leap year. + * @return + */ + static double computeJulianDayOfYear(UBool isGregorian, int32_t year, + UBool& isLeap); + + /** + * Validates the values of the set time fields. True if they're all valid. + * @return True if the set time fields are all valid. + */ + UBool validateFields(void) const; + + /** + * Validates the value of the given time field. True if it's valid. + */ + UBool boundsCheck(int32_t value, UCalendarDateFields field) const; + + /** + * Return the pseudo-time-stamp for two fields, given their + * individual pseudo-time-stamps. If either of the fields + * is unset, then the aggregate is unset. Otherwise, the + * aggregate is the later of the two stamps. + * @param stamp_a One given field. + * @param stamp_b Another given field. + * @return the pseudo-time-stamp for two fields + */ + int32_t aggregateStamp(int32_t stamp_a, int32_t stamp_b); + + /** + * The point at which the Gregorian calendar rules are used, measured in + * milliseconds from the standard epoch. Default is October 15, 1582 + * (Gregorian) 00:00:00 UTC, that is, October 4, 1582 (Julian) is followed + * by October 15, 1582 (Gregorian). This corresponds to Julian day number + * 2299161. This is measured from the standard epoch, not in Julian Days. + */ + UDate fGregorianCutover; + + /** + * Julian day number of the Gregorian cutover + */ + int32_t fCutoverJulianDay; + + /** + * Midnight, local time (using this Calendar's TimeZone) at or before the + * gregorianCutover. This is a pure date value with no time of day or + * timezone component. + */ + UDate fNormalizedGregorianCutover;// = gregorianCutover; + + /** + * The year of the gregorianCutover, with 0 representing + * 1 BC, -1 representing 2 BC, etc. + */ + int32_t fGregorianCutoverYear;// = 1582; + + /** + * Converts time as milliseconds to Julian date. The Julian date used here is not a + * true Julian date, since it is measured from midnight, not noon. + * + * @param millis The given milliseconds. + * @return The Julian date number. + */ + static double millisToJulianDay(UDate millis); + + /** + * Converts Julian date to time as milliseconds. The Julian date used here is not a + * true Julian date, since it is measured from midnight, not noon. + * + * @param julian The given Julian date number. + * @return Time as milliseconds. + */ + static UDate julianDayToMillis(double julian); + + /** + * Used by handleComputeJulianDay() and handleComputeMonthStart(). + * Temporary field indicating whether the calendar is currently Gregorian as opposed to Julian. + */ + UBool fIsGregorian; + + /** + * Used by handleComputeJulianDay() and handleComputeMonthStart(). + * Temporary field indicating that the sense of the gregorian cutover should be inverted + * to handle certain calculations on and around the cutover date. + */ + UBool fInvertGregorian; + + + public: // internal implementation + + /** + * @return true if this calendar has the notion of a default century + * @internal + */ + virtual UBool haveDefaultCentury() const override; + + /** + * @return the start of the default century + * @internal + */ + virtual UDate defaultCenturyStart() const override; + + /** + * @return the beginning year of the default century + * @internal + */ + virtual int32_t defaultCenturyStartYear() const override; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _GREGOCAL +//eof + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icudataver.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icudataver.h new file mode 100644 index 0000000000000000000000000000000000000000..f218ed8ebccbcba8c0c5b721dd4c466ca43fa1f6 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icudataver.h @@ -0,0 +1,43 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 2009-2013, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +*/ + + +/** + * \file + * \brief C API: access to ICU Data Version number + */ + +#ifndef __ICU_DATA_VER_H__ +#define __ICU_DATA_VER_H__ + +#include "unicode/utypes.h" + +/** + * @stable ICU 49 + */ +#define U_ICU_VERSION_BUNDLE "icuver" + +/** + * @stable ICU 49 + */ +#define U_ICU_DATA_KEY "DataVersion" + +/** + * Retrieves the data version from icuver and stores it in dataVersionFillin. + * + * @param dataVersionFillin icuver data version information to be filled in if not-null + * @param status stores the error code from the calls to resource bundle + * + * @stable ICU 49 + */ +U_CAPI void U_EXPORT2 u_getDataVersion(UVersionInfo dataVersionFillin, UErrorCode *status); + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icuplug.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icuplug.h new file mode 100644 index 0000000000000000000000000000000000000000..c787fcd426643e42b904570971273344c6fb545c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/icuplug.h @@ -0,0 +1,391 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 2009-2015, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* FILE NAME : icuplug.h +* +* Date Name Description +* 10/29/2009 sl New. +****************************************************************************** +*/ + +/** + * \file + * \brief C API: ICU Plugin API + * + *

C API: ICU Plugin API

+ * + *

C API allowing run-time loadable modules that extend or modify ICU functionality.

+ * + *

Loading and Configuration

+ * + *

At ICU startup time, the environment variable "ICU_PLUGINS" will be + * queried for a directory name. If it is not set, the preprocessor symbol + * "DEFAULT_ICU_PLUGINS" will be checked for a default value.

+ * + *

Within the above-named directory, the file "icuplugins##.txt" will be + * opened, if present, where ## is the major+minor number of the currently + * running ICU (such as, 44 for ICU 4.4, thus icuplugins44.txt)

+ * + *

The configuration file has this format:

+ * + *
    + *
  • Hash (#) begins a comment line
  • + * + *
  • Non-comment lines have two or three components: + * LIBRARYNAME ENTRYPOINT [ CONFIGURATION .. ]
  • + * + *
  • Tabs or spaces separate the three items.
  • + * + *
  • LIBRARYNAME is the name of a shared library, either a short name if + * it is on the loader path, or a full pathname.
  • + * + *
  • ENTRYPOINT is the short (undecorated) symbol name of the plugin's + * entrypoint, as above.
  • + * + *
  • CONFIGURATION is the entire rest of the line . It's passed as-is to + * the plugin.
  • + *
+ * + *

An example configuration file is, in its entirety:

+ * + * \code + * # this is icuplugins44.txt + * testplug.dll myPlugin hello=world + * \endcode + *

Plugins are categorized as "high" or "low" level. Low level are those + * which must be run BEFORE high level plugins, and before any operations + * which cause ICU to be 'initialized'. If a plugin is low level but + * causes ICU to allocate memory or become initialized, that plugin is said + * to cause a 'level change'.

+ * + *

At load time, ICU first queries all plugins to determine their level, + * then loads all 'low' plugins first, and then loads all 'high' plugins. + * Plugins are otherwise loaded in the order listed in the configuration file.

+ * + *

Implementing a Plugin

+ * \code + * U_CAPI UPlugTokenReturn U_EXPORT2 + * myPlugin (UPlugData *plug, UPlugReason reason, UErrorCode *status) { + * if(reason==UPLUG_REASON_QUERY) { + * uplug_setPlugName(plug, "Simple Plugin"); + * uplug_setPlugLevel(plug, UPLUG_LEVEL_HIGH); + * } else if(reason==UPLUG_REASON_LOAD) { + * ... Set up some ICU things here.... + * } else if(reason==UPLUG_REASON_UNLOAD) { + * ... unload, clean up ... + * } + * return UPLUG_TOKEN; + * } + * \endcode + * + *

The UPlugData* is an opaque pointer to the plugin-specific data, and is + * used in all other API calls.

+ * + *

The API contract is:

+ *
  1. The plugin MUST always return UPLUG_TOKEN as a return value- to + * indicate that it is a valid plugin.
  2. + * + *
  3. When the 'reason' parameter is set to UPLUG_REASON_QUERY, the + * plugin MUST call uplug_setPlugLevel() to indicate whether it is a high + * level or low level plugin.
  4. + * + *
  5. When the 'reason' parameter is UPLUG_REASON_QUERY, the plugin + * SHOULD call uplug_setPlugName to indicate a human readable plugin name.
+ * + * + * \internal ICU 4.4 Technology Preview + */ + + +#ifndef ICUPLUG_H +#define ICUPLUG_H + +#include "unicode/utypes.h" + + +#if UCONFIG_ENABLE_PLUGINS || defined(U_IN_DOXYGEN) + + + +/* === Basic types === */ + +#ifndef U_HIDE_INTERNAL_API +struct UPlugData; +/** + * @{ + * Typedef for opaque structure passed to/from a plugin. + * Use the APIs to access it. + * @internal ICU 4.4 Technology Preview + */ +typedef struct UPlugData UPlugData; + +/** @} */ + +/** + * Random Token to identify a valid ICU plugin. Plugins must return this + * from the entrypoint. + * @internal ICU 4.4 Technology Preview + */ +#define UPLUG_TOKEN 0x54762486 + +/** + * Max width of names, symbols, and configuration strings + * @internal ICU 4.4 Technology Preview + */ +#define UPLUG_NAME_MAX 100 + + +/** + * Return value from a plugin entrypoint. + * Must always be set to UPLUG_TOKEN + * @see UPLUG_TOKEN + * @internal ICU 4.4 Technology Preview + */ +typedef uint32_t UPlugTokenReturn; + +/** + * Reason code for the entrypoint's call + * @internal ICU 4.4 Technology Preview + */ +typedef enum { + UPLUG_REASON_QUERY = 0, /**< The plugin is being queried for info. **/ + UPLUG_REASON_LOAD = 1, /**< The plugin is being loaded. **/ + UPLUG_REASON_UNLOAD = 2, /**< The plugin is being unloaded. **/ + /** + * Number of known reasons. + * @internal The numeric value may change over time, see ICU ticket #12420. + */ + UPLUG_REASON_COUNT +} UPlugReason; + + +/** + * Level of plugin loading + * INITIAL: UNKNOWN + * QUERY: INVALID -> { LOW | HIGH } + * ERR -> INVALID + * @internal ICU 4.4 Technology Preview + */ +typedef enum { + UPLUG_LEVEL_INVALID = 0, /**< The plugin is invalid, hasn't called uplug_setLevel, or can't load. **/ + UPLUG_LEVEL_UNKNOWN = 1, /**< The plugin is waiting to be installed. **/ + UPLUG_LEVEL_LOW = 2, /**< The plugin must be called before u_init completes **/ + UPLUG_LEVEL_HIGH = 3, /**< The plugin can run at any time. **/ + /** + * Number of known levels. + * @internal The numeric value may change over time, see ICU ticket #12420. + */ + UPLUG_LEVEL_COUNT +} UPlugLevel; + +/** + * Entrypoint for an ICU plugin. + * @param plug the UPlugData handle. + * @param reason the reason code for the entrypoint's call. + * @param status Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return A valid plugin must return UPLUG_TOKEN + * @internal ICU 4.4 Technology Preview + */ +typedef UPlugTokenReturn (U_EXPORT2 UPlugEntrypoint) ( + UPlugData *plug, + UPlugReason reason, + UErrorCode *status); + +/* === Needed for Implementing === */ + +/** + * Request that this plugin not be unloaded at cleanup time. + * This is appropriate for plugins which cannot be cleaned up. + * @see u_cleanup() + * @param plug plugin + * @param dontUnload set true if this plugin can't be unloaded + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void U_EXPORT2 +uplug_setPlugNoUnload(UPlugData *plug, UBool dontUnload); + +/** + * Set the level of this plugin. + * @param plug plugin data handle + * @param level the level of this plugin + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void U_EXPORT2 +uplug_setPlugLevel(UPlugData *plug, UPlugLevel level); + +/** + * Get the level of this plugin. + * @param plug plugin data handle + * @return the level of this plugin + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UPlugLevel U_EXPORT2 +uplug_getPlugLevel(UPlugData *plug); + +/** + * Get the lowest level of plug which can currently load. + * For example, if UPLUG_LEVEL_LOW is returned, then low level plugins may load + * if UPLUG_LEVEL_HIGH is returned, then only high level plugins may load. + * @return the lowest level of plug which can currently load + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UPlugLevel U_EXPORT2 +uplug_getCurrentLevel(void); + + +/** + * Get plug load status + * @return The error code of this plugin's load attempt. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UErrorCode U_EXPORT2 +uplug_getPlugLoadStatus(UPlugData *plug); + +/** + * Set the human-readable name of this plugin. + * @param plug plugin data handle + * @param name the name of this plugin. The first UPLUG_NAME_MAX characters willi be copied into a new buffer. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void U_EXPORT2 +uplug_setPlugName(UPlugData *plug, const char *name); + +/** + * Get the human-readable name of this plugin. + * @param plug plugin data handle + * @return the name of this plugin + * @internal ICU 4.4 Technology Preview + */ +U_CAPI const char * U_EXPORT2 +uplug_getPlugName(UPlugData *plug); + +/** + * Return the symbol name for this plugin, if known. + * @param plug plugin data handle + * @return the symbol name, or NULL + * @internal ICU 4.4 Technology Preview + */ +U_CAPI const char * U_EXPORT2 +uplug_getSymbolName(UPlugData *plug); + +/** + * Return the library name for this plugin, if known. + * @param plug plugin data handle + * @param status error code + * @return the library name, or NULL + * @internal ICU 4.4 Technology Preview + */ +U_CAPI const char * U_EXPORT2 +uplug_getLibraryName(UPlugData *plug, UErrorCode *status); + +/** + * Return the library used for this plugin, if known. + * Plugins could use this to load data out of their + * @param plug plugin data handle + * @return the library, or NULL + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void * U_EXPORT2 +uplug_getLibrary(UPlugData *plug); + +/** + * Return the plugin-specific context data. + * @param plug plugin data handle + * @return the context, or NULL if not set + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void * U_EXPORT2 +uplug_getContext(UPlugData *plug); + +/** + * Set the plugin-specific context data. + * @param plug plugin data handle + * @param context new context to set + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void U_EXPORT2 +uplug_setContext(UPlugData *plug, void *context); + + +/** + * Get the configuration string, if available. + * The string is in the platform default codepage. + * @param plug plugin data handle + * @return configuration string, or else null. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI const char * U_EXPORT2 +uplug_getConfiguration(UPlugData *plug); + +/** + * Return all currently installed plugins, from newest to oldest + * Usage Example: + * \code + * UPlugData *plug = NULL; + * while(plug=uplug_nextPlug(plug)) { + * ... do something with 'plug' ... + * } + * \endcode + * Not thread safe- do not call while plugs are added or removed. + * @param prior pass in 'NULL' to get the first (most recent) plug, + * otherwise pass the value returned on a prior call to uplug_nextPlug + * @return the next oldest plugin, or NULL if no more. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UPlugData* U_EXPORT2 +uplug_nextPlug(UPlugData *prior); + +/** + * Inject a plugin as if it were loaded from a library. + * This is useful for testing plugins. + * Note that it will have a 'NULL' library pointer associated + * with it, and therefore no llibrary will be closed at cleanup time. + * Low level plugins may not be able to load, as ordering can't be enforced. + * @param entrypoint entrypoint to install + * @param config user specified configuration string, if available, or NULL. + * @param status error result + * @return the new UPlugData associated with this plugin, or NULL if error. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UPlugData* U_EXPORT2 +uplug_loadPlugFromEntrypoint(UPlugEntrypoint *entrypoint, const char *config, UErrorCode *status); + + +/** + * Inject a plugin from a library, as if the information came from a config file. + * Low level plugins may not be able to load, and ordering can't be enforced. + * @param libName DLL name to load + * @param sym symbol of plugin (UPlugEntrypoint function) + * @param config configuration string, or NULL + * @param status error result + * @return the new UPlugData associated with this plugin, or NULL if error. + * @internal ICU 4.4 Technology Preview + */ +U_CAPI UPlugData* U_EXPORT2 +uplug_loadPlugFromLibrary(const char *libName, const char *sym, const char *config, UErrorCode *status); + +/** + * Remove a plugin. + * Will request the plugin to be unloaded, and close the library if needed + * @param plug plugin handle to close + * @param status error result + * @internal ICU 4.4 Technology Preview + */ +U_CAPI void U_EXPORT2 +uplug_removePlug(UPlugData *plug, UErrorCode *status); +#endif /* U_HIDE_INTERNAL_API */ + +#endif /* UCONFIG_ENABLE_PLUGINS */ + +#endif /* _ICUPLUG */ + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/idna.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/idna.h new file mode 100644 index 0000000000000000000000000000000000000000..1c57205bae2ef4d659587bcc921a66fb88aa6852 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/idna.h @@ -0,0 +1,330 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2012, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: idna.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010mar05 +* created by: Markus W. Scherer +*/ + +#ifndef __IDNA_H__ +#define __IDNA_H__ + +/** + * \file + * \brief C++ API: Internationalizing Domain Names in Applications (IDNA) + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_IDNA + +#include "unicode/bytestream.h" +#include "unicode/stringpiece.h" +#include "unicode/uidna.h" +#include "unicode/unistr.h" + +U_NAMESPACE_BEGIN + +class IDNAInfo; + +/** + * Abstract base class for IDNA processing. + * See http://www.unicode.org/reports/tr46/ + * and http://www.ietf.org/rfc/rfc3490.txt + * + * The IDNA class is not intended for public subclassing. + * + * This C++ API currently only implements UTS #46. + * The uidna.h C API implements both UTS #46 (functions using UIDNA service object) + * and IDNA2003 (functions that do not use a service object). + * @stable ICU 4.6 + */ +class U_COMMON_API IDNA : public UObject { +public: + /** + * Destructor. + * @stable ICU 4.6 + */ + ~IDNA(); + + /** + * Returns an IDNA instance which implements UTS #46. + * Returns an unmodifiable instance, owned by the caller. + * Cache it for multiple operations, and delete it when done. + * The instance is thread-safe, that is, it can be used concurrently. + * + * UTS #46 defines Unicode IDNA Compatibility Processing, + * updated to the latest version of Unicode and compatible with both + * IDNA2003 and IDNA2008. + * + * The worker functions use transitional processing, including deviation mappings, + * unless UIDNA_NONTRANSITIONAL_TO_ASCII or UIDNA_NONTRANSITIONAL_TO_UNICODE + * is used in which case the deviation characters are passed through without change. + * + * Disallowed characters are mapped to U+FFFD. + * + * For available options see the uidna.h header. + * Operations with the UTS #46 instance do not support the + * UIDNA_ALLOW_UNASSIGNED option. + * + * By default, the UTS #46 implementation allows all ASCII characters (as valid or mapped). + * When the UIDNA_USE_STD3_RULES option is used, ASCII characters other than + * letters, digits, hyphen (LDH) and dot/full stop are disallowed and mapped to U+FFFD. + * + * @param options Bit set to modify the processing and error checking. + * See option bit set values in uidna.h. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the UTS #46 IDNA instance, if successful + * @stable ICU 4.6 + */ + static IDNA * + createUTS46Instance(uint32_t options, UErrorCode &errorCode); + + /** + * Converts a single domain name label into its ASCII form for DNS lookup. + * If any processing step fails, then info.hasErrors() will be true and + * the result might not be an ASCII string. + * The label might be modified according to the types of errors. + * Labels with severe errors will be left in (or turned into) their Unicode form. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param label Input domain name label + * @param dest Destination string object + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual UnicodeString & + labelToASCII(const UnicodeString &label, UnicodeString &dest, + IDNAInfo &info, UErrorCode &errorCode) const = 0; + + /** + * Converts a single domain name label into its Unicode form for human-readable display. + * If any processing step fails, then info.hasErrors() will be true. + * The label might be modified according to the types of errors. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param label Input domain name label + * @param dest Destination string object + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual UnicodeString & + labelToUnicode(const UnicodeString &label, UnicodeString &dest, + IDNAInfo &info, UErrorCode &errorCode) const = 0; + + /** + * Converts a whole domain name into its ASCII form for DNS lookup. + * If any processing step fails, then info.hasErrors() will be true and + * the result might not be an ASCII string. + * The domain name might be modified according to the types of errors. + * Labels with severe errors will be left in (or turned into) their Unicode form. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param name Input domain name + * @param dest Destination string object + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual UnicodeString & + nameToASCII(const UnicodeString &name, UnicodeString &dest, + IDNAInfo &info, UErrorCode &errorCode) const = 0; + + /** + * Converts a whole domain name into its Unicode form for human-readable display. + * If any processing step fails, then info.hasErrors() will be true. + * The domain name might be modified according to the types of errors. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param name Input domain name + * @param dest Destination string object + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual UnicodeString & + nameToUnicode(const UnicodeString &name, UnicodeString &dest, + IDNAInfo &info, UErrorCode &errorCode) const = 0; + + // UTF-8 versions of the processing methods ---------------------------- *** + + /** + * Converts a single domain name label into its ASCII form for DNS lookup. + * UTF-8 version of labelToASCII(), same behavior. + * + * @param label Input domain name label + * @param dest Destination byte sink; Flush()ed if successful + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual void + labelToASCII_UTF8(StringPiece label, ByteSink &dest, + IDNAInfo &info, UErrorCode &errorCode) const; + + /** + * Converts a single domain name label into its Unicode form for human-readable display. + * UTF-8 version of labelToUnicode(), same behavior. + * + * @param label Input domain name label + * @param dest Destination byte sink; Flush()ed if successful + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual void + labelToUnicodeUTF8(StringPiece label, ByteSink &dest, + IDNAInfo &info, UErrorCode &errorCode) const; + + /** + * Converts a whole domain name into its ASCII form for DNS lookup. + * UTF-8 version of nameToASCII(), same behavior. + * + * @param name Input domain name + * @param dest Destination byte sink; Flush()ed if successful + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual void + nameToASCII_UTF8(StringPiece name, ByteSink &dest, + IDNAInfo &info, UErrorCode &errorCode) const; + + /** + * Converts a whole domain name into its Unicode form for human-readable display. + * UTF-8 version of nameToUnicode(), same behavior. + * + * @param name Input domain name + * @param dest Destination byte sink; Flush()ed if successful + * @param info Output container of IDNA processing details. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.6 + */ + virtual void + nameToUnicodeUTF8(StringPiece name, ByteSink &dest, + IDNAInfo &info, UErrorCode &errorCode) const; +}; + +class UTS46; + +/** + * Output container for IDNA processing errors. + * The IDNAInfo class is not suitable for subclassing. + * @stable ICU 4.6 + */ +class U_COMMON_API IDNAInfo : public UMemory { +public: + /** + * Constructor for stack allocation. + * @stable ICU 4.6 + */ + IDNAInfo() : errors(0), labelErrors(0), isTransDiff(false), isBiDi(false), isOkBiDi(true) {} + /** + * Were there IDNA processing errors? + * @return true if there were processing errors + * @stable ICU 4.6 + */ + UBool hasErrors() const { return errors!=0; } + /** + * Returns a bit set indicating IDNA processing errors. + * See UIDNA_ERROR_... constants in uidna.h. + * @return bit set of processing errors + * @stable ICU 4.6 + */ + uint32_t getErrors() const { return errors; } + /** + * Returns true if transitional and nontransitional processing produce different results. + * This is the case when the input label or domain name contains + * one or more deviation characters outside a Punycode label (see UTS #46). + *
    + *
  • With nontransitional processing, such characters are + * copied to the destination string. + *
  • With transitional processing, such characters are + * mapped (sharp s/sigma) or removed (joiner/nonjoiner). + *
+ * @return true if transitional and nontransitional processing produce different results + * @stable ICU 4.6 + */ + UBool isTransitionalDifferent() const { return isTransDiff; } + +private: + friend class UTS46; + + IDNAInfo(const IDNAInfo &other) = delete; // no copying + IDNAInfo &operator=(const IDNAInfo &other) = delete; // no copying + + void reset() { + errors=labelErrors=0; + isTransDiff=false; + isBiDi=false; + isOkBiDi=true; + } + + uint32_t errors, labelErrors; + UBool isTransDiff; + UBool isBiDi; + UBool isOkBiDi; +}; + +U_NAMESPACE_END + +#endif // UCONFIG_NO_IDNA + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __IDNA_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/listformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/listformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..37a76dcdd408fd67d6e3e2a80fdb45bc63c94cdd --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/listformatter.h @@ -0,0 +1,286 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2012-2016, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: listformatter.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 20120426 +* created by: Umesh P. Nair +*/ + +#ifndef __LISTFORMATTER_H__ +#define __LISTFORMATTER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" +#include "unicode/locid.h" +#include "unicode/formattedvalue.h" +#include "unicode/ulistformatter.h" + +U_NAMESPACE_BEGIN + +class FieldPositionHandler; +class FormattedListData; +class ListFormatter; + +/** @internal */ +class Hashtable; + +/** @internal */ +struct ListFormatInternal; + +/* The following can't be #ifndef U_HIDE_INTERNAL_API, needed for other .h file declarations */ +/** + * @internal + * \cond + */ +struct ListFormatData : public UMemory { + UnicodeString twoPattern; + UnicodeString startPattern; + UnicodeString middlePattern; + UnicodeString endPattern; + Locale locale; + + ListFormatData(const UnicodeString& two, const UnicodeString& start, const UnicodeString& middle, const UnicodeString& end, + const Locale& loc) : + twoPattern(two), startPattern(start), middlePattern(middle), endPattern(end), locale(loc) {} +}; +/** \endcond */ + + +/** + * \file + * \brief C++ API: API for formatting a list. + */ + + +/** + * An immutable class containing the result of a list formatting operation. + * + * Instances of this class are immutable and thread-safe. + * + * When calling nextPosition(): + * The fields are returned from start to end. The special field category + * UFIELD_CATEGORY_LIST_SPAN is used to indicate which argument + * was inserted at the given position. The span category will + * always occur before the corresponding instance of UFIELD_CATEGORY_LIST + * in the nextPosition() iterator. + * + * Not intended for public subclassing. + * + * @stable ICU 64 + */ +class U_I18N_API FormattedList : public UMemory, public FormattedValue { + public: + /** + * Default constructor; makes an empty FormattedList. + * @stable ICU 64 + */ + FormattedList() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} + + /** + * Move constructor: Leaves the source FormattedList in an undefined state. + * @stable ICU 64 + */ + FormattedList(FormattedList&& src) noexcept; + + /** + * Destruct an instance of FormattedList. + * @stable ICU 64 + */ + virtual ~FormattedList() override; + + /** Copying not supported; use move constructor instead. */ + FormattedList(const FormattedList&) = delete; + + /** Copying not supported; use move assignment instead. */ + FormattedList& operator=(const FormattedList&) = delete; + + /** + * Move assignment: Leaves the source FormattedList in an undefined state. + * @stable ICU 64 + */ + FormattedList& operator=(FormattedList&& src) noexcept; + + /** @copydoc FormattedValue::toString() */ + UnicodeString toString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::toTempString() */ + UnicodeString toTempString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::appendTo() */ + Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override; + + /** @copydoc FormattedValue::nextPosition() */ + UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; + + private: + FormattedListData *fData; + UErrorCode fErrorCode; + explicit FormattedList(FormattedListData *results) + : fData(results), fErrorCode(U_ZERO_ERROR) {} + explicit FormattedList(UErrorCode errorCode) + : fData(nullptr), fErrorCode(errorCode) {} + friend class ListFormatter; +}; + + +/** + * An immutable class for formatting a list, using data from CLDR (or supplied + * separately). + * + * Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted + * as "Alice, Bob, Charlie and Delta" in English. + * + * The ListFormatter class is not intended for public subclassing. + * @stable ICU 50 + */ +class U_I18N_API ListFormatter : public UObject{ + + public: + + /** + * Copy constructor. + * @stable ICU 52 + */ + ListFormatter(const ListFormatter&); + + /** + * Assignment operator. + * @stable ICU 52 + */ + ListFormatter& operator=(const ListFormatter& other); + + /** + * Creates a ListFormatter appropriate for the default locale. + * + * @param errorCode ICU error code, set if no data available for default locale. + * @return Pointer to a ListFormatter object for the default locale, + * created from internal data derived from CLDR data. + * @stable ICU 50 + */ + static ListFormatter* createInstance(UErrorCode& errorCode); + + /** + * Creates a ListFormatter appropriate for a locale. + * + * @param locale The locale. + * @param errorCode ICU error code, set if no data available for the given locale. + * @return A ListFormatter object created from internal data derived from + * CLDR data. + * @stable ICU 50 + */ + static ListFormatter* createInstance(const Locale& locale, UErrorCode& errorCode); + + /** + * Creates a ListFormatter for the given locale, list type, and style. + * + * @param locale The locale. + * @param type The type of list formatting to use. + * @param width The width of formatting to use. + * @param errorCode ICU error code, set if no data available for the given locale. + * @return A ListFormatter object created from internal data derived from CLDR data. + * @stable ICU 67 + */ + static ListFormatter* createInstance( + const Locale& locale, UListFormatterType type, UListFormatterWidth width, UErrorCode& errorCode); + + /** + * Destructor. + * + * @stable ICU 50 + */ + virtual ~ListFormatter(); + + + /** + * Formats a list of strings. + * + * @param items An array of strings to be combined and formatted. + * @param n_items Length of the array items. + * @param appendTo The string to which the result should be appended to. + * @param errorCode ICU error code, set if there is an error. + * @return Formatted string combining the elements of items, appended to appendTo. + * @stable ICU 50 + */ + UnicodeString& format(const UnicodeString items[], int32_t n_items, + UnicodeString& appendTo, UErrorCode& errorCode) const; + + /** + * Formats a list of strings to a FormattedList, which exposes field + * position information. The FormattedList contains more information than + * a FieldPositionIterator. + * + * @param items An array of strings to be combined and formatted. + * @param n_items Length of the array items. + * @param errorCode ICU error code returned here. + * @return A FormattedList containing field information. + * @stable ICU 64 + */ + FormattedList formatStringsToValue( + const UnicodeString items[], + int32_t n_items, + UErrorCode& errorCode) const; + +#ifndef U_HIDE_INTERNAL_API + /** + @internal for MeasureFormat + */ + UnicodeString& format( + const UnicodeString items[], + int32_t n_items, + UnicodeString& appendTo, + int32_t index, + int32_t &offset, + UErrorCode& errorCode) const; + /** + * @internal constructor made public for testing. + */ + ListFormatter(const ListFormatData &data, UErrorCode &errorCode); + /** + * @internal constructor made public for testing. + */ + ListFormatter(const ListFormatInternal* listFormatterInternal); +#endif /* U_HIDE_INTERNAL_API */ + + private: + + /** + * Creates a ListFormatter appropriate for a locale and style. + * + * @param locale The locale. + * @param style the style, either "standard", "or", "unit", "unit-narrow", or "unit-short" + */ + static ListFormatter* createInstance(const Locale& locale, const char* style, UErrorCode& errorCode); + + static void initializeHash(UErrorCode& errorCode); + static const ListFormatInternal* getListFormatInternal(const Locale& locale, const char *style, UErrorCode& errorCode); + struct U_HIDDEN ListPatternsSink; + static ListFormatInternal* loadListFormatInternal(const Locale& locale, const char* style, UErrorCode& errorCode); + + ListFormatter() = delete; + + ListFormatInternal* owned; + const ListFormatInternal* data; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __LISTFORMATTER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localebuilder.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localebuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..f708a7ed7c4cb3af8720458dd65a34d40806caf0 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localebuilder.h @@ -0,0 +1,309 @@ +// © 2018 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +#ifndef __LOCALEBUILDER_H__ +#define __LOCALEBUILDER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/locid.h" +#include "unicode/localematcher.h" +#include "unicode/stringpiece.h" +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Builder API for Locale + */ + +U_NAMESPACE_BEGIN +class CharString; + +/** + * LocaleBuilder is used to build instances of Locale + * from values configured by the setters. Unlike the Locale + * constructors, the LocaleBuilder checks if a value configured by a + * setter satisfies the syntax requirements defined by the Locale + * class. A Locale object created by a LocaleBuilder is + * well-formed and can be transformed to a well-formed IETF BCP 47 language tag + * without losing information. + * + *

The following example shows how to create a Locale object + * with the LocaleBuilder. + *

+ *
+ *     UErrorCode status = U_ZERO_ERROR;
+ *     Locale aLocale = LocaleBuilder()
+ *                          .setLanguage("sr")
+ *                          .setScript("Latn")
+ *                          .setRegion("RS")
+ *                          .build(status);
+ *     if (U_SUCCESS(status)) {
+ *       // ...
+ *     }
+ * 
+ *
+ * + *

LocaleBuilders can be reused; clear() resets all + * fields to their default values. + * + *

LocaleBuilder tracks errors in an internal UErrorCode. For all setters, + * except setLanguageTag and setLocale, LocaleBuilder will return immediately + * if the internal UErrorCode is in error state. + * To reset internal state and error code, call clear method. + * The setLanguageTag and setLocale method will first clear the internal + * UErrorCode, then track the error of the validation of the input parameter + * into the internal UErrorCode. + * + * @stable ICU 64 + */ +class U_COMMON_API LocaleBuilder : public UObject { +public: + /** + * Constructs an empty LocaleBuilder. The default value of all + * fields, extensions, and private use information is the + * empty string. + * + * @stable ICU 64 + */ + LocaleBuilder(); + + /** + * Destructor + * @stable ICU 64 + */ + virtual ~LocaleBuilder(); + + /** + * Resets the LocaleBuilder to match the provided + * locale. Existing state is discarded. + * + *

All fields of the locale must be well-formed. + *

This method clears the internal UErrorCode. + * + * @param locale the locale + * @return This builder. + * + * @stable ICU 64 + */ + LocaleBuilder& setLocale(const Locale& locale); + + /** + * Resets the LocaleBuilder to match the provided IETF BCP 47 language tag. + * Discards the existing state. + * The empty string causes the builder to be reset, like {@link #clear}. + * Legacy language tags (marked as “Type: grandfathered” in BCP 47) + * are converted to their canonical form before being processed. + * Otherwise, the language tag must be well-formed, + * or else the build() method will later report an U_ILLEGAL_ARGUMENT_ERROR. + * + *

This method clears the internal UErrorCode. + * + * @param tag the language tag, defined as IETF BCP 47 language tag. + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setLanguageTag(StringPiece tag); + + /** + * Sets the language. If language is the empty string, the + * language in this LocaleBuilder is removed. Otherwise, the + * language must be well-formed, or else the build() method will + * later report an U_ILLEGAL_ARGUMENT_ERROR. + * + *

The syntax of language value is defined as + * [unicode_language_subtag](http://www.unicode.org/reports/tr35/tr35.html#unicode_language_subtag). + * + * @param language the language + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setLanguage(StringPiece language); + + /** + * Sets the script. If script is the empty string, the script in + * this LocaleBuilder is removed. + * Otherwise, the script must be well-formed, or else the build() + * method will later report an U_ILLEGAL_ARGUMENT_ERROR. + * + *

The script value is a four-letter script code as + * [unicode_script_subtag](http://www.unicode.org/reports/tr35/tr35.html#unicode_script_subtag) + * defined by ISO 15924 + * + * @param script the script + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setScript(StringPiece script); + + /** + * Sets the region. If region is the empty string, the region in this + * LocaleBuilder is removed. Otherwise, the region + * must be well-formed, or else the build() method will later report an + * U_ILLEGAL_ARGUMENT_ERROR. + * + *

The region value is defined by + * [unicode_region_subtag](http://www.unicode.org/reports/tr35/tr35.html#unicode_region_subtag) + * as a two-letter ISO 3166 code or a three-digit UN M.49 area code. + * + *

The region value in the Locale created by the + * LocaleBuilder is always normalized to upper case. + * + * @param region the region + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setRegion(StringPiece region); + + /** + * Sets the variant. If variant is the empty string, the variant in this + * LocaleBuilder is removed. Otherwise, the variant + * must be well-formed, or else the build() method will later report an + * U_ILLEGAL_ARGUMENT_ERROR. + * + *

Note: This method checks if variant + * satisfies the + * [unicode_variant_subtag](http://www.unicode.org/reports/tr35/tr35.html#unicode_variant_subtag) + * syntax requirements, and normalizes the value to lowercase letters. However, + * the Locale class does not impose any syntactic + * restriction on variant. To set an ill-formed variant, use a Locale constructor. + * If there are multiple unicode_variant_subtag, the caller must concatenate + * them with '-' as separator (ex: "foobar-fibar"). + * + * @param variant the variant + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setVariant(StringPiece variant); + + /** + * Sets the extension for the given key. If the value is the empty string, + * the extension is removed. Otherwise, the key and + * value must be well-formed, or else the build() method will + * later report an U_ILLEGAL_ARGUMENT_ERROR. + * + *

Note: The key ('u') is used for the Unicode locale extension. + * Setting a value for this key replaces any existing Unicode locale key/type + * pairs with those defined in the extension. + * + *

Note: The key ('x') is used for the private use code. To be + * well-formed, the value for this key needs only to have subtags of one to + * eight alphanumeric characters, not two to eight as in the general case. + * + * @param key the extension key + * @param value the extension value + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setExtension(char key, StringPiece value); + + /** + * Sets the Unicode locale keyword type for the given key. If the type + * StringPiece is constructed with a nullptr, the keyword is removed. + * If the type is the empty string, the keyword is set without type subtags. + * Otherwise, the key and type must be well-formed, or else the build() + * method will later report an U_ILLEGAL_ARGUMENT_ERROR. + * + *

Keys and types are converted to lower case. + * + *

Note:Setting the 'u' extension via {@link #setExtension} + * replaces all Unicode locale keywords with those defined in the + * extension. + * + * @param key the Unicode locale key + * @param type the Unicode locale type + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& setUnicodeLocaleKeyword( + StringPiece key, StringPiece type); + + /** + * Adds a unicode locale attribute, if not already present, otherwise + * has no effect. The attribute must not be empty string and must be + * well-formed or U_ILLEGAL_ARGUMENT_ERROR will be set to status + * during the build() call. + * + * @param attribute the attribute + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& addUnicodeLocaleAttribute(StringPiece attribute); + + /** + * Removes a unicode locale attribute, if present, otherwise has no + * effect. The attribute must not be empty string and must be well-formed + * or U_ILLEGAL_ARGUMENT_ERROR will be set to status during the build() call. + * + *

Attribute comparison for removal is case-insensitive. + * + * @param attribute the attribute + * @return This builder. + * @stable ICU 64 + */ + LocaleBuilder& removeUnicodeLocaleAttribute(StringPiece attribute); + + /** + * Resets the builder to its initial, empty state. + *

This method clears the internal UErrorCode. + * + * @return this builder + * @stable ICU 64 + */ + LocaleBuilder& clear(); + + /** + * Resets the extensions to their initial, empty state. + * Language, script, region and variant are unchanged. + * + * @return this builder + * @stable ICU 64 + */ + LocaleBuilder& clearExtensions(); + + /** + * Returns an instance of Locale created from the fields set + * on this builder. + * If any set methods or during the build() call require memory allocation + * but fail U_MEMORY_ALLOCATION_ERROR will be set to status. + * If any of the fields set by the setters are not well-formed, the status + * will be set to U_ILLEGAL_ARGUMENT_ERROR. The state of the builder will + * not change after the build() call and the caller is free to keep using + * the same builder to build more locales. + * + * @return a new Locale + * @stable ICU 64 + */ + Locale build(UErrorCode& status); + + /** + * Sets the UErrorCode if an error occurred while recording sets. + * Preserves older error codes in the outErrorCode. + * @param outErrorCode Set to an error code that occurred while setting subtags. + * Unchanged if there is no such error or if outErrorCode + * already contained an error. + * @return true if U_FAILURE(outErrorCode) + * @stable ICU 65 + */ + UBool copyErrorTo(UErrorCode &outErrorCode) const; + +private: + friend class LocaleMatcher::Result; + + void copyExtensionsFrom(const Locale& src, UErrorCode& errorCode); + + UErrorCode status_; + char language_[9]; + char script_[5]; + char region_[4]; + CharString *variant_; // Pointer not object so we need not #include internal charstr.h. + icu::Locale *extensions_; // Pointer not object. Storage for all other fields. + +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __LOCALEBUILDER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localematcher.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localematcher.h new file mode 100644 index 0000000000000000000000000000000000000000..603daf7231dd1aa5f8a43c19944aec5dafc2720f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localematcher.h @@ -0,0 +1,708 @@ +// © 2019 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// localematcher.h +// created: 2019may08 Markus W. Scherer + +#ifndef __LOCALEMATCHER_H__ +#define __LOCALEMATCHER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/locid.h" +#include "unicode/stringpiece.h" +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Locale matcher: User's desired locales vs. application's supported locales. + */ + +/** + * Builder option for whether the language subtag or the script subtag is most important. + * + * @see LocaleMatcher::Builder#setFavorSubtag(ULocMatchFavorSubtag) + * @stable ICU 65 + */ +enum ULocMatchFavorSubtag { + /** + * Language differences are most important, then script differences, then region differences. + * (This is the default behavior.) + * + * @stable ICU 65 + */ + ULOCMATCH_FAVOR_LANGUAGE, + /** + * Makes script differences matter relatively more than language differences. + * + * @stable ICU 65 + */ + ULOCMATCH_FAVOR_SCRIPT +}; +#ifndef U_IN_DOXYGEN +typedef enum ULocMatchFavorSubtag ULocMatchFavorSubtag; +#endif + +/** + * Builder option for whether all desired locales are treated equally or + * earlier ones are preferred. + * + * @see LocaleMatcher::Builder#setDemotionPerDesiredLocale(ULocMatchDemotion) + * @stable ICU 65 + */ +enum ULocMatchDemotion { + /** + * All desired locales are treated equally. + * + * @stable ICU 65 + */ + ULOCMATCH_DEMOTION_NONE, + /** + * Earlier desired locales are preferred. + * + *

From each desired locale to the next, + * the distance to any supported locale is increased by an additional amount + * which is at least as large as most region mismatches. + * A later desired locale has to have a better match with some supported locale + * due to more than merely having the same region subtag. + * + *

For example: Supported={en, sv} desired=[en-GB, sv] + * yields Result(en-GB, en) because + * with the demotion of sv its perfect match is no better than + * the region distance between the earlier desired locale en-GB and en=en-US. + * + *

Notes: + *

    + *
  • In some cases, language and/or script differences can be as small as + * the typical region difference. (Example: sr-Latn vs. sr-Cyrl) + *
  • It is possible for certain region differences to be larger than usual, + * and larger than the demotion. + * (As of CLDR 35 there is no such case, but + * this is possible in future versions of the data.) + *
+ * + * @stable ICU 65 + */ + ULOCMATCH_DEMOTION_REGION +}; +#ifndef U_IN_DOXYGEN +typedef enum ULocMatchDemotion ULocMatchDemotion; +#endif + +/** + * Builder option for whether to include or ignore one-way (fallback) match data. + * The LocaleMatcher uses CLDR languageMatch data which includes fallback (oneway=true) entries. + * Sometimes it is desirable to ignore those. + * + *

For example, consider a web application with the UI in a given language, + * with a link to another, related web app. + * The link should include the UI language, and the target server may also use + * the client’s Accept-Language header data. + * The target server has its own list of supported languages. + * One may want to favor UI language consistency, that is, + * if there is a decent match for the original UI language, we want to use it, + * but not if it is merely a fallback. + * + * @see LocaleMatcher::Builder#setDirection(ULocMatchDirection) + * @stable ICU 67 + */ +enum ULocMatchDirection { + /** + * Locale matching includes one-way matches such as Breton→French. (default) + * + * @stable ICU 67 + */ + ULOCMATCH_DIRECTION_WITH_ONE_WAY, + /** + * Locale matching limited to two-way matches including e.g. Danish↔Norwegian + * but ignoring one-way matches. + * + * @stable ICU 67 + */ + ULOCMATCH_DIRECTION_ONLY_TWO_WAY +}; +#ifndef U_IN_DOXYGEN +typedef enum ULocMatchDirection ULocMatchDirection; +#endif + +struct UHashtable; + +U_NAMESPACE_BEGIN + +struct LSR; + +class LocaleDistance; +class LocaleLsrIterator; +class UVector; +class XLikelySubtags; + +/** + * Immutable class that picks the best match between a user's desired locales and + * an application's supported locales. + * Movable but not copyable. + * + *

Example: + *

+ * UErrorCode errorCode = U_ZERO_ERROR;
+ * LocaleMatcher matcher = LocaleMatcher::Builder().setSupportedLocales("fr, en-GB, en").build(errorCode);
+ * Locale *bestSupported = matcher.getBestLocale(Locale.US, errorCode);  // "en"
+ * 
+ * + *

A matcher takes into account when languages are close to one another, + * such as Danish and Norwegian, + * and when regional variants are close, like en-GB and en-AU as opposed to en-US. + * + *

If there are multiple supported locales with the same (language, script, region) + * likely subtags, then the current implementation returns the first of those locales. + * It ignores variant subtags (except for pseudolocale variants) and extensions. + * This may change in future versions. + * + *

For example, the current implementation does not distinguish between + * de, de-DE, de-Latn, de-1901, de-u-co-phonebk. + * + *

If you prefer one equivalent locale over another, then provide only the preferred one, + * or place it earlier in the list of supported locales. + * + *

Otherwise, the order of supported locales may have no effect on the best-match results. + * The current implementation compares each desired locale with supported locales + * in the following order: + * 1. Default locale, if supported; + * 2. CLDR "paradigm locales" like en-GB and es-419; + * 3. other supported locales. + * This may change in future versions. + * + *

Often a product will just need one matcher instance, built with the languages + * that it supports. However, it may want multiple instances with different + * default languages based on additional information, such as the domain. + * + *

This class is not intended for public subclassing. + * + * @stable ICU 65 + */ +class U_COMMON_API LocaleMatcher : public UMemory { +public: + /** + * Data for the best-matching pair of a desired and a supported locale. + * Movable but not copyable. + * + * @stable ICU 65 + */ + class U_COMMON_API Result : public UMemory { + public: + /** + * Move constructor; might modify the source. + * This object will have the same contents that the source object had. + * + * @param src Result to move contents from. + * @stable ICU 65 + */ + Result(Result &&src) noexcept; + + /** + * Destructor. + * + * @stable ICU 65 + */ + ~Result(); + + /** + * Move assignment; might modify the source. + * This object will have the same contents that the source object had. + * + * @param src Result to move contents from. + * @stable ICU 65 + */ + Result &operator=(Result &&src) noexcept; + + /** + * Returns the best-matching desired locale. + * nullptr if the list of desired locales is empty or if none matched well enough. + * + * @return the best-matching desired locale, or nullptr. + * @stable ICU 65 + */ + inline const Locale *getDesiredLocale() const { return desiredLocale; } + + /** + * Returns the best-matching supported locale. + * If none matched well enough, this is the default locale. + * The default locale is nullptr if Builder::setNoDefaultLocale() was called, + * or if the list of supported locales is empty and no explicit default locale is set. + * + * @return the best-matching supported locale, or nullptr. + * @stable ICU 65 + */ + inline const Locale *getSupportedLocale() const { return supportedLocale; } + + /** + * Returns the index of the best-matching desired locale in the input Iterable order. + * -1 if the list of desired locales is empty or if none matched well enough. + * + * @return the index of the best-matching desired locale, or -1. + * @stable ICU 65 + */ + inline int32_t getDesiredIndex() const { return desiredIndex; } + + /** + * Returns the index of the best-matching supported locale in the + * constructor’s or builder’s input order (“set” Collection plus “added” locales). + * If the matcher was built from a locale list string, then the iteration order is that + * of a LocalePriorityList built from the same string. + * -1 if the list of supported locales is empty or if none matched well enough. + * + * @return the index of the best-matching supported locale, or -1. + * @stable ICU 65 + */ + inline int32_t getSupportedIndex() const { return supportedIndex; } + + /** + * Takes the best-matching supported locale and adds relevant fields of the + * best-matching desired locale, such as the -t- and -u- extensions. + * May replace some fields of the supported locale. + * The result is the locale that should be used for date and number formatting, collation, etc. + * Returns the root locale if getSupportedLocale() returns nullptr. + * + *

Example: desired=ar-SA-u-nu-latn, supported=ar-EG, resolved locale=ar-SA-u-nu-latn + * + * @return a locale combining the best-matching desired and supported locales. + * @stable ICU 65 + */ + Locale makeResolvedLocale(UErrorCode &errorCode) const; + + private: + Result(const Locale *desired, const Locale *supported, + int32_t desIndex, int32_t suppIndex, UBool owned) : + desiredLocale(desired), supportedLocale(supported), + desiredIndex(desIndex), supportedIndex(suppIndex), + desiredIsOwned(owned) {} + + Result(const Result &other) = delete; + Result &operator=(const Result &other) = delete; + + const Locale *desiredLocale; + const Locale *supportedLocale; + int32_t desiredIndex; + int32_t supportedIndex; + UBool desiredIsOwned; + + friend class LocaleMatcher; + }; + + /** + * LocaleMatcher builder. + * Movable but not copyable. + * + * @stable ICU 65 + */ + class U_COMMON_API Builder : public UMemory { + public: + /** + * Constructs a builder used in chaining parameters for building a LocaleMatcher. + * + * @return a new Builder object + * @stable ICU 65 + */ + Builder() {} + + /** + * Move constructor; might modify the source. + * This builder will have the same contents that the source builder had. + * + * @param src Builder to move contents from. + * @stable ICU 65 + */ + Builder(Builder &&src) noexcept; + + /** + * Destructor. + * + * @stable ICU 65 + */ + ~Builder(); + + /** + * Move assignment; might modify the source. + * This builder will have the same contents that the source builder had. + * + * @param src Builder to move contents from. + * @stable ICU 65 + */ + Builder &operator=(Builder &&src) noexcept; + + /** + * Parses an Accept-Language string + * (RFC 2616 Section 14.4), + * such as "af, en, fr;q=0.9", and sets the supported locales accordingly. + * Allows whitespace in more places but does not allow "*". + * Clears any previously set/added supported locales first. + * + * @param locales the Accept-Language string of locales to set + * @return this Builder object + * @stable ICU 65 + */ + Builder &setSupportedLocalesFromListString(StringPiece locales); + + /** + * Copies the supported locales, preserving iteration order. + * Clears any previously set/added supported locales first. + * Duplicates are allowed, and are not removed. + * + * @param locales the list of locale + * @return this Builder object + * @stable ICU 65 + */ + Builder &setSupportedLocales(Locale::Iterator &locales); + + /** + * Copies the supported locales from the begin/end range, preserving iteration order. + * Clears any previously set/added supported locales first. + * Duplicates are allowed, and are not removed. + * + * Each of the iterator parameter values must be an + * input iterator whose value is convertible to const Locale &. + * + * @param begin Start of range. + * @param end Exclusive end of range. + * @return this Builder object + * @stable ICU 65 + */ + template + Builder &setSupportedLocales(Iter begin, Iter end) { + if (U_FAILURE(errorCode_)) { return *this; } + clearSupportedLocales(); + while (begin != end) { + addSupportedLocale(*begin++); + } + return *this; + } + + /** + * Copies the supported locales from the begin/end range, preserving iteration order. + * Calls the converter to convert each *begin to a Locale or const Locale &. + * Clears any previously set/added supported locales first. + * Duplicates are allowed, and are not removed. + * + * Each of the iterator parameter values must be an + * input iterator whose value is convertible to const Locale &. + * + * @param begin Start of range. + * @param end Exclusive end of range. + * @param converter Converter from *begin to const Locale & or compatible. + * @return this Builder object + * @stable ICU 65 + */ + template + Builder &setSupportedLocalesViaConverter(Iter begin, Iter end, Conv converter) { + if (U_FAILURE(errorCode_)) { return *this; } + clearSupportedLocales(); + while (begin != end) { + addSupportedLocale(converter(*begin++)); + } + return *this; + } + + /** + * Adds another supported locale. + * Duplicates are allowed, and are not removed. + * + * @param locale another locale + * @return this Builder object + * @stable ICU 65 + */ + Builder &addSupportedLocale(const Locale &locale); + + /** + * Sets no default locale. + * There will be no explicit or implicit default locale. + * If there is no good match, then the matcher will return nullptr for the + * best supported locale. + * + * @stable ICU 68 + */ + Builder &setNoDefaultLocale(); + + /** + * Sets the default locale; if nullptr, or if it is not set explicitly, + * then the first supported locale is used as the default locale. + * There is no default locale at all (nullptr will be returned instead) + * if setNoDefaultLocale() is called. + * + * @param defaultLocale the default locale (will be copied) + * @return this Builder object + * @stable ICU 65 + */ + Builder &setDefaultLocale(const Locale *defaultLocale); + + /** + * If ULOCMATCH_FAVOR_SCRIPT, then the language differences are smaller than script + * differences. + * This is used in situations (such as maps) where + * it is better to fall back to the same script than a similar language. + * + * @param subtag the subtag to favor + * @return this Builder object + * @stable ICU 65 + */ + Builder &setFavorSubtag(ULocMatchFavorSubtag subtag); + + /** + * Option for whether all desired locales are treated equally or + * earlier ones are preferred (this is the default). + * + * @param demotion the demotion per desired locale to set. + * @return this Builder object + * @stable ICU 65 + */ + Builder &setDemotionPerDesiredLocale(ULocMatchDemotion demotion); + + /** + * Option for whether to include or ignore one-way (fallback) match data. + * By default, they are included. + * + * @param matchDirection the match direction to set. + * @return this Builder object + * @stable ICU 67 + */ + Builder &setDirection(ULocMatchDirection matchDirection) { + if (U_SUCCESS(errorCode_)) { + direction_ = matchDirection; + } + return *this; + } + + /** + * Sets the maximum distance for an acceptable match. + * The matcher will return a match for a pair of locales only if + * they match at least as well as the pair given here. + * + * For example, setMaxDistance(en-US, en-GB) limits matches to ones where the + * (desired, support) locales have a distance no greater than a region subtag difference. + * This is much stricter than the CLDR default. + * + * The details of locale matching are subject to changes in + * CLDR data and in the algorithm. + * Specifying a maximum distance in relative terms via a sample pair of locales + * insulates from changes that affect all distance metrics similarly, + * but some changes will necessarily affect relative distances between + * different pairs of locales. + * + * @param desired the desired locale for distance comparison. + * @param supported the supported locale for distance comparison. + * @return this Builder object + * @stable ICU 68 + */ + Builder &setMaxDistance(const Locale &desired, const Locale &supported); + + /** + * Sets the UErrorCode if an error occurred while setting parameters. + * Preserves older error codes in the outErrorCode. + * + * @param outErrorCode Set to an error code if it does not contain one already + * and an error occurred while setting parameters. + * Otherwise unchanged. + * @return true if U_FAILURE(outErrorCode) + * @stable ICU 65 + */ + UBool copyErrorTo(UErrorCode &outErrorCode) const; + + /** + * Builds and returns a new locale matcher. + * This builder can continue to be used. + * + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return LocaleMatcher + * @stable ICU 65 + */ + LocaleMatcher build(UErrorCode &errorCode) const; + + private: + friend class LocaleMatcher; + + Builder(const Builder &other) = delete; + Builder &operator=(const Builder &other) = delete; + + void clearSupportedLocales(); + bool ensureSupportedLocaleVector(); + + UErrorCode errorCode_ = U_ZERO_ERROR; + UVector *supportedLocales_ = nullptr; + int32_t thresholdDistance_ = -1; + ULocMatchDemotion demotion_ = ULOCMATCH_DEMOTION_REGION; + Locale *defaultLocale_ = nullptr; + bool withDefault_ = true; + ULocMatchFavorSubtag favor_ = ULOCMATCH_FAVOR_LANGUAGE; + ULocMatchDirection direction_ = ULOCMATCH_DIRECTION_WITH_ONE_WAY; + Locale *maxDistanceDesired_ = nullptr; + Locale *maxDistanceSupported_ = nullptr; + }; + + // FYI No public LocaleMatcher constructors in C++; use the Builder. + + /** + * Move copy constructor; might modify the source. + * This matcher will have the same settings that the source matcher had. + * @param src source matcher + * @stable ICU 65 + */ + LocaleMatcher(LocaleMatcher &&src) noexcept; + + /** + * Destructor. + * @stable ICU 65 + */ + ~LocaleMatcher(); + + /** + * Move assignment operator; might modify the source. + * This matcher will have the same settings that the source matcher had. + * The behavior is undefined if *this and src are the same object. + * @param src source matcher + * @return *this + * @stable ICU 65 + */ + LocaleMatcher &operator=(LocaleMatcher &&src) noexcept; + + /** + * Returns the supported locale which best matches the desired locale. + * + * @param desiredLocale Typically a user's language. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return the best-matching supported locale. + * @stable ICU 65 + */ + const Locale *getBestMatch(const Locale &desiredLocale, UErrorCode &errorCode) const; + + /** + * Returns the supported locale which best matches one of the desired locales. + * + * @param desiredLocales Typically a user's languages, in order of preference (descending). + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return the best-matching supported locale. + * @stable ICU 65 + */ + const Locale *getBestMatch(Locale::Iterator &desiredLocales, UErrorCode &errorCode) const; + + /** + * Parses an Accept-Language string + * (RFC 2616 Section 14.4), + * such as "af, en, fr;q=0.9", + * and returns the supported locale which best matches one of the desired locales. + * Allows whitespace in more places but does not allow "*". + * + * @param desiredLocaleList Typically a user's languages, as an Accept-Language string. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return the best-matching supported locale. + * @stable ICU 65 + */ + const Locale *getBestMatchForListString(StringPiece desiredLocaleList, UErrorCode &errorCode) const; + + /** + * Returns the best match between the desired locale and the supported locales. + * If the result's desired locale is not nullptr, then it is the address of the input locale. + * It has not been cloned. + * + * @param desiredLocale Typically a user's language. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return the best-matching pair of the desired and a supported locale. + * @stable ICU 65 + */ + Result getBestMatchResult(const Locale &desiredLocale, UErrorCode &errorCode) const; + + /** + * Returns the best match between the desired and supported locales. + * If the result's desired locale is not nullptr, then it is a clone of + * the best-matching desired locale. The Result object owns the clone. + * + * @param desiredLocales Typically a user's languages, in order of preference (descending). + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return the best-matching pair of a desired and a supported locale. + * @stable ICU 65 + */ + Result getBestMatchResult(Locale::Iterator &desiredLocales, UErrorCode &errorCode) const; + + /** + * Returns true if the pair of locales matches acceptably. + * This is influenced by Builder options such as setDirection(), setFavorSubtag(), + * and setMaxDistance(). + * + * @param desired The desired locale. + * @param supported The supported locale. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return true if the pair of locales matches acceptably. + * @stable ICU 68 + */ + UBool isMatch(const Locale &desired, const Locale &supported, UErrorCode &errorCode) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Returns a fraction between 0 and 1, where 1 means that the languages are a + * perfect match, and 0 means that they are completely different. + * + *

This is mostly an implementation detail, and the precise values may change over time. + * The implementation may use either the maximized forms or the others ones, or both. + * The implementation may or may not rely on the forms to be consistent with each other. + * + *

Callers should construct and use a matcher rather than match pairs of locales directly. + * + * @param desired Desired locale. + * @param supported Supported locale. + * @param errorCode ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return value between 0 and 1, inclusive. + * @internal (has a known user) + */ + double internalMatch(const Locale &desired, const Locale &supported, UErrorCode &errorCode) const; +#endif // U_HIDE_INTERNAL_API + +private: + LocaleMatcher(const Builder &builder, UErrorCode &errorCode); + LocaleMatcher(const LocaleMatcher &other) = delete; + LocaleMatcher &operator=(const LocaleMatcher &other) = delete; + + int32_t putIfAbsent(const LSR &lsr, int32_t i, int32_t suppLength, UErrorCode &errorCode); + + int32_t getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remainingIter, UErrorCode &errorCode) const; + + const XLikelySubtags &likelySubtags; + const LocaleDistance &localeDistance; + int32_t thresholdDistance; + int32_t demotionPerDesiredLocale; + ULocMatchFavorSubtag favorSubtag; + ULocMatchDirection direction; + + // These are in input order. + const Locale ** supportedLocales; + LSR *lsrs; + int32_t supportedLocalesLength; + // These are in preference order: 1. Default locale 2. paradigm locales 3. others. + UHashtable *supportedLsrToIndex; // Map + // Array versions of the supportedLsrToIndex keys and values. + // The distance lookup loops over the supportedLSRs and returns the index of the best match. + const LSR **supportedLSRs; + int32_t *supportedIndexes; + int32_t supportedLSRsLength; + Locale *ownedDefaultLocale; + const Locale *defaultLocale; +}; + +U_NAMESPACE_END + +#endif // U_SHOW_CPLUSPLUS_API +#endif // __LOCALEMATCHER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localpointer.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localpointer.h new file mode 100644 index 0000000000000000000000000000000000000000..b8be3d7942eaccac5a22a27064d7a6d12f6fef5a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/localpointer.h @@ -0,0 +1,595 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2009-2016, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: localpointer.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2009nov13 +* created by: Markus W. Scherer +*/ + +#ifndef __LOCALPOINTER_H__ +#define __LOCALPOINTER_H__ + +/** + * \file + * \brief C++ API: "Smart pointers" for use with and in ICU4C C++ code. + * + * These classes are inspired by + * - std::auto_ptr + * - boost::scoped_ptr & boost::scoped_array + * - Taligent Safe Pointers (TOnlyPointerTo) + * + * but none of those provide for all of the goals for ICU smart pointers: + * - Smart pointer owns the object and releases it when it goes out of scope. + * - No transfer of ownership via copy/assignment to reduce misuse. Simpler & more robust. + * - ICU-compatible: No exceptions. + * - Need to be able to orphan/release the pointer and its ownership. + * - Need variants for normal C++ object pointers, C++ arrays, and ICU C service objects. + * + * For details see https://icu.unicode.org/design/cpp/scoped_ptr + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include + +U_NAMESPACE_BEGIN + +/** + * "Smart pointer" base class; do not use directly: use LocalPointer etc. + * + * Base class for smart pointer classes that do not throw exceptions. + * + * Do not use this base class directly, since it does not delete its pointer. + * A subclass must implement methods that delete the pointer: + * Destructor and adoptInstead(). + * + * There is no operator T *() provided because the programmer must decide + * whether to use getAlias() (without transfer of ownership) or orphan() + * (with transfer of ownership and NULLing of the pointer). + * + * @see LocalPointer + * @see LocalArray + * @see U_DEFINE_LOCAL_OPEN_POINTER + * @stable ICU 4.4 + */ +template +class LocalPointerBase { +public: + // No heap allocation. Use only on the stack. + static void* U_EXPORT2 operator new(size_t) = delete; + static void* U_EXPORT2 operator new[](size_t) = delete; +#if U_HAVE_PLACEMENT_NEW + static void* U_EXPORT2 operator new(size_t, void*) = delete; +#endif + + /** + * Constructor takes ownership. + * @param p simple pointer to an object that is adopted + * @stable ICU 4.4 + */ + explicit LocalPointerBase(T *p=nullptr) : ptr(p) {} + /** + * Destructor deletes the object it owns. + * Subclass must override: Base class does nothing. + * @stable ICU 4.4 + */ + ~LocalPointerBase() { /* delete ptr; */ } + /** + * nullptr check. + * @return true if ==nullptr + * @stable ICU 4.4 + */ + UBool isNull() const { return ptr==nullptr; } + /** + * nullptr check. + * @return true if !=nullptr + * @stable ICU 4.4 + */ + UBool isValid() const { return ptr!=nullptr; } + /** + * Comparison with a simple pointer, so that existing code + * with ==nullptr need not be changed. + * @param other simple pointer for comparison + * @return true if this pointer value equals other + * @stable ICU 4.4 + */ + bool operator==(const T *other) const { return ptr==other; } + /** + * Comparison with a simple pointer, so that existing code + * with !=nullptr need not be changed. + * @param other simple pointer for comparison + * @return true if this pointer value differs from other + * @stable ICU 4.4 + */ + bool operator!=(const T *other) const { return ptr!=other; } + /** + * Access without ownership change. + * @return the pointer value + * @stable ICU 4.4 + */ + T *getAlias() const { return ptr; } + /** + * Access without ownership change. + * @return the pointer value as a reference + * @stable ICU 4.4 + */ + T &operator*() const { return *ptr; } + /** + * Access without ownership change. + * @return the pointer value + * @stable ICU 4.4 + */ + T *operator->() const { return ptr; } + /** + * Gives up ownership; the internal pointer becomes nullptr. + * @return the pointer value; + * caller becomes responsible for deleting the object + * @stable ICU 4.4 + */ + T *orphan() { + T *p=ptr; + ptr=nullptr; + return p; + } + /** + * Deletes the object it owns, + * and adopts (takes ownership of) the one passed in. + * Subclass must override: Base class does not delete the object. + * @param p simple pointer to an object that is adopted + * @stable ICU 4.4 + */ + void adoptInstead(T *p) { + // delete ptr; + ptr=p; + } +protected: + /** + * Actual pointer. + * @internal + */ + T *ptr; +private: + // No comparison operators with other LocalPointerBases. + bool operator==(const LocalPointerBase &other); + bool operator!=(const LocalPointerBase &other); + // No ownership sharing: No copy constructor, no assignment operator. + LocalPointerBase(const LocalPointerBase &other); + void operator=(const LocalPointerBase &other); +}; + +/** + * "Smart pointer" class, deletes objects via the standard C++ delete operator. + * For most methods see the LocalPointerBase base class. + * + * Usage example: + * \code + * LocalPointer s(new UnicodeString((UChar32)0x50005)); + * int32_t length=s->length(); // 2 + * char16_t lead=s->charAt(0); // 0xd900 + * if(some condition) { return; } // no need to explicitly delete the pointer + * s.adoptInstead(new UnicodeString((char16_t)0xfffc)); + * length=s->length(); // 1 + * // no need to explicitly delete the pointer + * \endcode + * + * @see LocalPointerBase + * @stable ICU 4.4 + */ +template +class LocalPointer : public LocalPointerBase { +public: + using LocalPointerBase::operator*; + using LocalPointerBase::operator->; + /** + * Constructor takes ownership. + * @param p simple pointer to an object that is adopted + * @stable ICU 4.4 + */ + explicit LocalPointer(T *p=nullptr) : LocalPointerBase(p) {} + /** + * Constructor takes ownership and reports an error if nullptr. + * + * This constructor is intended to be used with other-class constructors + * that may report a failure UErrorCode, + * so that callers need to check only for U_FAILURE(errorCode) + * and not also separately for isNull(). + * + * @param p simple pointer to an object that is adopted + * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR + * if p==nullptr and no other failure code had been set + * @stable ICU 55 + */ + LocalPointer(T *p, UErrorCode &errorCode) : LocalPointerBase(p) { + if(p==nullptr && U_SUCCESS(errorCode)) { + errorCode=U_MEMORY_ALLOCATION_ERROR; + } + } + /** + * Move constructor, leaves src with isNull(). + * @param src source smart pointer + * @stable ICU 56 + */ + LocalPointer(LocalPointer &&src) noexcept : LocalPointerBase(src.ptr) { + src.ptr=nullptr; + } + + /** + * Constructs a LocalPointer from a C++11 std::unique_ptr. + * The LocalPointer steals the object owned by the std::unique_ptr. + * + * This constructor works via move semantics. If your std::unique_ptr is + * in a local variable, you must use std::move. + * + * @param p The std::unique_ptr from which the pointer will be stolen. + * @stable ICU 64 + */ + explicit LocalPointer(std::unique_ptr &&p) + : LocalPointerBase(p.release()) {} + + /** + * Destructor deletes the object it owns. + * @stable ICU 4.4 + */ + ~LocalPointer() { + delete LocalPointerBase::ptr; + } + /** + * Move assignment operator, leaves src with isNull(). + * The behavior is undefined if *this and src are the same object. + * @param src source smart pointer + * @return *this + * @stable ICU 56 + */ + LocalPointer &operator=(LocalPointer &&src) noexcept { + delete LocalPointerBase::ptr; + LocalPointerBase::ptr=src.ptr; + src.ptr=nullptr; + return *this; + } + + /** + * Move-assign from an std::unique_ptr to this LocalPointer. + * Steals the pointer from the std::unique_ptr. + * + * @param p The std::unique_ptr from which the pointer will be stolen. + * @return *this + * @stable ICU 64 + */ + LocalPointer &operator=(std::unique_ptr &&p) noexcept { + adoptInstead(p.release()); + return *this; + } + + /** + * Swap pointers. + * @param other other smart pointer + * @stable ICU 56 + */ + void swap(LocalPointer &other) noexcept { + T *temp=LocalPointerBase::ptr; + LocalPointerBase::ptr=other.ptr; + other.ptr=temp; + } + /** + * Non-member LocalPointer swap function. + * @param p1 will get p2's pointer + * @param p2 will get p1's pointer + * @stable ICU 56 + */ + friend inline void swap(LocalPointer &p1, LocalPointer &p2) noexcept { + p1.swap(p2); + } + /** + * Deletes the object it owns, + * and adopts (takes ownership of) the one passed in. + * @param p simple pointer to an object that is adopted + * @stable ICU 4.4 + */ + void adoptInstead(T *p) { + delete LocalPointerBase::ptr; + LocalPointerBase::ptr=p; + } + /** + * Deletes the object it owns, + * and adopts (takes ownership of) the one passed in. + * + * If U_FAILURE(errorCode), then the current object is retained and the new one deleted. + * + * If U_SUCCESS(errorCode) but the input pointer is nullptr, + * then U_MEMORY_ALLOCATION_ERROR is set, + * the current object is deleted, and nullptr is set. + * + * @param p simple pointer to an object that is adopted + * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR + * if p==nullptr and no other failure code had been set + * @stable ICU 55 + */ + void adoptInsteadAndCheckErrorCode(T *p, UErrorCode &errorCode) { + if(U_SUCCESS(errorCode)) { + delete LocalPointerBase::ptr; + LocalPointerBase::ptr=p; + if(p==nullptr) { + errorCode=U_MEMORY_ALLOCATION_ERROR; + } + } else { + delete p; + } + } + + /** + * Conversion operator to a C++11 std::unique_ptr. + * Disowns the object and gives it to the returned std::unique_ptr. + * + * This operator works via move semantics. If your LocalPointer is + * in a local variable, you must use std::move. + * + * @return An std::unique_ptr owning the pointer previously owned by this + * icu::LocalPointer. + * @stable ICU 64 + */ + operator std::unique_ptr () && { + return std::unique_ptr(LocalPointerBase::orphan()); + } +}; + +/** + * "Smart pointer" class, deletes objects via the C++ array delete[] operator. + * For most methods see the LocalPointerBase base class. + * Adds operator[] for array item access. + * + * Usage example: + * \code + * LocalArray a(new UnicodeString[2]); + * a[0].append((char16_t)0x61); + * if(some condition) { return; } // no need to explicitly delete the array + * a.adoptInstead(new UnicodeString[4]); + * a[3].append((char16_t)0x62).append((char16_t)0x63).reverse(); + * // no need to explicitly delete the array + * \endcode + * + * @see LocalPointerBase + * @stable ICU 4.4 + */ +template +class LocalArray : public LocalPointerBase { +public: + using LocalPointerBase::operator*; + using LocalPointerBase::operator->; + /** + * Constructor takes ownership. + * @param p simple pointer to an array of T objects that is adopted + * @stable ICU 4.4 + */ + explicit LocalArray(T *p=nullptr) : LocalPointerBase(p) {} + /** + * Constructor takes ownership and reports an error if nullptr. + * + * This constructor is intended to be used with other-class constructors + * that may report a failure UErrorCode, + * so that callers need to check only for U_FAILURE(errorCode) + * and not also separately for isNull(). + * + * @param p simple pointer to an array of T objects that is adopted + * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR + * if p==nullptr and no other failure code had been set + * @stable ICU 56 + */ + LocalArray(T *p, UErrorCode &errorCode) : LocalPointerBase(p) { + if(p==nullptr && U_SUCCESS(errorCode)) { + errorCode=U_MEMORY_ALLOCATION_ERROR; + } + } + /** + * Move constructor, leaves src with isNull(). + * @param src source smart pointer + * @stable ICU 56 + */ + LocalArray(LocalArray &&src) noexcept : LocalPointerBase(src.ptr) { + src.ptr=nullptr; + } + + /** + * Constructs a LocalArray from a C++11 std::unique_ptr of an array type. + * The LocalPointer steals the array owned by the std::unique_ptr. + * + * This constructor works via move semantics. If your std::unique_ptr is + * in a local variable, you must use std::move. + * + * @param p The std::unique_ptr from which the array will be stolen. + * @stable ICU 64 + */ + explicit LocalArray(std::unique_ptr &&p) + : LocalPointerBase(p.release()) {} + + /** + * Destructor deletes the array it owns. + * @stable ICU 4.4 + */ + ~LocalArray() { + delete[] LocalPointerBase::ptr; + } + /** + * Move assignment operator, leaves src with isNull(). + * The behavior is undefined if *this and src are the same object. + * @param src source smart pointer + * @return *this + * @stable ICU 56 + */ + LocalArray &operator=(LocalArray &&src) noexcept { + delete[] LocalPointerBase::ptr; + LocalPointerBase::ptr=src.ptr; + src.ptr=nullptr; + return *this; + } + + /** + * Move-assign from an std::unique_ptr to this LocalPointer. + * Steals the array from the std::unique_ptr. + * + * @param p The std::unique_ptr from which the array will be stolen. + * @return *this + * @stable ICU 64 + */ + LocalArray &operator=(std::unique_ptr &&p) noexcept { + adoptInstead(p.release()); + return *this; + } + + /** + * Swap pointers. + * @param other other smart pointer + * @stable ICU 56 + */ + void swap(LocalArray &other) noexcept { + T *temp=LocalPointerBase::ptr; + LocalPointerBase::ptr=other.ptr; + other.ptr=temp; + } + /** + * Non-member LocalArray swap function. + * @param p1 will get p2's pointer + * @param p2 will get p1's pointer + * @stable ICU 56 + */ + friend inline void swap(LocalArray &p1, LocalArray &p2) noexcept { + p1.swap(p2); + } + /** + * Deletes the array it owns, + * and adopts (takes ownership of) the one passed in. + * @param p simple pointer to an array of T objects that is adopted + * @stable ICU 4.4 + */ + void adoptInstead(T *p) { + delete[] LocalPointerBase::ptr; + LocalPointerBase::ptr=p; + } + /** + * Deletes the array it owns, + * and adopts (takes ownership of) the one passed in. + * + * If U_FAILURE(errorCode), then the current array is retained and the new one deleted. + * + * If U_SUCCESS(errorCode) but the input pointer is nullptr, + * then U_MEMORY_ALLOCATION_ERROR is set, + * the current array is deleted, and nullptr is set. + * + * @param p simple pointer to an array of T objects that is adopted + * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR + * if p==nullptr and no other failure code had been set + * @stable ICU 56 + */ + void adoptInsteadAndCheckErrorCode(T *p, UErrorCode &errorCode) { + if(U_SUCCESS(errorCode)) { + delete[] LocalPointerBase::ptr; + LocalPointerBase::ptr=p; + if(p==nullptr) { + errorCode=U_MEMORY_ALLOCATION_ERROR; + } + } else { + delete[] p; + } + } + /** + * Array item access (writable). + * No index bounds check. + * @param i array index + * @return reference to the array item + * @stable ICU 4.4 + */ + T &operator[](ptrdiff_t i) const { return LocalPointerBase::ptr[i]; } + + /** + * Conversion operator to a C++11 std::unique_ptr. + * Disowns the object and gives it to the returned std::unique_ptr. + * + * This operator works via move semantics. If your LocalPointer is + * in a local variable, you must use std::move. + * + * @return An std::unique_ptr owning the pointer previously owned by this + * icu::LocalPointer. + * @stable ICU 64 + */ + operator std::unique_ptr () && { + return std::unique_ptr(LocalPointerBase::orphan()); + } +}; + +/** + * \def U_DEFINE_LOCAL_OPEN_POINTER + * "Smart pointer" definition macro, deletes objects via the closeFunction. + * Defines a subclass of LocalPointerBase which works just + * like LocalPointer except that this subclass will use the closeFunction + * rather than the C++ delete operator. + * + * Usage example: + * \code + * LocalUCaseMapPointer csm(ucasemap_open(localeID, options, &errorCode)); + * utf8OutLength=ucasemap_utf8ToLower(csm.getAlias(), + * utf8Out, (int32_t)sizeof(utf8Out), + * utf8In, utf8InLength, &errorCode); + * if(U_FAILURE(errorCode)) { return; } // no need to explicitly delete the UCaseMap + * \endcode + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +#define U_DEFINE_LOCAL_OPEN_POINTER(LocalPointerClassName, Type, closeFunction) \ + class LocalPointerClassName : public LocalPointerBase { \ + public: \ + using LocalPointerBase::operator*; \ + using LocalPointerBase::operator->; \ + explicit LocalPointerClassName(Type *p=nullptr) : LocalPointerBase(p) {} \ + LocalPointerClassName(LocalPointerClassName &&src) noexcept \ + : LocalPointerBase(src.ptr) { \ + src.ptr=nullptr; \ + } \ + /* TODO: Be agnostic of the deleter function signature from the user-provided std::unique_ptr? */ \ + explicit LocalPointerClassName(std::unique_ptr &&p) \ + : LocalPointerBase(p.release()) {} \ + ~LocalPointerClassName() { if (ptr != nullptr) { closeFunction(ptr); } } \ + LocalPointerClassName &operator=(LocalPointerClassName &&src) noexcept { \ + if (ptr != nullptr) { closeFunction(ptr); } \ + LocalPointerBase::ptr=src.ptr; \ + src.ptr=nullptr; \ + return *this; \ + } \ + /* TODO: Be agnostic of the deleter function signature from the user-provided std::unique_ptr? */ \ + LocalPointerClassName &operator=(std::unique_ptr &&p) { \ + adoptInstead(p.release()); \ + return *this; \ + } \ + void swap(LocalPointerClassName &other) noexcept { \ + Type *temp=LocalPointerBase::ptr; \ + LocalPointerBase::ptr=other.ptr; \ + other.ptr=temp; \ + } \ + friend inline void swap(LocalPointerClassName &p1, LocalPointerClassName &p2) noexcept { \ + p1.swap(p2); \ + } \ + void adoptInstead(Type *p) { \ + if (ptr != nullptr) { closeFunction(ptr); } \ + ptr=p; \ + } \ + operator std::unique_ptr () && { \ + return std::unique_ptr(LocalPointerBase::orphan(), closeFunction); \ + } \ + } + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ +#endif /* __LOCALPOINTER_H__ */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locdspnm.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locdspnm.h new file mode 100644 index 0000000000000000000000000000000000000000..4f06f857044c6e9bf5119122394bd2458f760919 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locdspnm.h @@ -0,0 +1,211 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 2010-2016, International Business Machines Corporation and +* others. All Rights Reserved. +****************************************************************************** +*/ + +#ifndef LOCDSPNM_H +#define LOCDSPNM_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Provides display names of Locale and its components. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/locid.h" +#include "unicode/strenum.h" +#include "unicode/uscript.h" +#include "unicode/uldnames.h" +#include "unicode/udisplaycontext.h" + +U_NAMESPACE_BEGIN + +/** + * Returns display names of Locales and components of Locales. For + * more information on language, script, region, variant, key, and + * values, see Locale. + * @stable ICU 4.4 + */ +class U_COMMON_API LocaleDisplayNames : public UObject { +public: + /** + * Destructor. + * @stable ICU 4.4 + */ + virtual ~LocaleDisplayNames(); + + /** + * Convenience overload of + * {@link #createInstance(const Locale& locale, UDialectHandling dialectHandling)} + * that specifies STANDARD dialect handling. + * @param locale the display locale + * @return a LocaleDisplayNames instance + * @stable ICU 4.4 + */ + inline static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale); + + /** + * Returns an instance of LocaleDisplayNames that returns names + * formatted for the provided locale, using the provided + * dialectHandling. + * + * @param locale the display locale + * @param dialectHandling how to select names for locales + * @return a LocaleDisplayNames instance + * @stable ICU 4.4 + */ + static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale, + UDialectHandling dialectHandling); + + /** + * Returns an instance of LocaleDisplayNames that returns names formatted + * for the provided locale, using the provided UDisplayContext settings. + * + * @param locale the display locale + * @param contexts List of one or more context settings (e.g. for dialect + * handling, capitalization, etc. + * @param length Number of items in the contexts list + * @return a LocaleDisplayNames instance + * @stable ICU 51 + */ + static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale, + UDisplayContext *contexts, int32_t length); + + // getters for state + /** + * Returns the locale used to determine the display names. This is + * not necessarily the same locale passed to {@link #createInstance}. + * @return the display locale + * @stable ICU 4.4 + */ + virtual const Locale& getLocale() const = 0; + + /** + * Returns the dialect handling used in the display names. + * @return the dialect handling enum + * @stable ICU 4.4 + */ + virtual UDialectHandling getDialectHandling() const = 0; + + /** + * Returns the UDisplayContext value for the specified UDisplayContextType. + * @param type the UDisplayContextType whose value to return + * @return the UDisplayContext for the specified type. + * @stable ICU 51 + */ + virtual UDisplayContext getContext(UDisplayContextType type) const = 0; + + // names for entire locales + /** + * Returns the display name of the provided locale. + * @param locale the locale whose display name to return + * @param result receives the locale's display name + * @return the display name of the provided locale + * @stable ICU 4.4 + */ + virtual UnicodeString& localeDisplayName(const Locale& locale, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided locale id. + * @param localeId the id of the locale whose display name to return + * @param result receives the locale's display name + * @return the display name of the provided locale + * @stable ICU 4.4 + */ + virtual UnicodeString& localeDisplayName(const char* localeId, + UnicodeString& result) const = 0; + + // names for components of a locale id + /** + * Returns the display name of the provided language code. + * @param lang the language code + * @param result receives the language code's display name + * @return the display name of the provided language code + * @stable ICU 4.4 + */ + virtual UnicodeString& languageDisplayName(const char* lang, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided script code. + * @param script the script code + * @param result receives the script code's display name + * @return the display name of the provided script code + * @stable ICU 4.4 + */ + virtual UnicodeString& scriptDisplayName(const char* script, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided script code. + * @param scriptCode the script code number + * @param result receives the script code's display name + * @return the display name of the provided script code + * @stable ICU 4.4 + */ + virtual UnicodeString& scriptDisplayName(UScriptCode scriptCode, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided region code. + * @param region the region code + * @param result receives the region code's display name + * @return the display name of the provided region code + * @stable ICU 4.4 + */ + virtual UnicodeString& regionDisplayName(const char* region, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided variant. + * @param variant the variant string + * @param result receives the variant's display name + * @return the display name of the provided variant + * @stable ICU 4.4 + */ + virtual UnicodeString& variantDisplayName(const char* variant, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided locale key. + * @param key the locale key name + * @param result receives the locale key's display name + * @return the display name of the provided locale key + * @stable ICU 4.4 + */ + virtual UnicodeString& keyDisplayName(const char* key, + UnicodeString& result) const = 0; + + /** + * Returns the display name of the provided value (used with the provided key). + * @param key the locale key name + * @param value the locale key's value + * @param result receives the value's display name + * @return the display name of the provided value + * @stable ICU 4.4 + */ + virtual UnicodeString& keyValueDisplayName(const char* key, const char* value, + UnicodeString& result) const = 0; +}; + +inline LocaleDisplayNames* LocaleDisplayNames::createInstance(const Locale& locale) { + return LocaleDisplayNames::createInstance(locale, ULDN_STANDARD_NAMES); +} + +U_NAMESPACE_END + +#endif + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locid.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locid.h new file mode 100644 index 0000000000000000000000000000000000000000..a6fbbb70418f510868d5ab878e38ebfb279fb650 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/locid.h @@ -0,0 +1,1272 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1996-2015, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* File locid.h +* +* Created by: Helena Shih +* +* Modification History: +* +* Date Name Description +* 02/11/97 aliu Changed gLocPath to fgLocPath and added methods to +* get and set it. +* 04/02/97 aliu Made operator!= inline; fixed return value of getName(). +* 04/15/97 aliu Cleanup for AIX/Win32. +* 04/24/97 aliu Numerous changes per code review. +* 08/18/98 stephen Added tokenizeString(),changed getDisplayName() +* 09/08/98 stephen Moved definition of kEmptyString for Mac Port +* 11/09/99 weiv Added const char * getName() const; +* 04/12/00 srl removing unicodestring api's and cached hash code +* 08/10/01 grhoten Change the static Locales to accessor functions +****************************************************************************** +*/ + +#ifndef LOCID_H +#define LOCID_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/bytestream.h" +#include "unicode/localpointer.h" +#include "unicode/strenum.h" +#include "unicode/stringpiece.h" +#include "unicode/uobject.h" +#include "unicode/putil.h" +#include "unicode/uloc.h" + +/** + * \file + * \brief C++ API: Locale ID object. + */ + +U_NAMESPACE_BEGIN + +// Forward Declarations +void U_CALLCONV locale_available_init(); /**< @internal */ + +class StringEnumeration; +class UnicodeString; + +/** + * A Locale object represents a specific geographical, political, + * or cultural region. An operation that requires a Locale to perform + * its task is called locale-sensitive and uses the Locale + * to tailor information for the user. For example, displaying a number + * is a locale-sensitive operation--the number should be formatted + * according to the customs/conventions of the user's native country, + * region, or culture. + * + * The Locale class is not suitable for subclassing. + * + *

+ * You can create a Locale object using the constructor in + * this class: + * \htmlonly

\endhtmlonly + *
+ *       Locale( const   char*  language,
+ *               const   char*  country,
+ *               const   char*  variant);
+ * 
+ * \htmlonly
\endhtmlonly + * The first argument to the constructors is a valid ISO + * Language Code. These codes are the lower-case two-letter + * codes as defined by ISO-639. + * You can find a full list of these codes at: + *
+ * http://www.loc.gov/standards/iso639-2/ + * + *

+ * The second argument to the constructors is a valid ISO Country + * Code. These codes are the upper-case two-letter codes + * as defined by ISO-3166. + * You can find a full list of these codes at a number of sites, such as: + *
+ * http://www.iso.org/iso/en/prods-services/iso3166ma/index.html + * + *

+ * The third constructor requires a third argument--the Variant. + * The Variant codes are vendor and browser-specific. + * For example, use REVISED for a language's revised script orthography, and POSIX for POSIX. + * Where there are two variants, separate them with an underscore, and + * put the most important one first. For + * example, a Traditional Spanish collation might be referenced, with + * "ES", "ES", "Traditional_POSIX". + * + *

+ * Because a Locale object is just an identifier for a region, + * no validity check is performed when you construct a Locale. + * If you want to see whether particular resources are available for the + * Locale you construct, you must query those resources. For + * example, ask the NumberFormat for the locales it supports + * using its getAvailableLocales method. + *
Note: When you ask for a resource for a particular + * locale, you get back the best available match, not necessarily + * precisely what you asked for. For more information, look at + * ResourceBundle. + * + *

+ * The Locale class provides a number of convenient constants + * that you can use to create Locale objects for commonly used + * locales. For example, the following refers to a Locale object + * for the United States: + * \htmlonly

\endhtmlonly + *
+ *       Locale::getUS()
+ * 
+ * \htmlonly
\endhtmlonly + * + *

+ * Once you've created a Locale you can query it for information about + * itself. Use getCountry to get the ISO Country Code and + * getLanguage to get the ISO Language Code. You can + * use getDisplayCountry to get the + * name of the country suitable for displaying to the user. Similarly, + * you can use getDisplayLanguage to get the name of + * the language suitable for displaying to the user. Interestingly, + * the getDisplayXXX methods are themselves locale-sensitive + * and have two versions: one that uses the default locale and one + * that takes a locale as an argument and displays the name or country in + * a language appropriate to that locale. + * + *

+ * ICU provides a number of classes that perform locale-sensitive + * operations. For example, the NumberFormat class formats + * numbers, currency, or percentages in a locale-sensitive manner. Classes + * such as NumberFormat have a number of convenience methods + * for creating a default object of that type. For example, the + * NumberFormat class provides these three convenience methods + * for creating a default NumberFormat object: + * \htmlonly

\endhtmlonly + *
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     Locale myLocale;
+ *     NumberFormat *nf;
+ *
+ *     nf = NumberFormat::createInstance( success );          delete nf;
+ *     nf = NumberFormat::createCurrencyInstance( success );  delete nf;
+ *     nf = NumberFormat::createPercentInstance( success );   delete nf;
+ * 
+ * \htmlonly
\endhtmlonly + * Each of these methods has two variants; one with an explicit locale + * and one without; the latter using the default locale. + * \htmlonly
\endhtmlonly + *
+ *     nf = NumberFormat::createInstance( myLocale, success );          delete nf;
+ *     nf = NumberFormat::createCurrencyInstance( myLocale, success );  delete nf;
+ *     nf = NumberFormat::createPercentInstance( myLocale, success );   delete nf;
+ * 
+ * \htmlonly
\endhtmlonly + * A Locale is the mechanism for identifying the kind of object + * (NumberFormat) that you would like to get. The locale is + * just a mechanism for identifying objects, + * not a container for the objects themselves. + * + *

+ * Each class that performs locale-sensitive operations allows you + * to get all the available objects of that type. You can sift + * through these objects by language, country, or variant, + * and use the display names to present a menu to the user. + * For example, you can create a menu of all the collation objects + * suitable for a given language. Such classes implement these + * three class methods: + * \htmlonly

\endhtmlonly + *
+ *       static Locale* getAvailableLocales(int32_t& numLocales)
+ *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
+ *                                            const Locale&  displayLocale,
+ *                                            UnicodeString& displayName)
+ *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
+ *                                            UnicodeString& displayName)
+ * 
+ * \htmlonly
\endhtmlonly + * + * @stable ICU 2.0 + * @see ResourceBundle + */ +class U_COMMON_API Locale : public UObject { +public: + /** Useful constant for the Root locale. @stable ICU 4.4 */ + static const Locale &U_EXPORT2 getRoot(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getEnglish(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getFrench(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getGerman(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getItalian(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getJapanese(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getKorean(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getChinese(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getSimplifiedChinese(void); + /** Useful constant for this language. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getTraditionalChinese(void); + + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getFrance(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getGermany(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getItaly(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getJapan(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getKorea(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getChina(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getPRC(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getTaiwan(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getUK(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getUS(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getCanada(void); + /** Useful constant for this country/region. @stable ICU 2.0 */ + static const Locale &U_EXPORT2 getCanadaFrench(void); + + + /** + * Construct a default locale object, a Locale for the default locale ID. + * + * @see getDefault + * @see uloc_getDefault + * @stable ICU 2.0 + */ + Locale(); + + /** + * Construct a locale from language, country, variant. + * If an error occurs, then the constructed object will be "bogus" + * (isBogus() will return true). + * + * @param language Lowercase two-letter or three-letter ISO-639 code. + * This parameter can instead be an ICU style C locale (e.g. "en_US"), + * but the other parameters must not be used. + * This parameter can be nullptr; if so, + * the locale is initialized to match the current default locale. + * (This is the same as using the default constructor.) + * Please note: The Java Locale class does NOT accept the form + * 'new Locale("en_US")' but only 'new Locale("en","US")' + * + * @param country Uppercase two-letter ISO-3166 code. (optional) + * @param variant Uppercase vendor and browser specific code. See class + * description. (optional) + * @param keywordsAndValues A string consisting of keyword/values pairs, such as + * "collation=phonebook;currency=euro" + * + * @see getDefault + * @see uloc_getDefault + * @stable ICU 2.0 + */ + Locale( const char * language, + const char * country = 0, + const char * variant = 0, + const char * keywordsAndValues = 0); + + /** + * Initializes a Locale object from another Locale object. + * + * @param other The Locale object being copied in. + * @stable ICU 2.0 + */ + Locale(const Locale& other); + + /** + * Move constructor; might leave source in bogus state. + * This locale will have the same contents that the source locale had. + * + * @param other The Locale object being moved in. + * @stable ICU 63 + */ + Locale(Locale&& other) noexcept; + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~Locale() ; + + /** + * Replaces the entire contents of *this with the specified value. + * + * @param other The Locale object being copied in. + * @return *this + * @stable ICU 2.0 + */ + Locale& operator=(const Locale& other); + + /** + * Move assignment operator; might leave source in bogus state. + * This locale will have the same contents that the source locale had. + * The behavior is undefined if *this and the source are the same object. + * + * @param other The Locale object being moved in. + * @return *this + * @stable ICU 63 + */ + Locale& operator=(Locale&& other) noexcept; + + /** + * Checks if two locale keys are the same. + * + * @param other The locale key object to be compared with this. + * @return true if the two locale keys are the same, false otherwise. + * @stable ICU 2.0 + */ + bool operator==(const Locale& other) const; + + /** + * Checks if two locale keys are not the same. + * + * @param other The locale key object to be compared with this. + * @return true if the two locale keys are not the same, false + * otherwise. + * @stable ICU 2.0 + */ + inline bool operator!=(const Locale& other) const; + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + Locale *clone() const; + +#ifndef U_HIDE_SYSTEM_API + /** + * Common methods of getting the current default Locale. Used for the + * presentation: menus, dialogs, etc. Generally set once when your applet or + * application is initialized, then never reset. (If you do reset the + * default locale, you probably want to reload your GUI, so that the change + * is reflected in your interface.) + * + * More advanced programs will allow users to use different locales for + * different fields, e.g. in a spreadsheet. + * + * Note that the initial setting will match the host system. + * @return a reference to the Locale object for the default locale ID + * @system + * @stable ICU 2.0 + */ + static const Locale& U_EXPORT2 getDefault(void); + + /** + * Sets the default. Normally set once at the beginning of a process, + * then never reset. + * setDefault() only changes ICU's default locale ID, not + * the default locale ID of the runtime environment. + * + * @param newLocale Locale to set to. If nullptr, set to the value obtained + * from the runtime environment. + * @param success The error code. + * @system + * @stable ICU 2.0 + */ + static void U_EXPORT2 setDefault(const Locale& newLocale, + UErrorCode& success); +#endif /* U_HIDE_SYSTEM_API */ + + /** + * Returns a Locale for the specified BCP47 language tag string. + * If the specified language tag contains any ill-formed subtags, + * the first such subtag and all following subtags are ignored. + *

+ * This implements the 'Language-Tag' production of BCP 47, and so + * supports legacy language tags (marked as “Type: grandfathered” in BCP 47) + * (regular and irregular) as well as private use language tags. + * + * Private use tags are represented as 'x-whatever', + * and legacy tags are converted to their canonical replacements where they exist. + * + * Note that a few legacy tags have no modern replacement; + * these will be converted using the fallback described in + * the first paragraph, so some information might be lost. + * + * @param tag the input BCP47 language tag. + * @param status error information if creating the Locale failed. + * @return the Locale for the specified BCP47 language tag. + * @stable ICU 63 + */ + static Locale U_EXPORT2 forLanguageTag(StringPiece tag, UErrorCode& status); + + /** + * Returns a well-formed language tag for this Locale. + *

+ * Note: Any locale fields which do not satisfy the BCP47 syntax + * requirement will be silently omitted from the result. + * + * If this function fails, partial output may have been written to the sink. + * + * @param sink the output sink receiving the BCP47 language + * tag for this Locale. + * @param status error information if creating the language tag failed. + * @stable ICU 63 + */ + void toLanguageTag(ByteSink& sink, UErrorCode& status) const; + + /** + * Returns a well-formed language tag for this Locale. + *

+ * Note: Any locale fields which do not satisfy the BCP47 syntax + * requirement will be silently omitted from the result. + * + * @param status error information if creating the language tag failed. + * @return the BCP47 language tag for this Locale. + * @stable ICU 63 + */ + template + inline StringClass toLanguageTag(UErrorCode& status) const; + + /** + * Creates a locale which has had minimal canonicalization + * as per uloc_getName(). + * @param name The name to create from. If name is null, + * the default Locale is used. + * @return new locale object + * @stable ICU 2.0 + * @see uloc_getName + */ + static Locale U_EXPORT2 createFromName(const char *name); + + /** + * Creates a locale from the given string after canonicalizing + * the string according to CLDR by calling uloc_canonicalize(). + * @param name the locale ID to create from. Must not be nullptr. + * @return a new locale object corresponding to the given name + * @stable ICU 3.0 + * @see uloc_canonicalize + */ + static Locale U_EXPORT2 createCanonical(const char* name); + + /** + * Returns the locale's ISO-639 language code. + * @return An alias to the code + * @stable ICU 2.0 + */ + inline const char * getLanguage( ) const; + + /** + * Returns the locale's ISO-15924 abbreviation script code. + * @return An alias to the code + * @see uscript_getShortName + * @see uscript_getCode + * @stable ICU 2.8 + */ + inline const char * getScript( ) const; + + /** + * Returns the locale's ISO-3166 country code. + * @return An alias to the code + * @stable ICU 2.0 + */ + inline const char * getCountry( ) const; + + /** + * Returns the locale's variant code. + * @return An alias to the code + * @stable ICU 2.0 + */ + inline const char * getVariant( ) const; + + /** + * Returns the programmatic name of the entire locale, with the language, + * country and variant separated by underbars. If a field is missing, up + * to two leading underbars will occur. Example: "en", "de_DE", "en_US_WIN", + * "de__POSIX", "fr__MAC", "__MAC", "_MT", "_FR_EURO" + * @return A pointer to "name". + * @stable ICU 2.0 + */ + inline const char * getName() const; + + /** + * Returns the programmatic name of the entire locale as getName() would return, + * but without keywords. + * @return A pointer to "name". + * @see getName + * @stable ICU 2.8 + */ + const char * getBaseName() const; + + /** + * Add the likely subtags for this Locale, per the algorithm described + * in the following CLDR technical report: + * + * http://www.unicode.org/reports/tr35/#Likely_Subtags + * + * If this Locale is already in the maximal form, or not valid, or there is + * no data available for maximization, the Locale will be unchanged. + * + * For example, "und-Zzzz" cannot be maximized, since there is no + * reasonable maximization. + * + * Examples: + * + * "en" maximizes to "en_Latn_US" + * + * "de" maximizes to "de_Latn_US" + * + * "sr" maximizes to "sr_Cyrl_RS" + * + * "sh" maximizes to "sr_Latn_RS" (Note this will not reverse.) + * + * "zh_Hani" maximizes to "zh_Hans_CN" (Note this will not reverse.) + * + * @param status error information if maximizing this Locale failed. + * If this Locale is not well-formed, the error code is + * U_ILLEGAL_ARGUMENT_ERROR. + * @stable ICU 63 + */ + void addLikelySubtags(UErrorCode& status); + + /** + * Minimize the subtags for this Locale, per the algorithm described + * in the following CLDR technical report: + * + * http://www.unicode.org/reports/tr35/#Likely_Subtags + * + * If this Locale is already in the minimal form, or not valid, or there is + * no data available for minimization, the Locale will be unchanged. + * + * Since the minimization algorithm relies on proper maximization, see the + * comments for addLikelySubtags for reasons why there might not be any + * data. + * + * Examples: + * + * "en_Latn_US" minimizes to "en" + * + * "de_Latn_US" minimizes to "de" + * + * "sr_Cyrl_RS" minimizes to "sr" + * + * "zh_Hant_TW" minimizes to "zh_TW" (The region is preferred to the + * script, and minimizing to "zh" would imply "zh_Hans_CN".) + * + * @param status error information if maximizing this Locale failed. + * If this Locale is not well-formed, the error code is + * U_ILLEGAL_ARGUMENT_ERROR. + * @stable ICU 63 + */ + void minimizeSubtags(UErrorCode& status); + + /** + * Canonicalize the locale ID of this object according to CLDR. + * @param status the status code + * @stable ICU 67 + * @see createCanonical + */ + void canonicalize(UErrorCode& status); + + /** + * Gets the list of keywords for the specified locale. + * + * @param status the status code + * @return pointer to StringEnumeration class, or nullptr if there are no keywords. + * Client must dispose of it by calling delete. + * @see getKeywords + * @stable ICU 2.8 + */ + StringEnumeration * createKeywords(UErrorCode &status) const; + + /** + * Gets the list of Unicode keywords for the specified locale. + * + * @param status the status code + * @return pointer to StringEnumeration class, or nullptr if there are no keywords. + * Client must dispose of it by calling delete. + * @see getUnicodeKeywords + * @stable ICU 63 + */ + StringEnumeration * createUnicodeKeywords(UErrorCode &status) const; + + /** + * Gets the set of keywords for this Locale. + * + * A wrapper to call createKeywords() and write the resulting + * keywords as standard strings (or compatible objects) into any kind of + * container that can be written to by an STL style output iterator. + * + * @param iterator an STL style output iterator to write the keywords to. + * @param status error information if creating set of keywords failed. + * @stable ICU 63 + */ + template + inline void getKeywords(OutputIterator iterator, UErrorCode& status) const; + + /** + * Gets the set of Unicode keywords for this Locale. + * + * A wrapper to call createUnicodeKeywords() and write the resulting + * keywords as standard strings (or compatible objects) into any kind of + * container that can be written to by an STL style output iterator. + * + * @param iterator an STL style output iterator to write the keywords to. + * @param status error information if creating set of keywords failed. + * @stable ICU 63 + */ + template + inline void getUnicodeKeywords(OutputIterator iterator, UErrorCode& status) const; + + /** + * Gets the value for a keyword. + * + * This uses legacy keyword=value pairs, like "collation=phonebook". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword for which we want the value. Case insensitive. + * @param buffer The buffer to receive the keyword value. + * @param bufferCapacity The capacity of receiving buffer + * @param status Returns any error information while performing this operation. + * @return the length of the keyword value + * + * @stable ICU 2.8 + */ + int32_t getKeywordValue(const char* keywordName, char *buffer, int32_t bufferCapacity, UErrorCode &status) const; + + /** + * Gets the value for a keyword. + * + * This uses legacy keyword=value pairs, like "collation=phonebook". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword for which we want the value. + * @param sink the sink to receive the keyword value. + * @param status error information if getting the value failed. + * @stable ICU 63 + */ + void getKeywordValue(StringPiece keywordName, ByteSink& sink, UErrorCode& status) const; + + /** + * Gets the value for a keyword. + * + * This uses legacy keyword=value pairs, like "collation=phonebook". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword for which we want the value. + * @param status error information if getting the value failed. + * @return the keyword value. + * @stable ICU 63 + */ + template + inline StringClass getKeywordValue(StringPiece keywordName, UErrorCode& status) const; + + /** + * Gets the Unicode value for a Unicode keyword. + * + * This uses Unicode key-value pairs, like "co-phonebk". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword for which we want the value. + * @param sink the sink to receive the keyword value. + * @param status error information if getting the value failed. + * @stable ICU 63 + */ + void getUnicodeKeywordValue(StringPiece keywordName, ByteSink& sink, UErrorCode& status) const; + + /** + * Gets the Unicode value for a Unicode keyword. + * + * This uses Unicode key-value pairs, like "co-phonebk". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword for which we want the value. + * @param status error information if getting the value failed. + * @return the keyword value. + * @stable ICU 63 + */ + template + inline StringClass getUnicodeKeywordValue(StringPiece keywordName, UErrorCode& status) const; + + /** + * Sets or removes the value for a keyword. + * + * For removing all keywords, use getBaseName(), + * and construct a new Locale if it differs from getName(). + * + * This uses legacy keyword=value pairs, like "collation=phonebook". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword to be set. Case insensitive. + * @param keywordValue value of the keyword to be set. If 0-length or + * nullptr, will result in the keyword being removed. No error is given if + * that keyword does not exist. + * @param status Returns any error information while performing this operation. + * + * @stable ICU 49 + */ + void setKeywordValue(const char* keywordName, const char* keywordValue, UErrorCode &status); + + /** + * Sets or removes the value for a keyword. + * + * For removing all keywords, use getBaseName(), + * and construct a new Locale if it differs from getName(). + * + * This uses legacy keyword=value pairs, like "collation=phonebook". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword to be set. + * @param keywordValue value of the keyword to be set. If 0-length or + * nullptr, will result in the keyword being removed. No error is given if + * that keyword does not exist. + * @param status Returns any error information while performing this operation. + * @stable ICU 63 + */ + void setKeywordValue(StringPiece keywordName, StringPiece keywordValue, UErrorCode& status); + + /** + * Sets or removes the Unicode value for a Unicode keyword. + * + * For removing all keywords, use getBaseName(), + * and construct a new Locale if it differs from getName(). + * + * This uses Unicode key-value pairs, like "co-phonebk". + * + * ICU4C doesn't do automatic conversion between legacy and Unicode + * keywords and values in getters and setters (as opposed to ICU4J). + * + * @param keywordName name of the keyword to be set. + * @param keywordValue value of the keyword to be set. If 0-length or + * nullptr, will result in the keyword being removed. No error is given if + * that keyword does not exist. + * @param status Returns any error information while performing this operation. + * @stable ICU 63 + */ + void setUnicodeKeywordValue(StringPiece keywordName, StringPiece keywordValue, UErrorCode& status); + + /** + * returns the locale's three-letter language code, as specified + * in ISO draft standard ISO-639-2. + * @return An alias to the code, or an empty string + * @stable ICU 2.0 + */ + const char * getISO3Language() const; + + /** + * Fills in "name" with the locale's three-letter ISO-3166 country code. + * @return An alias to the code, or an empty string + * @stable ICU 2.0 + */ + const char * getISO3Country() const; + + /** + * Returns the Windows LCID value corresponding to this locale. + * This value is stored in the resource data for the locale as a one-to-four-digit + * hexadecimal number. If the resource is missing, in the wrong format, or + * there is no Windows LCID value that corresponds to this locale, returns 0. + * @stable ICU 2.0 + */ + uint32_t getLCID(void) const; + + /** + * Returns whether this locale's script is written right-to-left. + * If there is no script subtag, then the likely script is used, see uloc_addLikelySubtags(). + * If no likely script is known, then false is returned. + * + * A script is right-to-left according to the CLDR script metadata + * which corresponds to whether the script's letters have Bidi_Class=R or AL. + * + * Returns true for "ar" and "en-Hebr", false for "zh" and "fa-Cyrl". + * + * @return true if the locale's script is written right-to-left + * @stable ICU 54 + */ + UBool isRightToLeft() const; + + /** + * Fills in "dispLang" with the name of this locale's language in a format suitable for + * user display in the default locale. For example, if the locale's language code is + * "fr" and the default locale's language code is "en", this function would set + * dispLang to "French". + * @param dispLang Receives the language's display name. + * @return A reference to "dispLang". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayLanguage(UnicodeString& dispLang) const; + + /** + * Fills in "dispLang" with the name of this locale's language in a format suitable for + * user display in the locale specified by "displayLocale". For example, if the locale's + * language code is "en" and displayLocale's language code is "fr", this function would set + * dispLang to "Anglais". + * @param displayLocale Specifies the locale to be used to display the name. In other words, + * if the locale's language code is "en", passing Locale::getFrench() for + * displayLocale would result in "Anglais", while passing Locale::getGerman() + * for displayLocale would result in "Englisch". + * @param dispLang Receives the language's display name. + * @return A reference to "dispLang". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayLanguage( const Locale& displayLocale, + UnicodeString& dispLang) const; + + /** + * Fills in "dispScript" with the name of this locale's script in a format suitable + * for user display in the default locale. For example, if the locale's script code + * is "LATN" and the default locale's language code is "en", this function would set + * dispScript to "Latin". + * @param dispScript Receives the scripts's display name. + * @return A reference to "dispScript". + * @stable ICU 2.8 + */ + UnicodeString& getDisplayScript( UnicodeString& dispScript) const; + + /** + * Fills in "dispScript" with the name of this locale's country in a format suitable + * for user display in the locale specified by "displayLocale". For example, if the locale's + * script code is "LATN" and displayLocale's language code is "en", this function would set + * dispScript to "Latin". + * @param displayLocale Specifies the locale to be used to display the name. In other + * words, if the locale's script code is "LATN", passing + * Locale::getFrench() for displayLocale would result in "", while + * passing Locale::getGerman() for displayLocale would result in + * "". + * @param dispScript Receives the scripts's display name. + * @return A reference to "dispScript". + * @stable ICU 2.8 + */ + UnicodeString& getDisplayScript( const Locale& displayLocale, + UnicodeString& dispScript) const; + + /** + * Fills in "dispCountry" with the name of this locale's country in a format suitable + * for user display in the default locale. For example, if the locale's country code + * is "FR" and the default locale's language code is "en", this function would set + * dispCountry to "France". + * @param dispCountry Receives the country's display name. + * @return A reference to "dispCountry". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayCountry( UnicodeString& dispCountry) const; + + /** + * Fills in "dispCountry" with the name of this locale's country in a format suitable + * for user display in the locale specified by "displayLocale". For example, if the locale's + * country code is "US" and displayLocale's language code is "fr", this function would set + * dispCountry to "États-Unis". + * @param displayLocale Specifies the locale to be used to display the name. In other + * words, if the locale's country code is "US", passing + * Locale::getFrench() for displayLocale would result in "États-Unis", while + * passing Locale::getGerman() for displayLocale would result in + * "Vereinigte Staaten". + * @param dispCountry Receives the country's display name. + * @return A reference to "dispCountry". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayCountry( const Locale& displayLocale, + UnicodeString& dispCountry) const; + + /** + * Fills in "dispVar" with the name of this locale's variant code in a format suitable + * for user display in the default locale. + * @param dispVar Receives the variant's name. + * @return A reference to "dispVar". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayVariant( UnicodeString& dispVar) const; + + /** + * Fills in "dispVar" with the name of this locale's variant code in a format + * suitable for user display in the locale specified by "displayLocale". + * @param displayLocale Specifies the locale to be used to display the name. + * @param dispVar Receives the variant's display name. + * @return A reference to "dispVar". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayVariant( const Locale& displayLocale, + UnicodeString& dispVar) const; + + /** + * Fills in "name" with the name of this locale in a format suitable for user display + * in the default locale. This function uses getDisplayLanguage(), getDisplayCountry(), + * and getDisplayVariant() to do its work, and outputs the display name in the format + * "language (country[,variant])". For example, if the default locale is en_US, then + * fr_FR's display name would be "French (France)", and es_MX_Traditional's display name + * would be "Spanish (Mexico,Traditional)". + * @param name Receives the locale's display name. + * @return A reference to "name". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName( UnicodeString& name) const; + + /** + * Fills in "name" with the name of this locale in a format suitable for user display + * in the locale specified by "displayLocale". This function uses getDisplayLanguage(), + * getDisplayCountry(), and getDisplayVariant() to do its work, and outputs the display + * name in the format "language (country[,variant])". For example, if displayLocale is + * fr_FR, then en_US's display name would be "Anglais (États-Unis)", and no_NO_NY's + * display name would be "norvégien (Norvège,NY)". + * @param displayLocale Specifies the locale to be used to display the name. + * @param name Receives the locale's display name. + * @return A reference to "name". + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName( const Locale& displayLocale, + UnicodeString& name) const; + + /** + * Generates a hash code for the locale. + * @stable ICU 2.0 + */ + int32_t hashCode(void) const; + + /** + * Sets the locale to bogus + * A bogus locale represents a non-existing locale associated + * with services that can be instantiated from non-locale data + * in addition to locale (for example, collation can be + * instantiated from a locale and from a rule set). + * @stable ICU 2.1 + */ + void setToBogus(); + + /** + * Gets the bogus state. Locale object can be bogus if it doesn't exist + * @return false if it is a real locale, true if it is a bogus locale + * @stable ICU 2.1 + */ + inline UBool isBogus(void) const; + + /** + * Returns a list of all installed locales. + * @param count Receives the number of locales in the list. + * @return A pointer to an array of Locale objects. This array is the list + * of all locales with installed resource files. The called does NOT + * get ownership of this list, and must NOT delete it. + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + + /** + * Gets a list of all available 2-letter country codes defined in ISO 3166. This is a + * pointer to an array of pointers to arrays of char. All of these pointers are + * owned by ICU-- do not delete them, and do not write through them. The array is + * terminated with a null pointer. + * @return a list of all available country codes + * @stable ICU 2.0 + */ + static const char* const* U_EXPORT2 getISOCountries(); + + /** + * Gets a list of all available language codes defined in ISO 639. This is a pointer + * to an array of pointers to arrays of char. All of these pointers are owned + * by ICU-- do not delete them, and do not write through them. The array is + * terminated with a null pointer. + * @return a list of all available language codes + * @stable ICU 2.0 + */ + static const char* const* U_EXPORT2 getISOLanguages(); + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * A Locale iterator interface similar to a Java Iterator. + * @stable ICU 65 + */ + class U_COMMON_API Iterator /* not : public UObject because this is an interface/mixin class */ { + public: + /** @stable ICU 65 */ + virtual ~Iterator(); + + /** + * @return true if next() can be called again. + * @stable ICU 65 + */ + virtual UBool hasNext() const = 0; + + /** + * @return the next locale. + * @stable ICU 65 + */ + virtual const Locale &next() = 0; + }; + + /** + * A generic Locale iterator implementation over Locale input iterators. + * @stable ICU 65 + */ + template + class RangeIterator : public Iterator, public UMemory { + public: + /** + * Constructs an iterator from a begin/end range. + * Each of the iterator parameter values must be an + * input iterator whose value is convertible to const Locale &. + * + * @param begin Start of range. + * @param end Exclusive end of range. + * @stable ICU 65 + */ + RangeIterator(Iter begin, Iter end) : it_(begin), end_(end) {} + + /** + * @return true if next() can be called again. + * @stable ICU 65 + */ + UBool hasNext() const override { return it_ != end_; } + + /** + * @return the next locale. + * @stable ICU 65 + */ + const Locale &next() override { return *it_++; } + + private: + Iter it_; + const Iter end_; + }; + + /** + * A generic Locale iterator implementation over Locale input iterators. + * Calls the converter to convert each *begin to a const Locale &. + * @stable ICU 65 + */ + template + class ConvertingIterator : public Iterator, public UMemory { + public: + /** + * Constructs an iterator from a begin/end range. + * Each of the iterator parameter values must be an + * input iterator whose value the converter converts to const Locale &. + * + * @param begin Start of range. + * @param end Exclusive end of range. + * @param converter Converter from *begin to const Locale & or compatible. + * @stable ICU 65 + */ + ConvertingIterator(Iter begin, Iter end, Conv converter) : + it_(begin), end_(end), converter_(converter) {} + + /** + * @return true if next() can be called again. + * @stable ICU 65 + */ + UBool hasNext() const override { return it_ != end_; } + + /** + * @return the next locale. + * @stable ICU 65 + */ + const Locale &next() override { return converter_(*it_++); } + + private: + Iter it_; + const Iter end_; + Conv converter_; + }; + +protected: /* only protected for testing purposes. DO NOT USE. */ +#ifndef U_HIDE_INTERNAL_API + /** + * Set this from a single POSIX style locale string. + * @internal + */ + void setFromPOSIXID(const char *posixID); +#endif /* U_HIDE_INTERNAL_API */ + +private: + /** + * Initialize the locale object with a new name. + * Was deprecated - used in implementation - moved internal + * + * @param cLocaleID The new locale name. + * @param canonicalize whether to call uloc_canonicalize on cLocaleID + */ + Locale& init(const char* cLocaleID, UBool canonicalize); + + /* + * Internal constructor to allow construction of a locale object with + * NO side effects. (Default constructor tries to get + * the default locale.) + */ + enum ELocaleType { + eBOGUS + }; + Locale(ELocaleType); + + /** + * Initialize the locale cache for commonly used locales + */ + static Locale *getLocaleCache(void); + + char language[ULOC_LANG_CAPACITY]; + char script[ULOC_SCRIPT_CAPACITY]; + char country[ULOC_COUNTRY_CAPACITY]; + int32_t variantBegin; + char* fullName; + char fullNameBuffer[ULOC_FULLNAME_CAPACITY]; + // name without keywords + char* baseName; + void initBaseName(UErrorCode& status); + + UBool fIsBogus; + + static const Locale &getLocale(int locid); + + /** + * A friend to allow the default locale to be set by either the C or C++ API. + * @internal (private) + */ + friend Locale *locale_set_default_internal(const char *, UErrorCode& status); + + /** + * @internal (private) + */ + friend void U_CALLCONV locale_available_init(); +}; + +inline bool +Locale::operator!=(const Locale& other) const +{ + return !operator==(other); +} + +template inline StringClass +Locale::toLanguageTag(UErrorCode& status) const +{ + StringClass result; + StringByteSink sink(&result); + toLanguageTag(sink, status); + return result; +} + +inline const char * +Locale::getCountry() const +{ + return country; +} + +inline const char * +Locale::getLanguage() const +{ + return language; +} + +inline const char * +Locale::getScript() const +{ + return script; +} + +inline const char * +Locale::getVariant() const +{ + return &baseName[variantBegin]; +} + +inline const char * +Locale::getName() const +{ + return fullName; +} + +template inline void +Locale::getKeywords(OutputIterator iterator, UErrorCode& status) const +{ + LocalPointer keys(createKeywords(status)); + if (U_FAILURE(status) || keys.isNull()) { + return; + } + for (;;) { + int32_t resultLength; + const char* buffer = keys->next(&resultLength, status); + if (U_FAILURE(status) || buffer == nullptr) { + return; + } + *iterator++ = StringClass(buffer, resultLength); + } +} + +template inline void +Locale::getUnicodeKeywords(OutputIterator iterator, UErrorCode& status) const +{ + LocalPointer keys(createUnicodeKeywords(status)); + if (U_FAILURE(status) || keys.isNull()) { + return; + } + for (;;) { + int32_t resultLength; + const char* buffer = keys->next(&resultLength, status); + if (U_FAILURE(status) || buffer == nullptr) { + return; + } + *iterator++ = StringClass(buffer, resultLength); + } +} + +template inline StringClass +Locale::getKeywordValue(StringPiece keywordName, UErrorCode& status) const +{ + StringClass result; + StringByteSink sink(&result); + getKeywordValue(keywordName, sink, status); + return result; +} + +template inline StringClass +Locale::getUnicodeKeywordValue(StringPiece keywordName, UErrorCode& status) const +{ + StringClass result; + StringByteSink sink(&result); + getUnicodeKeywordValue(keywordName, sink, status); + return result; +} + +inline UBool +Locale::isBogus(void) const { + return fIsBogus; +} + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..59bf546a9052946e1a7ac5d95f7660d1fe4441bf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measfmt.h @@ -0,0 +1,398 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2004-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: April 20, 2004 +* Since: ICU 3.0 +********************************************************************** +*/ +#ifndef MEASUREFORMAT_H +#define MEASUREFORMAT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/format.h" +#include "unicode/udat.h" + +/** + * \file + * \brief C++ API: Compatibility APIs for measure formatting. + */ + +/** + * Constants for various widths. + * There are 4 widths: Wide, Short, Narrow, Numeric. + * For example, for English, when formatting "3 hours" + * Wide is "3 hours"; short is "3 hrs"; narrow is "3h"; + * formatting "3 hours 17 minutes" as numeric give "3:17" + * @stable ICU 53 + */ +enum UMeasureFormatWidth { + + // Wide, short, and narrow must be first and in this order. + /** + * Spell out measure units. + * @stable ICU 53 + */ + UMEASFMT_WIDTH_WIDE, + + /** + * Abbreviate measure units. + * @stable ICU 53 + */ + UMEASFMT_WIDTH_SHORT, + + /** + * Use symbols for measure units when possible. + * @stable ICU 53 + */ + UMEASFMT_WIDTH_NARROW, + + /** + * Completely omit measure units when possible. For example, format + * '5 hours, 37 minutes' as '5:37' + * @stable ICU 53 + */ + UMEASFMT_WIDTH_NUMERIC, + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UMeasureFormatWidth value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UMEASFMT_WIDTH_COUNT = 4 +#endif // U_HIDE_DEPRECATED_API +}; +/** @stable ICU 53 */ +typedef enum UMeasureFormatWidth UMeasureFormatWidth; + +U_NAMESPACE_BEGIN + +class Measure; +class MeasureUnit; +class NumberFormat; +class PluralRules; +class MeasureFormatCacheData; +class SharedNumberFormat; +class SharedPluralRules; +class QuantityFormatter; +class SimpleFormatter; +class ListFormatter; +class DateFormat; + +/** + *

IMPORTANT: New users are strongly encouraged to see if + * numberformatter.h fits their use case. Although not deprecated, this header + * is provided for backwards compatibility only, and has much more limited + * capabilities. + * + * @see Format + * @author Alan Liu + * @stable ICU 3.0 + */ +class U_I18N_API MeasureFormat : public Format { + public: + using Format::parseObject; + using Format::format; + + /** + * Constructor. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 53 + */ + MeasureFormat( + const Locale &locale, UMeasureFormatWidth width, UErrorCode &status); + + /** + * Constructor. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 53 + */ + MeasureFormat( + const Locale &locale, + UMeasureFormatWidth width, + NumberFormat *nfToAdopt, + UErrorCode &status); + + /** + * Copy constructor. + * @stable ICU 3.0 + */ + MeasureFormat(const MeasureFormat &other); + + /** + * Assignment operator. + * @stable ICU 3.0 + */ + MeasureFormat &operator=(const MeasureFormat &rhs); + + /** + * Destructor. + * @stable ICU 3.0 + */ + virtual ~MeasureFormat(); + + /** + * Return true if given Format objects are semantically equal. + * @stable ICU 53 + */ + virtual bool operator==(const Format &other) const override; + + /** + * Clones this object polymorphically. + * @stable ICU 53 + */ + virtual MeasureFormat *clone() const override; + + /** + * Formats object to produce a string. + * @stable ICU 53 + */ + virtual UnicodeString &format( + const Formattable &obj, + UnicodeString &appendTo, + FieldPosition &pos, + UErrorCode &status) const override; + +#ifndef U_FORCE_HIDE_DRAFT_API + /** + * Parse a string to produce an object. This implementation sets + * status to U_UNSUPPORTED_ERROR. + * + * @draft ICU 53 + */ + virtual void parseObject( + const UnicodeString &source, + Formattable &reslt, + ParsePosition &pos) const override; +#endif // U_FORCE_HIDE_DRAFT_API + + /** + * Formats measure objects to produce a string. An example of such a + * formatted string is 3 meters, 3.5 centimeters. Measure objects appear + * in the formatted string in the same order they appear in the "measures" + * array. The NumberFormat of this object is used only to format the amount + * of the very last measure. The other amounts are formatted with zero + * decimal places while rounding toward zero. + * @param measures array of measure objects. + * @param measureCount the number of measure objects. + * @param appendTo formatted string appended here. + * @param pos the field position. + * @param status the error. + * @return appendTo reference + * + * @stable ICU 53 + */ + UnicodeString &formatMeasures( + const Measure *measures, + int32_t measureCount, + UnicodeString &appendTo, + FieldPosition &pos, + UErrorCode &status) const; + + /** + * Formats a single measure per unit. An example of such a + * formatted string is 3.5 meters per second. + * @param measure The measure object. In above example, 3.5 meters. + * @param perUnit The per unit. In above example, it is + * `*%MeasureUnit::createSecond(status)`. + * @param appendTo formatted string appended here. + * @param pos the field position. + * @param status the error. + * @return appendTo reference + * + * @stable ICU 55 + */ + UnicodeString &formatMeasurePerUnit( + const Measure &measure, + const MeasureUnit &perUnit, + UnicodeString &appendTo, + FieldPosition &pos, + UErrorCode &status) const; + + /** + * Gets the display name of the specified {@link MeasureUnit} corresponding to the current + * locale and format width. + * @param unit The unit for which to get a display name. + * @param status the error. + * @return The display name in the locale and width specified in + * the MeasureFormat constructor, or null if there is no display name available + * for the specified unit. + * + * @stable ICU 58 + */ + UnicodeString getUnitDisplayName(const MeasureUnit& unit, UErrorCode &status) const; + + + /** + * Return a formatter for CurrencyAmount objects in the given + * locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param locale desired locale + * @param ec input-output error code + * @return a formatter object, or nullptr upon error + * @stable ICU 3.0 + */ + static MeasureFormat* U_EXPORT2 createCurrencyFormat(const Locale& locale, + UErrorCode& ec); + + /** + * Return a formatter for CurrencyAmount objects in the default + * locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param ec input-output error code + * @return a formatter object, or nullptr upon error + * @stable ICU 3.0 + */ + static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec); + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 53 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 53 + */ + virtual UClassID getDynamicClassID(void) const override; + + protected: + /** + * Default constructor. + * @stable ICU 3.0 + */ + MeasureFormat(); + +#ifndef U_HIDE_INTERNAL_API + + /** + * ICU use only. + * Initialize or change MeasureFormat class from subclass. + * @internal. + */ + void initMeasureFormat( + const Locale &locale, + UMeasureFormatWidth width, + NumberFormat *nfToAdopt, + UErrorCode &status); + /** + * ICU use only. + * Allows subclass to change locale. Note that this method also changes + * the NumberFormat object. Returns true if locale changed; false if no + * change was made. + * @internal. + */ + UBool setMeasureFormatLocale(const Locale &locale, UErrorCode &status); + + /** + * ICU use only. + * Let subclass change NumberFormat. + * @internal. + */ + void adoptNumberFormat(NumberFormat *nfToAdopt, UErrorCode &status); + + /** + * ICU use only. + * @internal. + */ + const NumberFormat &getNumberFormatInternal() const; + + /** + * ICU use only. + * Always returns the short form currency formatter. + * @internal. + */ + const NumberFormat& getCurrencyFormatInternal() const; + + /** + * ICU use only. + * @internal. + */ + const PluralRules &getPluralRules() const; + + /** + * ICU use only. + * @internal. + */ + Locale getLocale(UErrorCode &status) const; + + /** + * ICU use only. + * @internal. + */ + const char *getLocaleID(UErrorCode &status) const; + +#endif /* U_HIDE_INTERNAL_API */ + + private: + const MeasureFormatCacheData *cache; + const SharedNumberFormat *numberFormat; + const SharedPluralRules *pluralRules; + UMeasureFormatWidth fWidth; + + // Declared outside of MeasureFormatSharedData because ListFormatter + // objects are relatively cheap to copy; therefore, they don't need to be + // shared across instances. + ListFormatter *listFormatter; + + UnicodeString &formatMeasure( + const Measure &measure, + const NumberFormat &nf, + UnicodeString &appendTo, + FieldPosition &pos, + UErrorCode &status) const; + + UnicodeString &formatMeasuresSlowTrack( + const Measure *measures, + int32_t measureCount, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + UnicodeString &formatNumeric( + const Formattable *hms, // always length 3: [0] is hour; [1] is + // minute; [2] is second. + int32_t bitMap, // 1=hour set, 2=minute set, 4=second set + UnicodeString &appendTo, + UErrorCode &status) const; +}; + +U_NAMESPACE_END + +#endif // #if !UCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // #ifndef MEASUREFORMAT_H diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measunit.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measunit.h new file mode 100644 index 0000000000000000000000000000000000000000..f7acc6990b2489e0b954ca60f29a40390ae141d6 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measunit.h @@ -0,0 +1,3805 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2004-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: April 26, 2004 +* Since: ICU 3.0 +********************************************************************** +*/ +#ifndef __MEASUREUNIT_H__ +#define __MEASUREUNIT_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include +#include "unicode/unistr.h" +#include "unicode/localpointer.h" + +/** + * \file + * \brief C++ API: A unit for measuring a quantity. + */ + +U_NAMESPACE_BEGIN + +class StringEnumeration; +class MeasureUnitImpl; + +namespace number { +namespace impl { +class LongNameHandler; +} +} // namespace number + +/** + * Enumeration for unit complexity. There are three levels: + * + * - SINGLE: A single unit, optionally with a power and/or SI or binary prefix. + * Examples: hectare, square-kilometer, kilojoule, per-second, mebibyte. + * - COMPOUND: A unit composed of the product of multiple single units. Examples: + * meter-per-second, kilowatt-hour, kilogram-meter-per-square-second. + * - MIXED: A unit composed of the sum of multiple single units. Examples: foot+inch, + * hour+minute+second, degree+arcminute+arcsecond. + * + * The complexity determines which operations are available. For example, you cannot set the power + * or prefix of a compound unit. + * + * @stable ICU 67 + */ +enum UMeasureUnitComplexity { + /** + * A single unit, like kilojoule. + * + * @stable ICU 67 + */ + UMEASURE_UNIT_SINGLE, + + /** + * A compound unit, like meter-per-second. + * + * @stable ICU 67 + */ + UMEASURE_UNIT_COMPOUND, + + /** + * A mixed unit, like hour+minute. + * + * @stable ICU 67 + */ + UMEASURE_UNIT_MIXED +}; + + +/** + * Enumeration for SI and binary prefixes, e.g. "kilo-", "nano-", "mebi-". + * + * Enum values should be treated as opaque: use umeas_getPrefixPower() and + * umeas_getPrefixBase() to find their corresponding values. + * + * @stable ICU 69 + * @see umeas_getPrefixBase + * @see umeas_getPrefixPower + */ +typedef enum UMeasurePrefix { + /** + * The absence of an SI or binary prefix. + * + * The integer representation of this enum value is an arbitrary + * implementation detail and should not be relied upon: use + * umeas_getPrefixPower() to obtain meaningful values. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_ONE = 30 + 0, + + /** + * SI prefix: yotta, 10^24. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_YOTTA = UMEASURE_PREFIX_ONE + 24, + +#ifndef U_HIDE_INTERNAL_API + /** + * ICU use only. + * Used to determine the set of base-10 SI prefixes. + * @internal + */ + UMEASURE_PREFIX_INTERNAL_MAX_SI = UMEASURE_PREFIX_YOTTA, +#endif /* U_HIDE_INTERNAL_API */ + + /** + * SI prefix: zetta, 10^21. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_ZETTA = UMEASURE_PREFIX_ONE + 21, + + /** + * SI prefix: exa, 10^18. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_EXA = UMEASURE_PREFIX_ONE + 18, + + /** + * SI prefix: peta, 10^15. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_PETA = UMEASURE_PREFIX_ONE + 15, + + /** + * SI prefix: tera, 10^12. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_TERA = UMEASURE_PREFIX_ONE + 12, + + /** + * SI prefix: giga, 10^9. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_GIGA = UMEASURE_PREFIX_ONE + 9, + + /** + * SI prefix: mega, 10^6. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_MEGA = UMEASURE_PREFIX_ONE + 6, + + /** + * SI prefix: kilo, 10^3. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_KILO = UMEASURE_PREFIX_ONE + 3, + + /** + * SI prefix: hecto, 10^2. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_HECTO = UMEASURE_PREFIX_ONE + 2, + + /** + * SI prefix: deka, 10^1. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_DEKA = UMEASURE_PREFIX_ONE + 1, + + /** + * SI prefix: deci, 10^-1. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_DECI = UMEASURE_PREFIX_ONE + -1, + + /** + * SI prefix: centi, 10^-2. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_CENTI = UMEASURE_PREFIX_ONE + -2, + + /** + * SI prefix: milli, 10^-3. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_MILLI = UMEASURE_PREFIX_ONE + -3, + + /** + * SI prefix: micro, 10^-6. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_MICRO = UMEASURE_PREFIX_ONE + -6, + + /** + * SI prefix: nano, 10^-9. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_NANO = UMEASURE_PREFIX_ONE + -9, + + /** + * SI prefix: pico, 10^-12. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_PICO = UMEASURE_PREFIX_ONE + -12, + + /** + * SI prefix: femto, 10^-15. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_FEMTO = UMEASURE_PREFIX_ONE + -15, + + /** + * SI prefix: atto, 10^-18. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_ATTO = UMEASURE_PREFIX_ONE + -18, + + /** + * SI prefix: zepto, 10^-21. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_ZEPTO = UMEASURE_PREFIX_ONE + -21, + + /** + * SI prefix: yocto, 10^-24. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_YOCTO = UMEASURE_PREFIX_ONE + -24, + +#ifndef U_HIDE_INTERNAL_API + /** + * ICU use only. + * Used to determine the set of base-10 SI prefixes. + * @internal + */ + UMEASURE_PREFIX_INTERNAL_MIN_SI = UMEASURE_PREFIX_YOCTO, +#endif // U_HIDE_INTERNAL_API + + // Cannot conditionalize the following with #ifndef U_HIDE_INTERNAL_API, + // used in definitions of non-internal enum values + /** + * ICU use only. + * Sets the arbitrary offset of the base-1024 binary prefixes' enum values. + * @internal + */ + UMEASURE_PREFIX_INTERNAL_ONE_BIN = -60, + + /** + * Binary prefix: kibi, 1024^1. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_KIBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 1, + +#ifndef U_HIDE_INTERNAL_API + /** + * ICU use only. + * Used to determine the set of base-1024 binary prefixes. + * @internal + */ + UMEASURE_PREFIX_INTERNAL_MIN_BIN = UMEASURE_PREFIX_KIBI, +#endif // U_HIDE_INTERNAL_API + + /** + * Binary prefix: mebi, 1024^2. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_MEBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 2, + + /** + * Binary prefix: gibi, 1024^3. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_GIBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 3, + + /** + * Binary prefix: tebi, 1024^4. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_TEBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 4, + + /** + * Binary prefix: pebi, 1024^5. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_PEBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 5, + + /** + * Binary prefix: exbi, 1024^6. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_EXBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 6, + + /** + * Binary prefix: zebi, 1024^7. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_ZEBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 7, + + /** + * Binary prefix: yobi, 1024^8. + * + * @stable ICU 69 + */ + UMEASURE_PREFIX_YOBI = UMEASURE_PREFIX_INTERNAL_ONE_BIN + 8, + +#ifndef U_HIDE_INTERNAL_API + /** + * ICU use only. + * Used to determine the set of base-1024 binary prefixes. + * @internal + */ + UMEASURE_PREFIX_INTERNAL_MAX_BIN = UMEASURE_PREFIX_YOBI, +#endif // U_HIDE_INTERNAL_API +} UMeasurePrefix; + +/** + * Returns the base of the factor associated with the given unit prefix: the + * base is 10 for SI prefixes (kilo, micro) and 1024 for binary prefixes (kibi, + * mebi). + * + * @stable ICU 69 + */ +U_CAPI int32_t U_EXPORT2 umeas_getPrefixBase(UMeasurePrefix unitPrefix); + +/** + * Returns the exponent of the factor associated with the given unit prefix, for + * example 3 for kilo, -6 for micro, 1 for kibi, 2 for mebi, 3 for gibi. + * + * @stable ICU 69 + */ +U_CAPI int32_t U_EXPORT2 umeas_getPrefixPower(UMeasurePrefix unitPrefix); + +/** + * A unit such as length, mass, volume, currency, etc. A unit is + * coupled with a numeric amount to produce a Measure. + * + * @author Alan Liu + * @stable ICU 3.0 + */ +class U_I18N_API MeasureUnit: public UObject { + public: + + /** + * Default constructor. + * Populates the instance with the base dimensionless unit. + * @stable ICU 3.0 + */ + MeasureUnit(); + + /** + * Copy constructor. + * @stable ICU 3.0 + */ + MeasureUnit(const MeasureUnit &other); + + /** + * Move constructor. + * @stable ICU 67 + */ + MeasureUnit(MeasureUnit &&other) noexcept; + + /** + * Construct a MeasureUnit from a CLDR Core Unit Identifier, defined in UTS + * 35. (Core unit identifiers and mixed unit identifiers are supported, long + * unit identifiers are not.) Validates and canonicalizes the identifier. + * + *
+     * MeasureUnit example = MeasureUnit::forIdentifier("furlong-per-nanosecond")
+     * 
+ * + * @param identifier The CLDR Unit Identifier. + * @param status Set if the identifier is invalid. + * @stable ICU 67 + */ + static MeasureUnit forIdentifier(StringPiece identifier, UErrorCode& status); + + /** + * Copy assignment operator. + * @stable ICU 3.0 + */ + MeasureUnit &operator=(const MeasureUnit &other); + + /** + * Move assignment operator. + * @stable ICU 67 + */ + MeasureUnit &operator=(MeasureUnit &&other) noexcept; + + /** + * Returns a polymorphic clone of this object. The result will + * have the same class as returned by getDynamicClassID(). + * @stable ICU 3.0 + */ + virtual MeasureUnit* clone() const; + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~MeasureUnit(); + + /** + * Equality operator. Return true if this object is equal + * to the given object. + * @stable ICU 3.0 + */ + virtual bool operator==(const UObject& other) const; + + /** + * Inequality operator. Return true if this object is not equal + * to the given object. + * @stable ICU 53 + */ + bool operator!=(const UObject& other) const { + return !(*this == other); + } + + /** + * Get the type. + * + * If the unit does not have a type, the empty string is returned. + * + * @stable ICU 53 + */ + const char *getType() const; + + /** + * Get the sub type. + * + * If the unit does not have a subtype, the empty string is returned. + * + * @stable ICU 53 + */ + const char *getSubtype() const; + + /** + * Get CLDR Unit Identifier for this MeasureUnit, as defined in UTS 35. + * + * @return The string form of this unit, owned by this MeasureUnit. + * @stable ICU 67 + */ + const char* getIdentifier() const; + + /** + * Compute the complexity of the unit. See UMeasureUnitComplexity for more information. + * + * @param status Set if an error occurs. + * @return The unit complexity. + * @stable ICU 67 + */ + UMeasureUnitComplexity getComplexity(UErrorCode& status) const; + + /** + * Creates a MeasureUnit which is this SINGLE unit augmented with the specified prefix. + * For example, UMEASURE_PREFIX_KILO for "kilo", or UMEASURE_PREFIX_KIBI for "kibi". + * + * There is sufficient locale data to format all standard prefixes. + * + * NOTE: Only works on SINGLE units. If this is a COMPOUND or MIXED unit, an error will + * occur. For more information, see UMeasureUnitComplexity. + * + * @param prefix The prefix, from UMeasurePrefix. + * @param status Set if this is not a SINGLE unit or if another error occurs. + * @return A new SINGLE unit. + * @stable ICU 69 + */ + MeasureUnit withPrefix(UMeasurePrefix prefix, UErrorCode& status) const; + + /** + * Returns the current SI or binary prefix of this SINGLE unit. For example, + * if the unit has the prefix "kilo", then UMEASURE_PREFIX_KILO is + * returned. + * + * NOTE: Only works on SINGLE units. If this is a COMPOUND or MIXED unit, an error will + * occur. For more information, see UMeasureUnitComplexity. + * + * @param status Set if this is not a SINGLE unit or if another error occurs. + * @return The prefix of this SINGLE unit, from UMeasurePrefix. + * @see umeas_getPrefixBase + * @see umeas_getPrefixPower + * @stable ICU 69 + */ + UMeasurePrefix getPrefix(UErrorCode& status) const; + + /** + * Creates a MeasureUnit which is this SINGLE unit augmented with the specified dimensionality + * (power). For example, if dimensionality is 2, the unit will be squared. + * + * NOTE: Only works on SINGLE units. If this is a COMPOUND or MIXED unit, an error will + * occur. For more information, see UMeasureUnitComplexity. + * + * For the base dimensionless unit, withDimensionality does nothing. + * + * @param dimensionality The dimensionality (power). + * @param status Set if this is not a SINGLE unit or if another error occurs. + * @return A new SINGLE unit. + * @stable ICU 67 + */ + MeasureUnit withDimensionality(int32_t dimensionality, UErrorCode& status) const; + + /** + * Gets the dimensionality (power) of this MeasureUnit. For example, if the unit is square, + * then 2 is returned. + * + * NOTE: Only works on SINGLE units. If this is a COMPOUND or MIXED unit, an error will + * occur. For more information, see UMeasureUnitComplexity. + * + * For the base dimensionless unit, getDimensionality returns 0. + * + * @param status Set if this is not a SINGLE unit or if another error occurs. + * @return The dimensionality (power) of this simple unit. + * @stable ICU 67 + */ + int32_t getDimensionality(UErrorCode& status) const; + + /** + * Gets the reciprocal of this MeasureUnit, with the numerator and denominator flipped. + * + * For example, if the receiver is "meter-per-second", the unit "second-per-meter" is returned. + * + * NOTE: Only works on SINGLE and COMPOUND units. If this is a MIXED unit, an error will + * occur. For more information, see UMeasureUnitComplexity. + * + * @param status Set if this is a MIXED unit or if another error occurs. + * @return The reciprocal of the target unit. + * @stable ICU 67 + */ + MeasureUnit reciprocal(UErrorCode& status) const; + + /** + * Gets the product of this unit with another unit. This is a way to build units from + * constituent parts. + * + * The numerator and denominator are preserved through this operation. + * + * For example, if the receiver is "kilowatt" and the argument is "hour-per-day", then the + * unit "kilowatt-hour-per-day" is returned. + * + * NOTE: Only works on SINGLE and COMPOUND units. If either unit (receiver and argument) is a + * MIXED unit, an error will occur. For more information, see UMeasureUnitComplexity. + * + * @param other The MeasureUnit to multiply with the target. + * @param status Set if this or other is a MIXED unit or if another error occurs. + * @return The product of the target unit with the provided unit. + * @stable ICU 67 + */ + MeasureUnit product(const MeasureUnit& other, UErrorCode& status) const; + + /** + * Gets the list of SINGLE units contained within a MIXED or COMPOUND unit. + * + * Examples: + * - Given "meter-kilogram-per-second", three units will be returned: "meter", + * "kilogram", and "per-second". + * - Given "hour+minute+second", three units will be returned: "hour", "minute", + * and "second". + * + * If this is a SINGLE unit, an array of length 1 will be returned. + * + * @param status Set if an error occurs. + * @return A pair with the list of units as a LocalArray and the number of units in the list. + * @stable ICU 68 + */ + inline std::pair, int32_t> splitToSingleUnits(UErrorCode& status) const; + + /** + * getAvailable gets all of the available units. + * If there are too many units to fit into destCapacity then the + * error code is set to U_BUFFER_OVERFLOW_ERROR. + * + * @param destArray destination buffer. + * @param destCapacity number of MeasureUnit instances available at dest. + * @param errorCode ICU error code. + * @return number of available units. + * @stable ICU 53 + */ + static int32_t getAvailable( + MeasureUnit *destArray, + int32_t destCapacity, + UErrorCode &errorCode); + + /** + * getAvailable gets all of the available units for a specific type. + * If there are too many units to fit into destCapacity then the + * error code is set to U_BUFFER_OVERFLOW_ERROR. + * + * @param type the type + * @param destArray destination buffer. + * @param destCapacity number of MeasureUnit instances available at dest. + * @param errorCode ICU error code. + * @return number of available units for type. + * @stable ICU 53 + */ + static int32_t getAvailable( + const char *type, + MeasureUnit *destArray, + int32_t destCapacity, + UErrorCode &errorCode); + + /** + * getAvailableTypes gets all of the available types. Caller owns the + * returned StringEnumeration and must delete it when finished using it. + * + * @param errorCode ICU error code. + * @return the types. + * @stable ICU 53 + */ + static StringEnumeration* getAvailableTypes(UErrorCode &errorCode); + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 53 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 53 + */ + virtual UClassID getDynamicClassID(void) const override; + +#ifndef U_HIDE_INTERNAL_API + /** + * ICU use only. + * Returns associated array index for this measure unit. + * @internal + */ + int32_t getOffset() const; +#endif /* U_HIDE_INTERNAL_API */ + +// All code between the "Start generated createXXX methods" comment and +// the "End generated createXXX methods" comment is auto generated code +// and must not be edited manually. For instructions on how to correctly +// update this code, refer to: +// docs/processes/release/tasks/updating-measure-unit.md +// +// Start generated createXXX methods + + /** + * Returns by pointer, unit of acceleration: g-force. + * Caller owns returned value and must free it. + * Also see {@link #getGForce()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createGForce(UErrorCode &status); + + /** + * Returns by value, unit of acceleration: g-force. + * Also see {@link #createGForce()}. + * @stable ICU 64 + */ + static MeasureUnit getGForce(); + + /** + * Returns by pointer, unit of acceleration: meter-per-square-second. + * Caller owns returned value and must free it. + * Also see {@link #getMeterPerSecondSquared()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMeterPerSecondSquared(UErrorCode &status); + + /** + * Returns by value, unit of acceleration: meter-per-square-second. + * Also see {@link #createMeterPerSecondSquared()}. + * @stable ICU 64 + */ + static MeasureUnit getMeterPerSecondSquared(); + + /** + * Returns by pointer, unit of angle: arc-minute. + * Caller owns returned value and must free it. + * Also see {@link #getArcMinute()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createArcMinute(UErrorCode &status); + + /** + * Returns by value, unit of angle: arc-minute. + * Also see {@link #createArcMinute()}. + * @stable ICU 64 + */ + static MeasureUnit getArcMinute(); + + /** + * Returns by pointer, unit of angle: arc-second. + * Caller owns returned value and must free it. + * Also see {@link #getArcSecond()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createArcSecond(UErrorCode &status); + + /** + * Returns by value, unit of angle: arc-second. + * Also see {@link #createArcSecond()}. + * @stable ICU 64 + */ + static MeasureUnit getArcSecond(); + + /** + * Returns by pointer, unit of angle: degree. + * Caller owns returned value and must free it. + * Also see {@link #getDegree()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createDegree(UErrorCode &status); + + /** + * Returns by value, unit of angle: degree. + * Also see {@link #createDegree()}. + * @stable ICU 64 + */ + static MeasureUnit getDegree(); + + /** + * Returns by pointer, unit of angle: radian. + * Caller owns returned value and must free it. + * Also see {@link #getRadian()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createRadian(UErrorCode &status); + + /** + * Returns by value, unit of angle: radian. + * Also see {@link #createRadian()}. + * @stable ICU 64 + */ + static MeasureUnit getRadian(); + + /** + * Returns by pointer, unit of angle: revolution. + * Caller owns returned value and must free it. + * Also see {@link #getRevolutionAngle()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createRevolutionAngle(UErrorCode &status); + + /** + * Returns by value, unit of angle: revolution. + * Also see {@link #createRevolutionAngle()}. + * @stable ICU 64 + */ + static MeasureUnit getRevolutionAngle(); + + /** + * Returns by pointer, unit of area: acre. + * Caller owns returned value and must free it. + * Also see {@link #getAcre()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createAcre(UErrorCode &status); + + /** + * Returns by value, unit of area: acre. + * Also see {@link #createAcre()}. + * @stable ICU 64 + */ + static MeasureUnit getAcre(); + + /** + * Returns by pointer, unit of area: dunam. + * Caller owns returned value and must free it. + * Also see {@link #getDunam()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createDunam(UErrorCode &status); + + /** + * Returns by value, unit of area: dunam. + * Also see {@link #createDunam()}. + * @stable ICU 64 + */ + static MeasureUnit getDunam(); + + /** + * Returns by pointer, unit of area: hectare. + * Caller owns returned value and must free it. + * Also see {@link #getHectare()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createHectare(UErrorCode &status); + + /** + * Returns by value, unit of area: hectare. + * Also see {@link #createHectare()}. + * @stable ICU 64 + */ + static MeasureUnit getHectare(); + + /** + * Returns by pointer, unit of area: square-centimeter. + * Caller owns returned value and must free it. + * Also see {@link #getSquareCentimeter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createSquareCentimeter(UErrorCode &status); + + /** + * Returns by value, unit of area: square-centimeter. + * Also see {@link #createSquareCentimeter()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareCentimeter(); + + /** + * Returns by pointer, unit of area: square-foot. + * Caller owns returned value and must free it. + * Also see {@link #getSquareFoot()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createSquareFoot(UErrorCode &status); + + /** + * Returns by value, unit of area: square-foot. + * Also see {@link #createSquareFoot()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareFoot(); + + /** + * Returns by pointer, unit of area: square-inch. + * Caller owns returned value and must free it. + * Also see {@link #getSquareInch()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createSquareInch(UErrorCode &status); + + /** + * Returns by value, unit of area: square-inch. + * Also see {@link #createSquareInch()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareInch(); + + /** + * Returns by pointer, unit of area: square-kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getSquareKilometer()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createSquareKilometer(UErrorCode &status); + + /** + * Returns by value, unit of area: square-kilometer. + * Also see {@link #createSquareKilometer()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareKilometer(); + + /** + * Returns by pointer, unit of area: square-meter. + * Caller owns returned value and must free it. + * Also see {@link #getSquareMeter()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createSquareMeter(UErrorCode &status); + + /** + * Returns by value, unit of area: square-meter. + * Also see {@link #createSquareMeter()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareMeter(); + + /** + * Returns by pointer, unit of area: square-mile. + * Caller owns returned value and must free it. + * Also see {@link #getSquareMile()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createSquareMile(UErrorCode &status); + + /** + * Returns by value, unit of area: square-mile. + * Also see {@link #createSquareMile()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareMile(); + + /** + * Returns by pointer, unit of area: square-yard. + * Caller owns returned value and must free it. + * Also see {@link #getSquareYard()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createSquareYard(UErrorCode &status); + + /** + * Returns by value, unit of area: square-yard. + * Also see {@link #createSquareYard()}. + * @stable ICU 64 + */ + static MeasureUnit getSquareYard(); + + /** + * Returns by pointer, unit of concentr: item. + * Caller owns returned value and must free it. + * Also see {@link #getItem()}. + * @param status ICU error code. + * @stable ICU 70 + */ + static MeasureUnit *createItem(UErrorCode &status); + + /** + * Returns by value, unit of concentr: item. + * Also see {@link #createItem()}. + * @stable ICU 70 + */ + static MeasureUnit getItem(); + + /** + * Returns by pointer, unit of concentr: karat. + * Caller owns returned value and must free it. + * Also see {@link #getKarat()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKarat(UErrorCode &status); + + /** + * Returns by value, unit of concentr: karat. + * Also see {@link #createKarat()}. + * @stable ICU 64 + */ + static MeasureUnit getKarat(); + + /** + * Returns by pointer, unit of concentr: milligram-ofglucose-per-deciliter. + * Caller owns returned value and must free it. + * Also see {@link #getMilligramOfglucosePerDeciliter()}. + * @param status ICU error code. + * @stable ICU 69 + */ + static MeasureUnit *createMilligramOfglucosePerDeciliter(UErrorCode &status); + + /** + * Returns by value, unit of concentr: milligram-ofglucose-per-deciliter. + * Also see {@link #createMilligramOfglucosePerDeciliter()}. + * @stable ICU 69 + */ + static MeasureUnit getMilligramOfglucosePerDeciliter(); + + /** + * Returns by pointer, unit of concentr: milligram-per-deciliter. + * Caller owns returned value and must free it. + * Also see {@link #getMilligramPerDeciliter()}. + * @param status ICU error code. + * @stable ICU 57 + */ + static MeasureUnit *createMilligramPerDeciliter(UErrorCode &status); + + /** + * Returns by value, unit of concentr: milligram-per-deciliter. + * Also see {@link #createMilligramPerDeciliter()}. + * @stable ICU 64 + */ + static MeasureUnit getMilligramPerDeciliter(); + + /** + * Returns by pointer, unit of concentr: millimole-per-liter. + * Caller owns returned value and must free it. + * Also see {@link #getMillimolePerLiter()}. + * @param status ICU error code. + * @stable ICU 57 + */ + static MeasureUnit *createMillimolePerLiter(UErrorCode &status); + + /** + * Returns by value, unit of concentr: millimole-per-liter. + * Also see {@link #createMillimolePerLiter()}. + * @stable ICU 64 + */ + static MeasureUnit getMillimolePerLiter(); + + /** + * Returns by pointer, unit of concentr: mole. + * Caller owns returned value and must free it. + * Also see {@link #getMole()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createMole(UErrorCode &status); + + /** + * Returns by value, unit of concentr: mole. + * Also see {@link #createMole()}. + * @stable ICU 64 + */ + static MeasureUnit getMole(); + + /** + * Returns by pointer, unit of concentr: percent. + * Caller owns returned value and must free it. + * Also see {@link #getPercent()}. + * @param status ICU error code. + * @stable ICU 63 + */ + static MeasureUnit *createPercent(UErrorCode &status); + + /** + * Returns by value, unit of concentr: percent. + * Also see {@link #createPercent()}. + * @stable ICU 64 + */ + static MeasureUnit getPercent(); + + /** + * Returns by pointer, unit of concentr: permille. + * Caller owns returned value and must free it. + * Also see {@link #getPermille()}. + * @param status ICU error code. + * @stable ICU 63 + */ + static MeasureUnit *createPermille(UErrorCode &status); + + /** + * Returns by value, unit of concentr: permille. + * Also see {@link #createPermille()}. + * @stable ICU 64 + */ + static MeasureUnit getPermille(); + + /** + * Returns by pointer, unit of concentr: permillion. + * Caller owns returned value and must free it. + * Also see {@link #getPartPerMillion()}. + * @param status ICU error code. + * @stable ICU 57 + */ + static MeasureUnit *createPartPerMillion(UErrorCode &status); + + /** + * Returns by value, unit of concentr: permillion. + * Also see {@link #createPartPerMillion()}. + * @stable ICU 64 + */ + static MeasureUnit getPartPerMillion(); + + /** + * Returns by pointer, unit of concentr: permyriad. + * Caller owns returned value and must free it. + * Also see {@link #getPermyriad()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createPermyriad(UErrorCode &status); + + /** + * Returns by value, unit of concentr: permyriad. + * Also see {@link #createPermyriad()}. + * @stable ICU 64 + */ + static MeasureUnit getPermyriad(); + + /** + * Returns by pointer, unit of consumption: liter-per-100-kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getLiterPer100Kilometers()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createLiterPer100Kilometers(UErrorCode &status); + + /** + * Returns by value, unit of consumption: liter-per-100-kilometer. + * Also see {@link #createLiterPer100Kilometers()}. + * @stable ICU 64 + */ + static MeasureUnit getLiterPer100Kilometers(); + + /** + * Returns by pointer, unit of consumption: liter-per-kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getLiterPerKilometer()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createLiterPerKilometer(UErrorCode &status); + + /** + * Returns by value, unit of consumption: liter-per-kilometer. + * Also see {@link #createLiterPerKilometer()}. + * @stable ICU 64 + */ + static MeasureUnit getLiterPerKilometer(); + + /** + * Returns by pointer, unit of consumption: mile-per-gallon. + * Caller owns returned value and must free it. + * Also see {@link #getMilePerGallon()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMilePerGallon(UErrorCode &status); + + /** + * Returns by value, unit of consumption: mile-per-gallon. + * Also see {@link #createMilePerGallon()}. + * @stable ICU 64 + */ + static MeasureUnit getMilePerGallon(); + + /** + * Returns by pointer, unit of consumption: mile-per-gallon-imperial. + * Caller owns returned value and must free it. + * Also see {@link #getMilePerGallonImperial()}. + * @param status ICU error code. + * @stable ICU 57 + */ + static MeasureUnit *createMilePerGallonImperial(UErrorCode &status); + + /** + * Returns by value, unit of consumption: mile-per-gallon-imperial. + * Also see {@link #createMilePerGallonImperial()}. + * @stable ICU 64 + */ + static MeasureUnit getMilePerGallonImperial(); + + /** + * Returns by pointer, unit of digital: bit. + * Caller owns returned value and must free it. + * Also see {@link #getBit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createBit(UErrorCode &status); + + /** + * Returns by value, unit of digital: bit. + * Also see {@link #createBit()}. + * @stable ICU 64 + */ + static MeasureUnit getBit(); + + /** + * Returns by pointer, unit of digital: byte. + * Caller owns returned value and must free it. + * Also see {@link #getByte()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createByte(UErrorCode &status); + + /** + * Returns by value, unit of digital: byte. + * Also see {@link #createByte()}. + * @stable ICU 64 + */ + static MeasureUnit getByte(); + + /** + * Returns by pointer, unit of digital: gigabit. + * Caller owns returned value and must free it. + * Also see {@link #getGigabit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createGigabit(UErrorCode &status); + + /** + * Returns by value, unit of digital: gigabit. + * Also see {@link #createGigabit()}. + * @stable ICU 64 + */ + static MeasureUnit getGigabit(); + + /** + * Returns by pointer, unit of digital: gigabyte. + * Caller owns returned value and must free it. + * Also see {@link #getGigabyte()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createGigabyte(UErrorCode &status); + + /** + * Returns by value, unit of digital: gigabyte. + * Also see {@link #createGigabyte()}. + * @stable ICU 64 + */ + static MeasureUnit getGigabyte(); + + /** + * Returns by pointer, unit of digital: kilobit. + * Caller owns returned value and must free it. + * Also see {@link #getKilobit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilobit(UErrorCode &status); + + /** + * Returns by value, unit of digital: kilobit. + * Also see {@link #createKilobit()}. + * @stable ICU 64 + */ + static MeasureUnit getKilobit(); + + /** + * Returns by pointer, unit of digital: kilobyte. + * Caller owns returned value and must free it. + * Also see {@link #getKilobyte()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilobyte(UErrorCode &status); + + /** + * Returns by value, unit of digital: kilobyte. + * Also see {@link #createKilobyte()}. + * @stable ICU 64 + */ + static MeasureUnit getKilobyte(); + + /** + * Returns by pointer, unit of digital: megabit. + * Caller owns returned value and must free it. + * Also see {@link #getMegabit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMegabit(UErrorCode &status); + + /** + * Returns by value, unit of digital: megabit. + * Also see {@link #createMegabit()}. + * @stable ICU 64 + */ + static MeasureUnit getMegabit(); + + /** + * Returns by pointer, unit of digital: megabyte. + * Caller owns returned value and must free it. + * Also see {@link #getMegabyte()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMegabyte(UErrorCode &status); + + /** + * Returns by value, unit of digital: megabyte. + * Also see {@link #createMegabyte()}. + * @stable ICU 64 + */ + static MeasureUnit getMegabyte(); + + /** + * Returns by pointer, unit of digital: petabyte. + * Caller owns returned value and must free it. + * Also see {@link #getPetabyte()}. + * @param status ICU error code. + * @stable ICU 63 + */ + static MeasureUnit *createPetabyte(UErrorCode &status); + + /** + * Returns by value, unit of digital: petabyte. + * Also see {@link #createPetabyte()}. + * @stable ICU 64 + */ + static MeasureUnit getPetabyte(); + + /** + * Returns by pointer, unit of digital: terabit. + * Caller owns returned value and must free it. + * Also see {@link #getTerabit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createTerabit(UErrorCode &status); + + /** + * Returns by value, unit of digital: terabit. + * Also see {@link #createTerabit()}. + * @stable ICU 64 + */ + static MeasureUnit getTerabit(); + + /** + * Returns by pointer, unit of digital: terabyte. + * Caller owns returned value and must free it. + * Also see {@link #getTerabyte()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createTerabyte(UErrorCode &status); + + /** + * Returns by value, unit of digital: terabyte. + * Also see {@link #createTerabyte()}. + * @stable ICU 64 + */ + static MeasureUnit getTerabyte(); + + /** + * Returns by pointer, unit of duration: century. + * Caller owns returned value and must free it. + * Also see {@link #getCentury()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createCentury(UErrorCode &status); + + /** + * Returns by value, unit of duration: century. + * Also see {@link #createCentury()}. + * @stable ICU 64 + */ + static MeasureUnit getCentury(); + + /** + * Returns by pointer, unit of duration: day. + * Caller owns returned value and must free it. + * Also see {@link #getDay()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createDay(UErrorCode &status); + + /** + * Returns by value, unit of duration: day. + * Also see {@link #createDay()}. + * @stable ICU 64 + */ + static MeasureUnit getDay(); + + /** + * Returns by pointer, unit of duration: day-person. + * Caller owns returned value and must free it. + * Also see {@link #getDayPerson()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createDayPerson(UErrorCode &status); + + /** + * Returns by value, unit of duration: day-person. + * Also see {@link #createDayPerson()}. + * @stable ICU 64 + */ + static MeasureUnit getDayPerson(); + + /** + * Returns by pointer, unit of duration: decade. + * Caller owns returned value and must free it. + * Also see {@link #getDecade()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createDecade(UErrorCode &status); + + /** + * Returns by value, unit of duration: decade. + * Also see {@link #createDecade()}. + * @stable ICU 65 + */ + static MeasureUnit getDecade(); + + /** + * Returns by pointer, unit of duration: hour. + * Caller owns returned value and must free it. + * Also see {@link #getHour()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createHour(UErrorCode &status); + + /** + * Returns by value, unit of duration: hour. + * Also see {@link #createHour()}. + * @stable ICU 64 + */ + static MeasureUnit getHour(); + + /** + * Returns by pointer, unit of duration: microsecond. + * Caller owns returned value and must free it. + * Also see {@link #getMicrosecond()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMicrosecond(UErrorCode &status); + + /** + * Returns by value, unit of duration: microsecond. + * Also see {@link #createMicrosecond()}. + * @stable ICU 64 + */ + static MeasureUnit getMicrosecond(); + + /** + * Returns by pointer, unit of duration: millisecond. + * Caller owns returned value and must free it. + * Also see {@link #getMillisecond()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMillisecond(UErrorCode &status); + + /** + * Returns by value, unit of duration: millisecond. + * Also see {@link #createMillisecond()}. + * @stable ICU 64 + */ + static MeasureUnit getMillisecond(); + + /** + * Returns by pointer, unit of duration: minute. + * Caller owns returned value and must free it. + * Also see {@link #getMinute()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMinute(UErrorCode &status); + + /** + * Returns by value, unit of duration: minute. + * Also see {@link #createMinute()}. + * @stable ICU 64 + */ + static MeasureUnit getMinute(); + + /** + * Returns by pointer, unit of duration: month. + * Caller owns returned value and must free it. + * Also see {@link #getMonth()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMonth(UErrorCode &status); + + /** + * Returns by value, unit of duration: month. + * Also see {@link #createMonth()}. + * @stable ICU 64 + */ + static MeasureUnit getMonth(); + + /** + * Returns by pointer, unit of duration: month-person. + * Caller owns returned value and must free it. + * Also see {@link #getMonthPerson()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createMonthPerson(UErrorCode &status); + + /** + * Returns by value, unit of duration: month-person. + * Also see {@link #createMonthPerson()}. + * @stable ICU 64 + */ + static MeasureUnit getMonthPerson(); + + /** + * Returns by pointer, unit of duration: nanosecond. + * Caller owns returned value and must free it. + * Also see {@link #getNanosecond()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createNanosecond(UErrorCode &status); + + /** + * Returns by value, unit of duration: nanosecond. + * Also see {@link #createNanosecond()}. + * @stable ICU 64 + */ + static MeasureUnit getNanosecond(); + +#ifndef U_HIDE_DRAFT_API + /** + * Returns by pointer, unit of duration: quarter. + * Caller owns returned value and must free it. + * Also see {@link #getQuarter()}. + * @param status ICU error code. + * @draft ICU 72 + */ + static MeasureUnit *createQuarter(UErrorCode &status); + + /** + * Returns by value, unit of duration: quarter. + * Also see {@link #createQuarter()}. + * @draft ICU 72 + */ + static MeasureUnit getQuarter(); +#endif /* U_HIDE_DRAFT_API */ + + /** + * Returns by pointer, unit of duration: second. + * Caller owns returned value and must free it. + * Also see {@link #getSecond()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createSecond(UErrorCode &status); + + /** + * Returns by value, unit of duration: second. + * Also see {@link #createSecond()}. + * @stable ICU 64 + */ + static MeasureUnit getSecond(); + + /** + * Returns by pointer, unit of duration: week. + * Caller owns returned value and must free it. + * Also see {@link #getWeek()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createWeek(UErrorCode &status); + + /** + * Returns by value, unit of duration: week. + * Also see {@link #createWeek()}. + * @stable ICU 64 + */ + static MeasureUnit getWeek(); + + /** + * Returns by pointer, unit of duration: week-person. + * Caller owns returned value and must free it. + * Also see {@link #getWeekPerson()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createWeekPerson(UErrorCode &status); + + /** + * Returns by value, unit of duration: week-person. + * Also see {@link #createWeekPerson()}. + * @stable ICU 64 + */ + static MeasureUnit getWeekPerson(); + + /** + * Returns by pointer, unit of duration: year. + * Caller owns returned value and must free it. + * Also see {@link #getYear()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createYear(UErrorCode &status); + + /** + * Returns by value, unit of duration: year. + * Also see {@link #createYear()}. + * @stable ICU 64 + */ + static MeasureUnit getYear(); + + /** + * Returns by pointer, unit of duration: year-person. + * Caller owns returned value and must free it. + * Also see {@link #getYearPerson()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createYearPerson(UErrorCode &status); + + /** + * Returns by value, unit of duration: year-person. + * Also see {@link #createYearPerson()}. + * @stable ICU 64 + */ + static MeasureUnit getYearPerson(); + + /** + * Returns by pointer, unit of electric: ampere. + * Caller owns returned value and must free it. + * Also see {@link #getAmpere()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createAmpere(UErrorCode &status); + + /** + * Returns by value, unit of electric: ampere. + * Also see {@link #createAmpere()}. + * @stable ICU 64 + */ + static MeasureUnit getAmpere(); + + /** + * Returns by pointer, unit of electric: milliampere. + * Caller owns returned value and must free it. + * Also see {@link #getMilliampere()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMilliampere(UErrorCode &status); + + /** + * Returns by value, unit of electric: milliampere. + * Also see {@link #createMilliampere()}. + * @stable ICU 64 + */ + static MeasureUnit getMilliampere(); + + /** + * Returns by pointer, unit of electric: ohm. + * Caller owns returned value and must free it. + * Also see {@link #getOhm()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createOhm(UErrorCode &status); + + /** + * Returns by value, unit of electric: ohm. + * Also see {@link #createOhm()}. + * @stable ICU 64 + */ + static MeasureUnit getOhm(); + + /** + * Returns by pointer, unit of electric: volt. + * Caller owns returned value and must free it. + * Also see {@link #getVolt()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createVolt(UErrorCode &status); + + /** + * Returns by value, unit of electric: volt. + * Also see {@link #createVolt()}. + * @stable ICU 64 + */ + static MeasureUnit getVolt(); + + /** + * Returns by pointer, unit of energy: british-thermal-unit. + * Caller owns returned value and must free it. + * Also see {@link #getBritishThermalUnit()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createBritishThermalUnit(UErrorCode &status); + + /** + * Returns by value, unit of energy: british-thermal-unit. + * Also see {@link #createBritishThermalUnit()}. + * @stable ICU 64 + */ + static MeasureUnit getBritishThermalUnit(); + + /** + * Returns by pointer, unit of energy: calorie. + * Caller owns returned value and must free it. + * Also see {@link #getCalorie()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCalorie(UErrorCode &status); + + /** + * Returns by value, unit of energy: calorie. + * Also see {@link #createCalorie()}. + * @stable ICU 64 + */ + static MeasureUnit getCalorie(); + + /** + * Returns by pointer, unit of energy: electronvolt. + * Caller owns returned value and must free it. + * Also see {@link #getElectronvolt()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createElectronvolt(UErrorCode &status); + + /** + * Returns by value, unit of energy: electronvolt. + * Also see {@link #createElectronvolt()}. + * @stable ICU 64 + */ + static MeasureUnit getElectronvolt(); + + /** + * Returns by pointer, unit of energy: foodcalorie. + * Caller owns returned value and must free it. + * Also see {@link #getFoodcalorie()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createFoodcalorie(UErrorCode &status); + + /** + * Returns by value, unit of energy: foodcalorie. + * Also see {@link #createFoodcalorie()}. + * @stable ICU 64 + */ + static MeasureUnit getFoodcalorie(); + + /** + * Returns by pointer, unit of energy: joule. + * Caller owns returned value and must free it. + * Also see {@link #getJoule()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createJoule(UErrorCode &status); + + /** + * Returns by value, unit of energy: joule. + * Also see {@link #createJoule()}. + * @stable ICU 64 + */ + static MeasureUnit getJoule(); + + /** + * Returns by pointer, unit of energy: kilocalorie. + * Caller owns returned value and must free it. + * Also see {@link #getKilocalorie()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilocalorie(UErrorCode &status); + + /** + * Returns by value, unit of energy: kilocalorie. + * Also see {@link #createKilocalorie()}. + * @stable ICU 64 + */ + static MeasureUnit getKilocalorie(); + + /** + * Returns by pointer, unit of energy: kilojoule. + * Caller owns returned value and must free it. + * Also see {@link #getKilojoule()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilojoule(UErrorCode &status); + + /** + * Returns by value, unit of energy: kilojoule. + * Also see {@link #createKilojoule()}. + * @stable ICU 64 + */ + static MeasureUnit getKilojoule(); + + /** + * Returns by pointer, unit of energy: kilowatt-hour. + * Caller owns returned value and must free it. + * Also see {@link #getKilowattHour()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilowattHour(UErrorCode &status); + + /** + * Returns by value, unit of energy: kilowatt-hour. + * Also see {@link #createKilowattHour()}. + * @stable ICU 64 + */ + static MeasureUnit getKilowattHour(); + + /** + * Returns by pointer, unit of energy: therm-us. + * Caller owns returned value and must free it. + * Also see {@link #getThermUs()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createThermUs(UErrorCode &status); + + /** + * Returns by value, unit of energy: therm-us. + * Also see {@link #createThermUs()}. + * @stable ICU 65 + */ + static MeasureUnit getThermUs(); + + /** + * Returns by pointer, unit of force: kilowatt-hour-per-100-kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getKilowattHourPer100Kilometer()}. + * @param status ICU error code. + * @stable ICU 70 + */ + static MeasureUnit *createKilowattHourPer100Kilometer(UErrorCode &status); + + /** + * Returns by value, unit of force: kilowatt-hour-per-100-kilometer. + * Also see {@link #createKilowattHourPer100Kilometer()}. + * @stable ICU 70 + */ + static MeasureUnit getKilowattHourPer100Kilometer(); + + /** + * Returns by pointer, unit of force: newton. + * Caller owns returned value and must free it. + * Also see {@link #getNewton()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createNewton(UErrorCode &status); + + /** + * Returns by value, unit of force: newton. + * Also see {@link #createNewton()}. + * @stable ICU 64 + */ + static MeasureUnit getNewton(); + + /** + * Returns by pointer, unit of force: pound-force. + * Caller owns returned value and must free it. + * Also see {@link #getPoundForce()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createPoundForce(UErrorCode &status); + + /** + * Returns by value, unit of force: pound-force. + * Also see {@link #createPoundForce()}. + * @stable ICU 64 + */ + static MeasureUnit getPoundForce(); + + /** + * Returns by pointer, unit of frequency: gigahertz. + * Caller owns returned value and must free it. + * Also see {@link #getGigahertz()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createGigahertz(UErrorCode &status); + + /** + * Returns by value, unit of frequency: gigahertz. + * Also see {@link #createGigahertz()}. + * @stable ICU 64 + */ + static MeasureUnit getGigahertz(); + + /** + * Returns by pointer, unit of frequency: hertz. + * Caller owns returned value and must free it. + * Also see {@link #getHertz()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createHertz(UErrorCode &status); + + /** + * Returns by value, unit of frequency: hertz. + * Also see {@link #createHertz()}. + * @stable ICU 64 + */ + static MeasureUnit getHertz(); + + /** + * Returns by pointer, unit of frequency: kilohertz. + * Caller owns returned value and must free it. + * Also see {@link #getKilohertz()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKilohertz(UErrorCode &status); + + /** + * Returns by value, unit of frequency: kilohertz. + * Also see {@link #createKilohertz()}. + * @stable ICU 64 + */ + static MeasureUnit getKilohertz(); + + /** + * Returns by pointer, unit of frequency: megahertz. + * Caller owns returned value and must free it. + * Also see {@link #getMegahertz()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMegahertz(UErrorCode &status); + + /** + * Returns by value, unit of frequency: megahertz. + * Also see {@link #createMegahertz()}. + * @stable ICU 64 + */ + static MeasureUnit getMegahertz(); + + /** + * Returns by pointer, unit of graphics: dot. + * Caller owns returned value and must free it. + * Also see {@link #getDot()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createDot(UErrorCode &status); + + /** + * Returns by value, unit of graphics: dot. + * Also see {@link #createDot()}. + * @stable ICU 68 + */ + static MeasureUnit getDot(); + + /** + * Returns by pointer, unit of graphics: dot-per-centimeter. + * Caller owns returned value and must free it. + * Also see {@link #getDotPerCentimeter()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createDotPerCentimeter(UErrorCode &status); + + /** + * Returns by value, unit of graphics: dot-per-centimeter. + * Also see {@link #createDotPerCentimeter()}. + * @stable ICU 65 + */ + static MeasureUnit getDotPerCentimeter(); + + /** + * Returns by pointer, unit of graphics: dot-per-inch. + * Caller owns returned value and must free it. + * Also see {@link #getDotPerInch()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createDotPerInch(UErrorCode &status); + + /** + * Returns by value, unit of graphics: dot-per-inch. + * Also see {@link #createDotPerInch()}. + * @stable ICU 65 + */ + static MeasureUnit getDotPerInch(); + + /** + * Returns by pointer, unit of graphics: em. + * Caller owns returned value and must free it. + * Also see {@link #getEm()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createEm(UErrorCode &status); + + /** + * Returns by value, unit of graphics: em. + * Also see {@link #createEm()}. + * @stable ICU 65 + */ + static MeasureUnit getEm(); + + /** + * Returns by pointer, unit of graphics: megapixel. + * Caller owns returned value and must free it. + * Also see {@link #getMegapixel()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createMegapixel(UErrorCode &status); + + /** + * Returns by value, unit of graphics: megapixel. + * Also see {@link #createMegapixel()}. + * @stable ICU 65 + */ + static MeasureUnit getMegapixel(); + + /** + * Returns by pointer, unit of graphics: pixel. + * Caller owns returned value and must free it. + * Also see {@link #getPixel()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createPixel(UErrorCode &status); + + /** + * Returns by value, unit of graphics: pixel. + * Also see {@link #createPixel()}. + * @stable ICU 65 + */ + static MeasureUnit getPixel(); + + /** + * Returns by pointer, unit of graphics: pixel-per-centimeter. + * Caller owns returned value and must free it. + * Also see {@link #getPixelPerCentimeter()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createPixelPerCentimeter(UErrorCode &status); + + /** + * Returns by value, unit of graphics: pixel-per-centimeter. + * Also see {@link #createPixelPerCentimeter()}. + * @stable ICU 65 + */ + static MeasureUnit getPixelPerCentimeter(); + + /** + * Returns by pointer, unit of graphics: pixel-per-inch. + * Caller owns returned value and must free it. + * Also see {@link #getPixelPerInch()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createPixelPerInch(UErrorCode &status); + + /** + * Returns by value, unit of graphics: pixel-per-inch. + * Also see {@link #createPixelPerInch()}. + * @stable ICU 65 + */ + static MeasureUnit getPixelPerInch(); + + /** + * Returns by pointer, unit of length: astronomical-unit. + * Caller owns returned value and must free it. + * Also see {@link #getAstronomicalUnit()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createAstronomicalUnit(UErrorCode &status); + + /** + * Returns by value, unit of length: astronomical-unit. + * Also see {@link #createAstronomicalUnit()}. + * @stable ICU 64 + */ + static MeasureUnit getAstronomicalUnit(); + + /** + * Returns by pointer, unit of length: centimeter. + * Caller owns returned value and must free it. + * Also see {@link #getCentimeter()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createCentimeter(UErrorCode &status); + + /** + * Returns by value, unit of length: centimeter. + * Also see {@link #createCentimeter()}. + * @stable ICU 64 + */ + static MeasureUnit getCentimeter(); + + /** + * Returns by pointer, unit of length: decimeter. + * Caller owns returned value and must free it. + * Also see {@link #getDecimeter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createDecimeter(UErrorCode &status); + + /** + * Returns by value, unit of length: decimeter. + * Also see {@link #createDecimeter()}. + * @stable ICU 64 + */ + static MeasureUnit getDecimeter(); + + /** + * Returns by pointer, unit of length: earth-radius. + * Caller owns returned value and must free it. + * Also see {@link #getEarthRadius()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createEarthRadius(UErrorCode &status); + + /** + * Returns by value, unit of length: earth-radius. + * Also see {@link #createEarthRadius()}. + * @stable ICU 68 + */ + static MeasureUnit getEarthRadius(); + + /** + * Returns by pointer, unit of length: fathom. + * Caller owns returned value and must free it. + * Also see {@link #getFathom()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createFathom(UErrorCode &status); + + /** + * Returns by value, unit of length: fathom. + * Also see {@link #createFathom()}. + * @stable ICU 64 + */ + static MeasureUnit getFathom(); + + /** + * Returns by pointer, unit of length: foot. + * Caller owns returned value and must free it. + * Also see {@link #getFoot()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createFoot(UErrorCode &status); + + /** + * Returns by value, unit of length: foot. + * Also see {@link #createFoot()}. + * @stable ICU 64 + */ + static MeasureUnit getFoot(); + + /** + * Returns by pointer, unit of length: furlong. + * Caller owns returned value and must free it. + * Also see {@link #getFurlong()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createFurlong(UErrorCode &status); + + /** + * Returns by value, unit of length: furlong. + * Also see {@link #createFurlong()}. + * @stable ICU 64 + */ + static MeasureUnit getFurlong(); + + /** + * Returns by pointer, unit of length: inch. + * Caller owns returned value and must free it. + * Also see {@link #getInch()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createInch(UErrorCode &status); + + /** + * Returns by value, unit of length: inch. + * Also see {@link #createInch()}. + * @stable ICU 64 + */ + static MeasureUnit getInch(); + + /** + * Returns by pointer, unit of length: kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getKilometer()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createKilometer(UErrorCode &status); + + /** + * Returns by value, unit of length: kilometer. + * Also see {@link #createKilometer()}. + * @stable ICU 64 + */ + static MeasureUnit getKilometer(); + + /** + * Returns by pointer, unit of length: light-year. + * Caller owns returned value and must free it. + * Also see {@link #getLightYear()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createLightYear(UErrorCode &status); + + /** + * Returns by value, unit of length: light-year. + * Also see {@link #createLightYear()}. + * @stable ICU 64 + */ + static MeasureUnit getLightYear(); + + /** + * Returns by pointer, unit of length: meter. + * Caller owns returned value and must free it. + * Also see {@link #getMeter()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMeter(UErrorCode &status); + + /** + * Returns by value, unit of length: meter. + * Also see {@link #createMeter()}. + * @stable ICU 64 + */ + static MeasureUnit getMeter(); + + /** + * Returns by pointer, unit of length: micrometer. + * Caller owns returned value and must free it. + * Also see {@link #getMicrometer()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMicrometer(UErrorCode &status); + + /** + * Returns by value, unit of length: micrometer. + * Also see {@link #createMicrometer()}. + * @stable ICU 64 + */ + static MeasureUnit getMicrometer(); + + /** + * Returns by pointer, unit of length: mile. + * Caller owns returned value and must free it. + * Also see {@link #getMile()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMile(UErrorCode &status); + + /** + * Returns by value, unit of length: mile. + * Also see {@link #createMile()}. + * @stable ICU 64 + */ + static MeasureUnit getMile(); + + /** + * Returns by pointer, unit of length: mile-scandinavian. + * Caller owns returned value and must free it. + * Also see {@link #getMileScandinavian()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createMileScandinavian(UErrorCode &status); + + /** + * Returns by value, unit of length: mile-scandinavian. + * Also see {@link #createMileScandinavian()}. + * @stable ICU 64 + */ + static MeasureUnit getMileScandinavian(); + + /** + * Returns by pointer, unit of length: millimeter. + * Caller owns returned value and must free it. + * Also see {@link #getMillimeter()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMillimeter(UErrorCode &status); + + /** + * Returns by value, unit of length: millimeter. + * Also see {@link #createMillimeter()}. + * @stable ICU 64 + */ + static MeasureUnit getMillimeter(); + + /** + * Returns by pointer, unit of length: nanometer. + * Caller owns returned value and must free it. + * Also see {@link #getNanometer()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createNanometer(UErrorCode &status); + + /** + * Returns by value, unit of length: nanometer. + * Also see {@link #createNanometer()}. + * @stable ICU 64 + */ + static MeasureUnit getNanometer(); + + /** + * Returns by pointer, unit of length: nautical-mile. + * Caller owns returned value and must free it. + * Also see {@link #getNauticalMile()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createNauticalMile(UErrorCode &status); + + /** + * Returns by value, unit of length: nautical-mile. + * Also see {@link #createNauticalMile()}. + * @stable ICU 64 + */ + static MeasureUnit getNauticalMile(); + + /** + * Returns by pointer, unit of length: parsec. + * Caller owns returned value and must free it. + * Also see {@link #getParsec()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createParsec(UErrorCode &status); + + /** + * Returns by value, unit of length: parsec. + * Also see {@link #createParsec()}. + * @stable ICU 64 + */ + static MeasureUnit getParsec(); + + /** + * Returns by pointer, unit of length: picometer. + * Caller owns returned value and must free it. + * Also see {@link #getPicometer()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createPicometer(UErrorCode &status); + + /** + * Returns by value, unit of length: picometer. + * Also see {@link #createPicometer()}. + * @stable ICU 64 + */ + static MeasureUnit getPicometer(); + + /** + * Returns by pointer, unit of length: point. + * Caller owns returned value and must free it. + * Also see {@link #getPoint()}. + * @param status ICU error code. + * @stable ICU 59 + */ + static MeasureUnit *createPoint(UErrorCode &status); + + /** + * Returns by value, unit of length: point. + * Also see {@link #createPoint()}. + * @stable ICU 64 + */ + static MeasureUnit getPoint(); + + /** + * Returns by pointer, unit of length: solar-radius. + * Caller owns returned value and must free it. + * Also see {@link #getSolarRadius()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createSolarRadius(UErrorCode &status); + + /** + * Returns by value, unit of length: solar-radius. + * Also see {@link #createSolarRadius()}. + * @stable ICU 64 + */ + static MeasureUnit getSolarRadius(); + + /** + * Returns by pointer, unit of length: yard. + * Caller owns returned value and must free it. + * Also see {@link #getYard()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createYard(UErrorCode &status); + + /** + * Returns by value, unit of length: yard. + * Also see {@link #createYard()}. + * @stable ICU 64 + */ + static MeasureUnit getYard(); + + /** + * Returns by pointer, unit of light: candela. + * Caller owns returned value and must free it. + * Also see {@link #getCandela()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createCandela(UErrorCode &status); + + /** + * Returns by value, unit of light: candela. + * Also see {@link #createCandela()}. + * @stable ICU 68 + */ + static MeasureUnit getCandela(); + + /** + * Returns by pointer, unit of light: lumen. + * Caller owns returned value and must free it. + * Also see {@link #getLumen()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createLumen(UErrorCode &status); + + /** + * Returns by value, unit of light: lumen. + * Also see {@link #createLumen()}. + * @stable ICU 68 + */ + static MeasureUnit getLumen(); + + /** + * Returns by pointer, unit of light: lux. + * Caller owns returned value and must free it. + * Also see {@link #getLux()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createLux(UErrorCode &status); + + /** + * Returns by value, unit of light: lux. + * Also see {@link #createLux()}. + * @stable ICU 64 + */ + static MeasureUnit getLux(); + + /** + * Returns by pointer, unit of light: solar-luminosity. + * Caller owns returned value and must free it. + * Also see {@link #getSolarLuminosity()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createSolarLuminosity(UErrorCode &status); + + /** + * Returns by value, unit of light: solar-luminosity. + * Also see {@link #createSolarLuminosity()}. + * @stable ICU 64 + */ + static MeasureUnit getSolarLuminosity(); + + /** + * Returns by pointer, unit of mass: carat. + * Caller owns returned value and must free it. + * Also see {@link #getCarat()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCarat(UErrorCode &status); + + /** + * Returns by value, unit of mass: carat. + * Also see {@link #createCarat()}. + * @stable ICU 64 + */ + static MeasureUnit getCarat(); + + /** + * Returns by pointer, unit of mass: dalton. + * Caller owns returned value and must free it. + * Also see {@link #getDalton()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createDalton(UErrorCode &status); + + /** + * Returns by value, unit of mass: dalton. + * Also see {@link #createDalton()}. + * @stable ICU 64 + */ + static MeasureUnit getDalton(); + + /** + * Returns by pointer, unit of mass: earth-mass. + * Caller owns returned value and must free it. + * Also see {@link #getEarthMass()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createEarthMass(UErrorCode &status); + + /** + * Returns by value, unit of mass: earth-mass. + * Also see {@link #createEarthMass()}. + * @stable ICU 64 + */ + static MeasureUnit getEarthMass(); + + /** + * Returns by pointer, unit of mass: grain. + * Caller owns returned value and must free it. + * Also see {@link #getGrain()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createGrain(UErrorCode &status); + + /** + * Returns by value, unit of mass: grain. + * Also see {@link #createGrain()}. + * @stable ICU 68 + */ + static MeasureUnit getGrain(); + + /** + * Returns by pointer, unit of mass: gram. + * Caller owns returned value and must free it. + * Also see {@link #getGram()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createGram(UErrorCode &status); + + /** + * Returns by value, unit of mass: gram. + * Also see {@link #createGram()}. + * @stable ICU 64 + */ + static MeasureUnit getGram(); + + /** + * Returns by pointer, unit of mass: kilogram. + * Caller owns returned value and must free it. + * Also see {@link #getKilogram()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createKilogram(UErrorCode &status); + + /** + * Returns by value, unit of mass: kilogram. + * Also see {@link #createKilogram()}. + * @stable ICU 64 + */ + static MeasureUnit getKilogram(); + + /** + * Returns by pointer, unit of mass: metric-ton + * (renamed to tonne in CLDR 42 / ICU 72). + * Caller owns returned value and must free it. + * Note: In ICU 74 this will be deprecated in favor of + * createTonne(), which is currently draft but will + * become stable in ICU 74, and which uses the preferred naming. + * Also see {@link #getMetricTon()} and {@link #createTonne()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMetricTon(UErrorCode &status); + + /** + * Returns by value, unit of mass: metric-ton + * (renamed to tonne in CLDR 42 / ICU 72). + * Note: In ICU 74 this will be deprecated in favor of + * getTonne(), which is currently draft but will + * become stable in ICU 74, and which uses the preferred naming. + * Also see {@link #createMetricTon()} and {@link #getTonne()}. + * @stable ICU 64 + */ + static MeasureUnit getMetricTon(); + + /** + * Returns by pointer, unit of mass: microgram. + * Caller owns returned value and must free it. + * Also see {@link #getMicrogram()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMicrogram(UErrorCode &status); + + /** + * Returns by value, unit of mass: microgram. + * Also see {@link #createMicrogram()}. + * @stable ICU 64 + */ + static MeasureUnit getMicrogram(); + + /** + * Returns by pointer, unit of mass: milligram. + * Caller owns returned value and must free it. + * Also see {@link #getMilligram()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMilligram(UErrorCode &status); + + /** + * Returns by value, unit of mass: milligram. + * Also see {@link #createMilligram()}. + * @stable ICU 64 + */ + static MeasureUnit getMilligram(); + + /** + * Returns by pointer, unit of mass: ounce. + * Caller owns returned value and must free it. + * Also see {@link #getOunce()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createOunce(UErrorCode &status); + + /** + * Returns by value, unit of mass: ounce. + * Also see {@link #createOunce()}. + * @stable ICU 64 + */ + static MeasureUnit getOunce(); + + /** + * Returns by pointer, unit of mass: ounce-troy. + * Caller owns returned value and must free it. + * Also see {@link #getOunceTroy()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createOunceTroy(UErrorCode &status); + + /** + * Returns by value, unit of mass: ounce-troy. + * Also see {@link #createOunceTroy()}. + * @stable ICU 64 + */ + static MeasureUnit getOunceTroy(); + + /** + * Returns by pointer, unit of mass: pound. + * Caller owns returned value and must free it. + * Also see {@link #getPound()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createPound(UErrorCode &status); + + /** + * Returns by value, unit of mass: pound. + * Also see {@link #createPound()}. + * @stable ICU 64 + */ + static MeasureUnit getPound(); + + /** + * Returns by pointer, unit of mass: solar-mass. + * Caller owns returned value and must free it. + * Also see {@link #getSolarMass()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createSolarMass(UErrorCode &status); + + /** + * Returns by value, unit of mass: solar-mass. + * Also see {@link #createSolarMass()}. + * @stable ICU 64 + */ + static MeasureUnit getSolarMass(); + + /** + * Returns by pointer, unit of mass: stone. + * Caller owns returned value and must free it. + * Also see {@link #getStone()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createStone(UErrorCode &status); + + /** + * Returns by value, unit of mass: stone. + * Also see {@link #createStone()}. + * @stable ICU 64 + */ + static MeasureUnit getStone(); + + /** + * Returns by pointer, unit of mass: ton. + * Caller owns returned value and must free it. + * Also see {@link #getTon()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createTon(UErrorCode &status); + + /** + * Returns by value, unit of mass: ton. + * Also see {@link #createTon()}. + * @stable ICU 64 + */ + static MeasureUnit getTon(); + +#ifndef U_HIDE_DRAFT_API + /** + * Returns by pointer, unit of mass: tonne. + * Caller owns returned value and must free it. + * Also see {@link #getTonne()}. + * @param status ICU error code. + * @draft ICU 72 + */ + static MeasureUnit *createTonne(UErrorCode &status); + + /** + * Returns by value, unit of mass: tonne. + * Also see {@link #createTonne()}. + * @draft ICU 72 + */ + static MeasureUnit getTonne(); +#endif /* U_HIDE_DRAFT_API */ + + /** + * Returns by pointer, unit of power: gigawatt. + * Caller owns returned value and must free it. + * Also see {@link #getGigawatt()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createGigawatt(UErrorCode &status); + + /** + * Returns by value, unit of power: gigawatt. + * Also see {@link #createGigawatt()}. + * @stable ICU 64 + */ + static MeasureUnit getGigawatt(); + + /** + * Returns by pointer, unit of power: horsepower. + * Caller owns returned value and must free it. + * Also see {@link #getHorsepower()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createHorsepower(UErrorCode &status); + + /** + * Returns by value, unit of power: horsepower. + * Also see {@link #createHorsepower()}. + * @stable ICU 64 + */ + static MeasureUnit getHorsepower(); + + /** + * Returns by pointer, unit of power: kilowatt. + * Caller owns returned value and must free it. + * Also see {@link #getKilowatt()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createKilowatt(UErrorCode &status); + + /** + * Returns by value, unit of power: kilowatt. + * Also see {@link #createKilowatt()}. + * @stable ICU 64 + */ + static MeasureUnit getKilowatt(); + + /** + * Returns by pointer, unit of power: megawatt. + * Caller owns returned value and must free it. + * Also see {@link #getMegawatt()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMegawatt(UErrorCode &status); + + /** + * Returns by value, unit of power: megawatt. + * Also see {@link #createMegawatt()}. + * @stable ICU 64 + */ + static MeasureUnit getMegawatt(); + + /** + * Returns by pointer, unit of power: milliwatt. + * Caller owns returned value and must free it. + * Also see {@link #getMilliwatt()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMilliwatt(UErrorCode &status); + + /** + * Returns by value, unit of power: milliwatt. + * Also see {@link #createMilliwatt()}. + * @stable ICU 64 + */ + static MeasureUnit getMilliwatt(); + + /** + * Returns by pointer, unit of power: watt. + * Caller owns returned value and must free it. + * Also see {@link #getWatt()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createWatt(UErrorCode &status); + + /** + * Returns by value, unit of power: watt. + * Also see {@link #createWatt()}. + * @stable ICU 64 + */ + static MeasureUnit getWatt(); + + /** + * Returns by pointer, unit of pressure: atmosphere. + * Caller owns returned value and must free it. + * Also see {@link #getAtmosphere()}. + * @param status ICU error code. + * @stable ICU 63 + */ + static MeasureUnit *createAtmosphere(UErrorCode &status); + + /** + * Returns by value, unit of pressure: atmosphere. + * Also see {@link #createAtmosphere()}. + * @stable ICU 64 + */ + static MeasureUnit getAtmosphere(); + + /** + * Returns by pointer, unit of pressure: bar. + * Caller owns returned value and must free it. + * Also see {@link #getBar()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createBar(UErrorCode &status); + + /** + * Returns by value, unit of pressure: bar. + * Also see {@link #createBar()}. + * @stable ICU 65 + */ + static MeasureUnit getBar(); + + /** + * Returns by pointer, unit of pressure: hectopascal. + * Caller owns returned value and must free it. + * Also see {@link #getHectopascal()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createHectopascal(UErrorCode &status); + + /** + * Returns by value, unit of pressure: hectopascal. + * Also see {@link #createHectopascal()}. + * @stable ICU 64 + */ + static MeasureUnit getHectopascal(); + + /** + * Returns by pointer, unit of pressure: inch-ofhg. + * Caller owns returned value and must free it. + * Also see {@link #getInchHg()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createInchHg(UErrorCode &status); + + /** + * Returns by value, unit of pressure: inch-ofhg. + * Also see {@link #createInchHg()}. + * @stable ICU 64 + */ + static MeasureUnit getInchHg(); + + /** + * Returns by pointer, unit of pressure: kilopascal. + * Caller owns returned value and must free it. + * Also see {@link #getKilopascal()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createKilopascal(UErrorCode &status); + + /** + * Returns by value, unit of pressure: kilopascal. + * Also see {@link #createKilopascal()}. + * @stable ICU 64 + */ + static MeasureUnit getKilopascal(); + + /** + * Returns by pointer, unit of pressure: megapascal. + * Caller owns returned value and must free it. + * Also see {@link #getMegapascal()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createMegapascal(UErrorCode &status); + + /** + * Returns by value, unit of pressure: megapascal. + * Also see {@link #createMegapascal()}. + * @stable ICU 64 + */ + static MeasureUnit getMegapascal(); + + /** + * Returns by pointer, unit of pressure: millibar. + * Caller owns returned value and must free it. + * Also see {@link #getMillibar()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMillibar(UErrorCode &status); + + /** + * Returns by value, unit of pressure: millibar. + * Also see {@link #createMillibar()}. + * @stable ICU 64 + */ + static MeasureUnit getMillibar(); + + /** + * Returns by pointer, unit of pressure: millimeter-ofhg. + * Caller owns returned value and must free it. + * Also see {@link #getMillimeterOfMercury()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMillimeterOfMercury(UErrorCode &status); + + /** + * Returns by value, unit of pressure: millimeter-ofhg. + * Also see {@link #createMillimeterOfMercury()}. + * @stable ICU 64 + */ + static MeasureUnit getMillimeterOfMercury(); + + /** + * Returns by pointer, unit of pressure: pascal. + * Caller owns returned value and must free it. + * Also see {@link #getPascal()}. + * @param status ICU error code. + * @stable ICU 65 + */ + static MeasureUnit *createPascal(UErrorCode &status); + + /** + * Returns by value, unit of pressure: pascal. + * Also see {@link #createPascal()}. + * @stable ICU 65 + */ + static MeasureUnit getPascal(); + + /** + * Returns by pointer, unit of pressure: pound-force-per-square-inch. + * Caller owns returned value and must free it. + * Also see {@link #getPoundPerSquareInch()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createPoundPerSquareInch(UErrorCode &status); + + /** + * Returns by value, unit of pressure: pound-force-per-square-inch. + * Also see {@link #createPoundPerSquareInch()}. + * @stable ICU 64 + */ + static MeasureUnit getPoundPerSquareInch(); + +#ifndef U_HIDE_DRAFT_API + /** + * Returns by pointer, unit of speed: beaufort. + * Caller owns returned value and must free it. + * Also see {@link #getBeaufort()}. + * @param status ICU error code. + * @draft ICU 73 + */ + static MeasureUnit *createBeaufort(UErrorCode &status); + + /** + * Returns by value, unit of speed: beaufort. + * Also see {@link #createBeaufort()}. + * @draft ICU 73 + */ + static MeasureUnit getBeaufort(); +#endif /* U_HIDE_DRAFT_API */ + + /** + * Returns by pointer, unit of speed: kilometer-per-hour. + * Caller owns returned value and must free it. + * Also see {@link #getKilometerPerHour()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createKilometerPerHour(UErrorCode &status); + + /** + * Returns by value, unit of speed: kilometer-per-hour. + * Also see {@link #createKilometerPerHour()}. + * @stable ICU 64 + */ + static MeasureUnit getKilometerPerHour(); + + /** + * Returns by pointer, unit of speed: knot. + * Caller owns returned value and must free it. + * Also see {@link #getKnot()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createKnot(UErrorCode &status); + + /** + * Returns by value, unit of speed: knot. + * Also see {@link #createKnot()}. + * @stable ICU 64 + */ + static MeasureUnit getKnot(); + + /** + * Returns by pointer, unit of speed: meter-per-second. + * Caller owns returned value and must free it. + * Also see {@link #getMeterPerSecond()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMeterPerSecond(UErrorCode &status); + + /** + * Returns by value, unit of speed: meter-per-second. + * Also see {@link #createMeterPerSecond()}. + * @stable ICU 64 + */ + static MeasureUnit getMeterPerSecond(); + + /** + * Returns by pointer, unit of speed: mile-per-hour. + * Caller owns returned value and must free it. + * Also see {@link #getMilePerHour()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createMilePerHour(UErrorCode &status); + + /** + * Returns by value, unit of speed: mile-per-hour. + * Also see {@link #createMilePerHour()}. + * @stable ICU 64 + */ + static MeasureUnit getMilePerHour(); + + /** + * Returns by pointer, unit of temperature: celsius. + * Caller owns returned value and must free it. + * Also see {@link #getCelsius()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createCelsius(UErrorCode &status); + + /** + * Returns by value, unit of temperature: celsius. + * Also see {@link #createCelsius()}. + * @stable ICU 64 + */ + static MeasureUnit getCelsius(); + + /** + * Returns by pointer, unit of temperature: fahrenheit. + * Caller owns returned value and must free it. + * Also see {@link #getFahrenheit()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createFahrenheit(UErrorCode &status); + + /** + * Returns by value, unit of temperature: fahrenheit. + * Also see {@link #createFahrenheit()}. + * @stable ICU 64 + */ + static MeasureUnit getFahrenheit(); + + /** + * Returns by pointer, unit of temperature: generic. + * Caller owns returned value and must free it. + * Also see {@link #getGenericTemperature()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createGenericTemperature(UErrorCode &status); + + /** + * Returns by value, unit of temperature: generic. + * Also see {@link #createGenericTemperature()}. + * @stable ICU 64 + */ + static MeasureUnit getGenericTemperature(); + + /** + * Returns by pointer, unit of temperature: kelvin. + * Caller owns returned value and must free it. + * Also see {@link #getKelvin()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createKelvin(UErrorCode &status); + + /** + * Returns by value, unit of temperature: kelvin. + * Also see {@link #createKelvin()}. + * @stable ICU 64 + */ + static MeasureUnit getKelvin(); + + /** + * Returns by pointer, unit of torque: newton-meter. + * Caller owns returned value and must free it. + * Also see {@link #getNewtonMeter()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createNewtonMeter(UErrorCode &status); + + /** + * Returns by value, unit of torque: newton-meter. + * Also see {@link #createNewtonMeter()}. + * @stable ICU 64 + */ + static MeasureUnit getNewtonMeter(); + + /** + * Returns by pointer, unit of torque: pound-force-foot. + * Caller owns returned value and must free it. + * Also see {@link #getPoundFoot()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createPoundFoot(UErrorCode &status); + + /** + * Returns by value, unit of torque: pound-force-foot. + * Also see {@link #createPoundFoot()}. + * @stable ICU 64 + */ + static MeasureUnit getPoundFoot(); + + /** + * Returns by pointer, unit of volume: acre-foot. + * Caller owns returned value and must free it. + * Also see {@link #getAcreFoot()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createAcreFoot(UErrorCode &status); + + /** + * Returns by value, unit of volume: acre-foot. + * Also see {@link #createAcreFoot()}. + * @stable ICU 64 + */ + static MeasureUnit getAcreFoot(); + + /** + * Returns by pointer, unit of volume: barrel. + * Caller owns returned value and must free it. + * Also see {@link #getBarrel()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createBarrel(UErrorCode &status); + + /** + * Returns by value, unit of volume: barrel. + * Also see {@link #createBarrel()}. + * @stable ICU 64 + */ + static MeasureUnit getBarrel(); + + /** + * Returns by pointer, unit of volume: bushel. + * Caller owns returned value and must free it. + * Also see {@link #getBushel()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createBushel(UErrorCode &status); + + /** + * Returns by value, unit of volume: bushel. + * Also see {@link #createBushel()}. + * @stable ICU 64 + */ + static MeasureUnit getBushel(); + + /** + * Returns by pointer, unit of volume: centiliter. + * Caller owns returned value and must free it. + * Also see {@link #getCentiliter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCentiliter(UErrorCode &status); + + /** + * Returns by value, unit of volume: centiliter. + * Also see {@link #createCentiliter()}. + * @stable ICU 64 + */ + static MeasureUnit getCentiliter(); + + /** + * Returns by pointer, unit of volume: cubic-centimeter. + * Caller owns returned value and must free it. + * Also see {@link #getCubicCentimeter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCubicCentimeter(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-centimeter. + * Also see {@link #createCubicCentimeter()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicCentimeter(); + + /** + * Returns by pointer, unit of volume: cubic-foot. + * Caller owns returned value and must free it. + * Also see {@link #getCubicFoot()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCubicFoot(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-foot. + * Also see {@link #createCubicFoot()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicFoot(); + + /** + * Returns by pointer, unit of volume: cubic-inch. + * Caller owns returned value and must free it. + * Also see {@link #getCubicInch()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCubicInch(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-inch. + * Also see {@link #createCubicInch()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicInch(); + + /** + * Returns by pointer, unit of volume: cubic-kilometer. + * Caller owns returned value and must free it. + * Also see {@link #getCubicKilometer()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createCubicKilometer(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-kilometer. + * Also see {@link #createCubicKilometer()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicKilometer(); + + /** + * Returns by pointer, unit of volume: cubic-meter. + * Caller owns returned value and must free it. + * Also see {@link #getCubicMeter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCubicMeter(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-meter. + * Also see {@link #createCubicMeter()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicMeter(); + + /** + * Returns by pointer, unit of volume: cubic-mile. + * Caller owns returned value and must free it. + * Also see {@link #getCubicMile()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createCubicMile(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-mile. + * Also see {@link #createCubicMile()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicMile(); + + /** + * Returns by pointer, unit of volume: cubic-yard. + * Caller owns returned value and must free it. + * Also see {@link #getCubicYard()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCubicYard(UErrorCode &status); + + /** + * Returns by value, unit of volume: cubic-yard. + * Also see {@link #createCubicYard()}. + * @stable ICU 64 + */ + static MeasureUnit getCubicYard(); + + /** + * Returns by pointer, unit of volume: cup. + * Caller owns returned value and must free it. + * Also see {@link #getCup()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createCup(UErrorCode &status); + + /** + * Returns by value, unit of volume: cup. + * Also see {@link #createCup()}. + * @stable ICU 64 + */ + static MeasureUnit getCup(); + + /** + * Returns by pointer, unit of volume: cup-metric. + * Caller owns returned value and must free it. + * Also see {@link #getCupMetric()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createCupMetric(UErrorCode &status); + + /** + * Returns by value, unit of volume: cup-metric. + * Also see {@link #createCupMetric()}. + * @stable ICU 64 + */ + static MeasureUnit getCupMetric(); + + /** + * Returns by pointer, unit of volume: deciliter. + * Caller owns returned value and must free it. + * Also see {@link #getDeciliter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createDeciliter(UErrorCode &status); + + /** + * Returns by value, unit of volume: deciliter. + * Also see {@link #createDeciliter()}. + * @stable ICU 64 + */ + static MeasureUnit getDeciliter(); + + /** + * Returns by pointer, unit of volume: dessert-spoon. + * Caller owns returned value and must free it. + * Also see {@link #getDessertSpoon()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createDessertSpoon(UErrorCode &status); + + /** + * Returns by value, unit of volume: dessert-spoon. + * Also see {@link #createDessertSpoon()}. + * @stable ICU 68 + */ + static MeasureUnit getDessertSpoon(); + + /** + * Returns by pointer, unit of volume: dessert-spoon-imperial. + * Caller owns returned value and must free it. + * Also see {@link #getDessertSpoonImperial()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createDessertSpoonImperial(UErrorCode &status); + + /** + * Returns by value, unit of volume: dessert-spoon-imperial. + * Also see {@link #createDessertSpoonImperial()}. + * @stable ICU 68 + */ + static MeasureUnit getDessertSpoonImperial(); + + /** + * Returns by pointer, unit of volume: dram. + * Caller owns returned value and must free it. + * Also see {@link #getDram()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createDram(UErrorCode &status); + + /** + * Returns by value, unit of volume: dram. + * Also see {@link #createDram()}. + * @stable ICU 68 + */ + static MeasureUnit getDram(); + + /** + * Returns by pointer, unit of volume: drop. + * Caller owns returned value and must free it. + * Also see {@link #getDrop()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createDrop(UErrorCode &status); + + /** + * Returns by value, unit of volume: drop. + * Also see {@link #createDrop()}. + * @stable ICU 68 + */ + static MeasureUnit getDrop(); + + /** + * Returns by pointer, unit of volume: fluid-ounce. + * Caller owns returned value and must free it. + * Also see {@link #getFluidOunce()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createFluidOunce(UErrorCode &status); + + /** + * Returns by value, unit of volume: fluid-ounce. + * Also see {@link #createFluidOunce()}. + * @stable ICU 64 + */ + static MeasureUnit getFluidOunce(); + + /** + * Returns by pointer, unit of volume: fluid-ounce-imperial. + * Caller owns returned value and must free it. + * Also see {@link #getFluidOunceImperial()}. + * @param status ICU error code. + * @stable ICU 64 + */ + static MeasureUnit *createFluidOunceImperial(UErrorCode &status); + + /** + * Returns by value, unit of volume: fluid-ounce-imperial. + * Also see {@link #createFluidOunceImperial()}. + * @stable ICU 64 + */ + static MeasureUnit getFluidOunceImperial(); + + /** + * Returns by pointer, unit of volume: gallon. + * Caller owns returned value and must free it. + * Also see {@link #getGallon()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createGallon(UErrorCode &status); + + /** + * Returns by value, unit of volume: gallon. + * Also see {@link #createGallon()}. + * @stable ICU 64 + */ + static MeasureUnit getGallon(); + + /** + * Returns by pointer, unit of volume: gallon-imperial. + * Caller owns returned value and must free it. + * Also see {@link #getGallonImperial()}. + * @param status ICU error code. + * @stable ICU 57 + */ + static MeasureUnit *createGallonImperial(UErrorCode &status); + + /** + * Returns by value, unit of volume: gallon-imperial. + * Also see {@link #createGallonImperial()}. + * @stable ICU 64 + */ + static MeasureUnit getGallonImperial(); + + /** + * Returns by pointer, unit of volume: hectoliter. + * Caller owns returned value and must free it. + * Also see {@link #getHectoliter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createHectoliter(UErrorCode &status); + + /** + * Returns by value, unit of volume: hectoliter. + * Also see {@link #createHectoliter()}. + * @stable ICU 64 + */ + static MeasureUnit getHectoliter(); + + /** + * Returns by pointer, unit of volume: jigger. + * Caller owns returned value and must free it. + * Also see {@link #getJigger()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createJigger(UErrorCode &status); + + /** + * Returns by value, unit of volume: jigger. + * Also see {@link #createJigger()}. + * @stable ICU 68 + */ + static MeasureUnit getJigger(); + + /** + * Returns by pointer, unit of volume: liter. + * Caller owns returned value and must free it. + * Also see {@link #getLiter()}. + * @param status ICU error code. + * @stable ICU 53 + */ + static MeasureUnit *createLiter(UErrorCode &status); + + /** + * Returns by value, unit of volume: liter. + * Also see {@link #createLiter()}. + * @stable ICU 64 + */ + static MeasureUnit getLiter(); + + /** + * Returns by pointer, unit of volume: megaliter. + * Caller owns returned value and must free it. + * Also see {@link #getMegaliter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMegaliter(UErrorCode &status); + + /** + * Returns by value, unit of volume: megaliter. + * Also see {@link #createMegaliter()}. + * @stable ICU 64 + */ + static MeasureUnit getMegaliter(); + + /** + * Returns by pointer, unit of volume: milliliter. + * Caller owns returned value and must free it. + * Also see {@link #getMilliliter()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createMilliliter(UErrorCode &status); + + /** + * Returns by value, unit of volume: milliliter. + * Also see {@link #createMilliliter()}. + * @stable ICU 64 + */ + static MeasureUnit getMilliliter(); + + /** + * Returns by pointer, unit of volume: pinch. + * Caller owns returned value and must free it. + * Also see {@link #getPinch()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createPinch(UErrorCode &status); + + /** + * Returns by value, unit of volume: pinch. + * Also see {@link #createPinch()}. + * @stable ICU 68 + */ + static MeasureUnit getPinch(); + + /** + * Returns by pointer, unit of volume: pint. + * Caller owns returned value and must free it. + * Also see {@link #getPint()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createPint(UErrorCode &status); + + /** + * Returns by value, unit of volume: pint. + * Also see {@link #createPint()}. + * @stable ICU 64 + */ + static MeasureUnit getPint(); + + /** + * Returns by pointer, unit of volume: pint-metric. + * Caller owns returned value and must free it. + * Also see {@link #getPintMetric()}. + * @param status ICU error code. + * @stable ICU 56 + */ + static MeasureUnit *createPintMetric(UErrorCode &status); + + /** + * Returns by value, unit of volume: pint-metric. + * Also see {@link #createPintMetric()}. + * @stable ICU 64 + */ + static MeasureUnit getPintMetric(); + + /** + * Returns by pointer, unit of volume: quart. + * Caller owns returned value and must free it. + * Also see {@link #getQuart()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createQuart(UErrorCode &status); + + /** + * Returns by value, unit of volume: quart. + * Also see {@link #createQuart()}. + * @stable ICU 64 + */ + static MeasureUnit getQuart(); + + /** + * Returns by pointer, unit of volume: quart-imperial. + * Caller owns returned value and must free it. + * Also see {@link #getQuartImperial()}. + * @param status ICU error code. + * @stable ICU 68 + */ + static MeasureUnit *createQuartImperial(UErrorCode &status); + + /** + * Returns by value, unit of volume: quart-imperial. + * Also see {@link #createQuartImperial()}. + * @stable ICU 68 + */ + static MeasureUnit getQuartImperial(); + + /** + * Returns by pointer, unit of volume: tablespoon. + * Caller owns returned value and must free it. + * Also see {@link #getTablespoon()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createTablespoon(UErrorCode &status); + + /** + * Returns by value, unit of volume: tablespoon. + * Also see {@link #createTablespoon()}. + * @stable ICU 64 + */ + static MeasureUnit getTablespoon(); + + /** + * Returns by pointer, unit of volume: teaspoon. + * Caller owns returned value and must free it. + * Also see {@link #getTeaspoon()}. + * @param status ICU error code. + * @stable ICU 54 + */ + static MeasureUnit *createTeaspoon(UErrorCode &status); + + /** + * Returns by value, unit of volume: teaspoon. + * Also see {@link #createTeaspoon()}. + * @stable ICU 64 + */ + static MeasureUnit getTeaspoon(); + +// End generated createXXX methods + + protected: + +#ifndef U_HIDE_INTERNAL_API + /** + * For ICU use only. + * @internal + */ + void initTime(const char *timeId); + + /** + * For ICU use only. + * @internal + */ + void initCurrency(StringPiece isoCurrency); + +#endif /* U_HIDE_INTERNAL_API */ + +private: + + // Used by new draft APIs in ICU 67. If non-null, fImpl is owned by the + // MeasureUnit. + MeasureUnitImpl* fImpl; + + // An index into a static string list in measunit.cpp. If set to -1, fImpl + // is in use instead of fTypeId and fSubTypeId. + int16_t fSubTypeId; + // An index into a static string list in measunit.cpp. If set to -1, fImpl + // is in use instead of fTypeId and fSubTypeId. + int8_t fTypeId; + + MeasureUnit(int32_t typeId, int32_t subTypeId); + MeasureUnit(MeasureUnitImpl&& impl); + void setTo(int32_t typeId, int32_t subTypeId); + static MeasureUnit *create(int typeId, int subTypeId, UErrorCode &status); + + /** + * Sets output's typeId and subTypeId according to subType, if subType is a + * valid/known identifier. + * + * @return Whether subType is known to ICU. If false, output was not + * modified. + */ + static bool findBySubType(StringPiece subType, MeasureUnit* output); + + /** Internal version of public API */ + LocalArray splitToSingleUnitsImpl(int32_t& outCount, UErrorCode& status) const; + + friend class MeasureUnitImpl; + + // For access to findBySubType + friend class number::impl::LongNameHandler; +}; + +// inline impl of @stable ICU 68 method +inline std::pair, int32_t> +MeasureUnit::splitToSingleUnits(UErrorCode& status) const { + int32_t length; + auto array = splitToSingleUnitsImpl(length, status); + return std::make_pair(std::move(array), length); +} + +U_NAMESPACE_END + +#endif // !UNCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __MEASUREUNIT_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measure.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measure.h new file mode 100644 index 0000000000000000000000000000000000000000..31f931d7d4a9e6efa5c7a60a651be5c397ad4ebf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/measure.h @@ -0,0 +1,166 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2004-2015, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: April 26, 2004 +* Since: ICU 3.0 +********************************************************************** +*/ +#ifndef __MEASURE_H__ +#define __MEASURE_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: MeasureUnit object. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/fmtable.h" + +U_NAMESPACE_BEGIN + +class MeasureUnit; + +/** + * An amount of a specified unit, consisting of a number and a Unit. + * For example, a length measure consists of a number and a length + * unit, such as feet or meters. + * + *

Measure objects are formatted by MeasureFormat. + * + *

Measure objects are immutable. + * + * @author Alan Liu + * @stable ICU 3.0 + */ +class U_I18N_API Measure: public UObject { + public: + /** + * Construct an object with the given numeric amount and the given + * unit. After this call, the caller must not delete the given + * unit object. + * @param number a numeric object; amount.isNumeric() must be true + * @param adoptedUnit the unit object, which must not be nullptr + * @param ec input-output error code. If the amount or the unit + * is invalid, then this will be set to a failing value. + * @stable ICU 3.0 + */ + Measure(const Formattable& number, MeasureUnit* adoptedUnit, + UErrorCode& ec); + + /** + * Copy constructor + * @stable ICU 3.0 + */ + Measure(const Measure& other); + + /** + * Assignment operator + * @stable ICU 3.0 + */ + Measure& operator=(const Measure& other); + + /** + * Return a polymorphic clone of this object. The result will + * have the same class as returned by getDynamicClassID(). + * @stable ICU 3.0 + */ + virtual Measure* clone() const; + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~Measure(); + + /** + * Equality operator. Return true if this object is equal + * to the given object. + * @stable ICU 3.0 + */ + bool operator==(const UObject& other) const; + + /** + * Return a reference to the numeric value of this object. The + * numeric value may be of any numeric type supported by + * Formattable. + * @stable ICU 3.0 + */ + inline const Formattable& getNumber() const; + + /** + * Return a reference to the unit of this object. + * @stable ICU 3.0 + */ + inline const MeasureUnit& getUnit() const; + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 53 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 53 + */ + virtual UClassID getDynamicClassID(void) const override; + + protected: + /** + * Default constructor. + * @stable ICU 3.0 + */ + Measure(); + + private: + /** + * The numeric value of this object, e.g. 2.54 or 100. + */ + Formattable number; + + /** + * The unit of this object, e.g., "millimeter" or "JPY". This is + * owned by this object. + */ + MeasureUnit* unit; +}; + +inline const Formattable& Measure::getNumber() const { + return number; +} + +inline const MeasureUnit& Measure::getUnit() const { + return *unit; +} + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __MEASURE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/messagepattern.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/messagepattern.h new file mode 100644 index 0000000000000000000000000000000000000000..55b09bfbd4b5dc2776ce1d0b3c15a2ef5e2f135d --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/messagepattern.h @@ -0,0 +1,949 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2011-2013, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: messagepattern.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2011mar14 +* created by: Markus W. Scherer +*/ + +#ifndef __MESSAGEPATTERN_H__ +#define __MESSAGEPATTERN_H__ + +/** + * \file + * \brief C++ API: MessagePattern class: Parses and represents ICU MessageFormat patterns. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/parseerr.h" +#include "unicode/unistr.h" + +/** + * Mode for when an apostrophe starts quoted literal text for MessageFormat output. + * The default is DOUBLE_OPTIONAL unless overridden via uconfig.h + * (UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE). + *

+ * A pair of adjacent apostrophes always results in a single apostrophe in the output, + * even when the pair is between two single, text-quoting apostrophes. + *

+ * The following table shows examples of desired MessageFormat.format() output + * with the pattern strings that yield that output. + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Desired outputDOUBLE_OPTIONALDOUBLE_REQUIRED
I see {many}I see '{many}'(same)
I said {'Wow!'}I said '{''Wow!''}'(same)
I don't knowI don't know OR
I don''t know
I don''t know
+ * @stable ICU 4.8 + * @see UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE + */ +enum UMessagePatternApostropheMode { + /** + * A literal apostrophe is represented by + * either a single or a double apostrophe pattern character. + * Within a MessageFormat pattern, a single apostrophe only starts quoted literal text + * if it immediately precedes a curly brace {}, + * or a pipe symbol | if inside a choice format, + * or a pound symbol # if inside a plural format. + *

+ * This is the default behavior starting with ICU 4.8. + * @stable ICU 4.8 + */ + UMSGPAT_APOS_DOUBLE_OPTIONAL, + /** + * A literal apostrophe must be represented by + * a double apostrophe pattern character. + * A single apostrophe always starts quoted literal text. + *

+ * This is the behavior of ICU 4.6 and earlier, and of the JDK. + * @stable ICU 4.8 + */ + UMSGPAT_APOS_DOUBLE_REQUIRED +}; +/** + * @stable ICU 4.8 + */ +typedef enum UMessagePatternApostropheMode UMessagePatternApostropheMode; + +/** + * MessagePattern::Part type constants. + * @stable ICU 4.8 + */ +enum UMessagePatternPartType { + /** + * Start of a message pattern (main or nested). + * The length is 0 for the top-level message + * and for a choice argument sub-message, otherwise 1 for the '{'. + * The value indicates the nesting level, starting with 0 for the main message. + *

+ * There is always a later MSG_LIMIT part. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_MSG_START, + /** + * End of a message pattern (main or nested). + * The length is 0 for the top-level message and + * the last sub-message of a choice argument, + * otherwise 1 for the '}' or (in a choice argument style) the '|'. + * The value indicates the nesting level, starting with 0 for the main message. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_MSG_LIMIT, + /** + * Indicates a substring of the pattern string which is to be skipped when formatting. + * For example, an apostrophe that begins or ends quoted text + * would be indicated with such a part. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_SKIP_SYNTAX, + /** + * Indicates that a syntax character needs to be inserted for auto-quoting. + * The length is 0. + * The value is the character code of the insertion character. (U+0027=APOSTROPHE) + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_INSERT_CHAR, + /** + * Indicates a syntactic (non-escaped) # symbol in a plural variant. + * When formatting, replace this part's substring with the + * (value-offset) for the plural argument value. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_REPLACE_NUMBER, + /** + * Start of an argument. + * The length is 1 for the '{'. + * The value is the ordinal value of the ArgType. Use getArgType(). + *

+ * This part is followed by either an ARG_NUMBER or ARG_NAME, + * followed by optional argument sub-parts (see UMessagePatternArgType constants) + * and finally an ARG_LIMIT part. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_START, + /** + * End of an argument. + * The length is 1 for the '}'. + * The value is the ordinal value of the ArgType. Use getArgType(). + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_LIMIT, + /** + * The argument number, provided by the value. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_NUMBER, + /** + * The argument name. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_NAME, + /** + * The argument type. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_TYPE, + /** + * The argument style text. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_STYLE, + /** + * A selector substring in a "complex" argument style. + * The value is undefined and currently always 0. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_SELECTOR, + /** + * An integer value, for example the offset or an explicit selector value + * in a PluralFormat style. + * The part value is the integer value. + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_INT, + /** + * A numeric value, for example the offset or an explicit selector value + * in a PluralFormat style. + * The part value is an index into an internal array of numeric values; + * use getNumericValue(). + * @stable ICU 4.8 + */ + UMSGPAT_PART_TYPE_ARG_DOUBLE +}; +/** + * @stable ICU 4.8 + */ +typedef enum UMessagePatternPartType UMessagePatternPartType; + +/** + * Argument type constants. + * Returned by Part.getArgType() for ARG_START and ARG_LIMIT parts. + * + * Messages nested inside an argument are each delimited by MSG_START and MSG_LIMIT, + * with a nesting level one greater than the surrounding message. + * @stable ICU 4.8 + */ +enum UMessagePatternArgType { + /** + * The argument has no specified type. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_TYPE_NONE, + /** + * The argument has a "simple" type which is provided by the ARG_TYPE part. + * An ARG_STYLE part might follow that. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_TYPE_SIMPLE, + /** + * The argument is a ChoiceFormat with one or more + * ((ARG_INT | ARG_DOUBLE), ARG_SELECTOR, message) tuples. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_TYPE_CHOICE, + /** + * The argument is a cardinal-number PluralFormat with an optional ARG_INT or ARG_DOUBLE offset + * (e.g., offset:1) + * and one or more (ARG_SELECTOR [explicit-value] message) tuples. + * If the selector has an explicit value (e.g., =2), then + * that value is provided by the ARG_INT or ARG_DOUBLE part preceding the message. + * Otherwise the message immediately follows the ARG_SELECTOR. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_TYPE_PLURAL, + /** + * The argument is a SelectFormat with one or more (ARG_SELECTOR, message) pairs. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_TYPE_SELECT, + /** + * The argument is an ordinal-number PluralFormat + * with the same style parts sequence and semantics as UMSGPAT_ARG_TYPE_PLURAL. + * @stable ICU 50 + */ + UMSGPAT_ARG_TYPE_SELECTORDINAL +}; +/** + * @stable ICU 4.8 + */ +typedef enum UMessagePatternArgType UMessagePatternArgType; + +/** + * \def UMSGPAT_ARG_TYPE_HAS_PLURAL_STYLE + * Returns true if the argument type has a plural style part sequence and semantics, + * for example UMSGPAT_ARG_TYPE_PLURAL and UMSGPAT_ARG_TYPE_SELECTORDINAL. + * @stable ICU 50 + */ +#define UMSGPAT_ARG_TYPE_HAS_PLURAL_STYLE(argType) \ + ((argType)==UMSGPAT_ARG_TYPE_PLURAL || (argType)==UMSGPAT_ARG_TYPE_SELECTORDINAL) + +enum { + /** + * Return value from MessagePattern.validateArgumentName() for when + * the string is a valid "pattern identifier" but not a number. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_NAME_NOT_NUMBER=-1, + + /** + * Return value from MessagePattern.validateArgumentName() for when + * the string is invalid. + * It might not be a valid "pattern identifier", + * or it have only ASCII digits but there is a leading zero or the number is too large. + * @stable ICU 4.8 + */ + UMSGPAT_ARG_NAME_NOT_VALID=-2 +}; + +/** + * Special value that is returned by getNumericValue(Part) when no + * numeric value is defined for a part. + * @see MessagePattern.getNumericValue() + * @stable ICU 4.8 + */ +#define UMSGPAT_NO_NUMERIC_VALUE ((double)(-123456789)) + +U_NAMESPACE_BEGIN + +class MessagePatternDoubleList; +class MessagePatternPartsList; + +/** + * Parses and represents ICU MessageFormat patterns. + * Also handles patterns for ChoiceFormat, PluralFormat and SelectFormat. + * Used in the implementations of those classes as well as in tools + * for message validation, translation and format conversion. + *

+ * The parser handles all syntax relevant for identifying message arguments. + * This includes "complex" arguments whose style strings contain + * nested MessageFormat pattern substrings. + * For "simple" arguments (with no nested MessageFormat pattern substrings), + * the argument style is not parsed any further. + *

+ * The parser handles named and numbered message arguments and allows both in one message. + *

+ * Once a pattern has been parsed successfully, iterate through the parsed data + * with countParts(), getPart() and related methods. + *

+ * The data logically represents a parse tree, but is stored and accessed + * as a list of "parts" for fast and simple parsing and to minimize object allocations. + * Arguments and nested messages are best handled via recursion. + * For every _START "part", MessagePattern.getLimitPartIndex() efficiently returns + * the index of the corresponding _LIMIT "part". + *

+ * List of "parts": + *

+ * message = MSG_START (SKIP_SYNTAX | INSERT_CHAR | REPLACE_NUMBER | argument)* MSG_LIMIT
+ * argument = noneArg | simpleArg | complexArg
+ * complexArg = choiceArg | pluralArg | selectArg
+ *
+ * noneArg = ARG_START.NONE (ARG_NAME | ARG_NUMBER) ARG_LIMIT.NONE
+ * simpleArg = ARG_START.SIMPLE (ARG_NAME | ARG_NUMBER) ARG_TYPE [ARG_STYLE] ARG_LIMIT.SIMPLE
+ * choiceArg = ARG_START.CHOICE (ARG_NAME | ARG_NUMBER) choiceStyle ARG_LIMIT.CHOICE
+ * pluralArg = ARG_START.PLURAL (ARG_NAME | ARG_NUMBER) pluralStyle ARG_LIMIT.PLURAL
+ * selectArg = ARG_START.SELECT (ARG_NAME | ARG_NUMBER) selectStyle ARG_LIMIT.SELECT
+ *
+ * choiceStyle = ((ARG_INT | ARG_DOUBLE) ARG_SELECTOR message)+
+ * pluralStyle = [ARG_INT | ARG_DOUBLE] (ARG_SELECTOR [ARG_INT | ARG_DOUBLE] message)+
+ * selectStyle = (ARG_SELECTOR message)+
+ * 
+ *
    + *
  • Literal output text is not represented directly by "parts" but accessed + * between parts of a message, from one part's getLimit() to the next part's getIndex(). + *
  • ARG_START.CHOICE stands for an ARG_START Part with ArgType CHOICE. + *
  • In the choiceStyle, the ARG_SELECTOR has the '<', the '#' or + * the less-than-or-equal-to sign (U+2264). + *
  • In the pluralStyle, the first, optional numeric Part has the "offset:" value. + * The optional numeric Part between each (ARG_SELECTOR, message) pair + * is the value of an explicit-number selector like "=2", + * otherwise the selector is a non-numeric identifier. + *
  • The REPLACE_NUMBER Part can occur only in an immediate sub-message of the pluralStyle. + *
+ *

+ * This class is not intended for public subclassing. + * + * @stable ICU 4.8 + */ +class U_COMMON_API MessagePattern : public UObject { +public: + /** + * Constructs an empty MessagePattern with default UMessagePatternApostropheMode. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + MessagePattern(UErrorCode &errorCode); + + /** + * Constructs an empty MessagePattern. + * @param mode Explicit UMessagePatternApostropheMode. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + MessagePattern(UMessagePatternApostropheMode mode, UErrorCode &errorCode); + + /** + * Constructs a MessagePattern with default UMessagePatternApostropheMode and + * parses the MessageFormat pattern string. + * @param pattern a MessageFormat pattern string + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * TODO: turn @throws into UErrorCode specifics? + * @throws IllegalArgumentException for syntax errors in the pattern string + * @throws IndexOutOfBoundsException if certain limits are exceeded + * (e.g., argument number too high, argument name too long, etc.) + * @throws NumberFormatException if a number could not be parsed + * @stable ICU 4.8 + */ + MessagePattern(const UnicodeString &pattern, UParseError *parseError, UErrorCode &errorCode); + + /** + * Copy constructor. + * @param other Object to copy. + * @stable ICU 4.8 + */ + MessagePattern(const MessagePattern &other); + + /** + * Assignment operator. + * @param other Object to copy. + * @return *this=other + * @stable ICU 4.8 + */ + MessagePattern &operator=(const MessagePattern &other); + + /** + * Destructor. + * @stable ICU 4.8 + */ + virtual ~MessagePattern(); + + /** + * Parses a MessageFormat pattern string. + * @param pattern a MessageFormat pattern string + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @throws IllegalArgumentException for syntax errors in the pattern string + * @throws IndexOutOfBoundsException if certain limits are exceeded + * (e.g., argument number too high, argument name too long, etc.) + * @throws NumberFormatException if a number could not be parsed + * @stable ICU 4.8 + */ + MessagePattern &parse(const UnicodeString &pattern, + UParseError *parseError, UErrorCode &errorCode); + + /** + * Parses a ChoiceFormat pattern string. + * @param pattern a ChoiceFormat pattern string + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @throws IllegalArgumentException for syntax errors in the pattern string + * @throws IndexOutOfBoundsException if certain limits are exceeded + * (e.g., argument number too high, argument name too long, etc.) + * @throws NumberFormatException if a number could not be parsed + * @stable ICU 4.8 + */ + MessagePattern &parseChoiceStyle(const UnicodeString &pattern, + UParseError *parseError, UErrorCode &errorCode); + + /** + * Parses a PluralFormat pattern string. + * @param pattern a PluralFormat pattern string + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @throws IllegalArgumentException for syntax errors in the pattern string + * @throws IndexOutOfBoundsException if certain limits are exceeded + * (e.g., argument number too high, argument name too long, etc.) + * @throws NumberFormatException if a number could not be parsed + * @stable ICU 4.8 + */ + MessagePattern &parsePluralStyle(const UnicodeString &pattern, + UParseError *parseError, UErrorCode &errorCode); + + /** + * Parses a SelectFormat pattern string. + * @param pattern a SelectFormat pattern string + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @throws IllegalArgumentException for syntax errors in the pattern string + * @throws IndexOutOfBoundsException if certain limits are exceeded + * (e.g., argument number too high, argument name too long, etc.) + * @throws NumberFormatException if a number could not be parsed + * @stable ICU 4.8 + */ + MessagePattern &parseSelectStyle(const UnicodeString &pattern, + UParseError *parseError, UErrorCode &errorCode); + + /** + * Clears this MessagePattern. + * countParts() will return 0. + * @stable ICU 4.8 + */ + void clear(); + + /** + * Clears this MessagePattern and sets the UMessagePatternApostropheMode. + * countParts() will return 0. + * @param mode The new UMessagePatternApostropheMode. + * @stable ICU 4.8 + */ + void clearPatternAndSetApostropheMode(UMessagePatternApostropheMode mode) { + clear(); + aposMode=mode; + } + + /** + * @param other another object to compare with. + * @return true if this object is equivalent to the other one. + * @stable ICU 4.8 + */ + bool operator==(const MessagePattern &other) const; + + /** + * @param other another object to compare with. + * @return false if this object is equivalent to the other one. + * @stable ICU 4.8 + */ + inline bool operator!=(const MessagePattern &other) const { + return !operator==(other); + } + + /** + * @return A hash code for this object. + * @stable ICU 4.8 + */ + int32_t hashCode() const; + + /** + * @return this instance's UMessagePatternApostropheMode. + * @stable ICU 4.8 + */ + UMessagePatternApostropheMode getApostropheMode() const { + return aposMode; + } + + // Java has package-private jdkAposMode() here. + // In C++, this is declared in the MessageImpl class. + + /** + * @return the parsed pattern string (null if none was parsed). + * @stable ICU 4.8 + */ + const UnicodeString &getPatternString() const { + return msg; + } + + /** + * Does the parsed pattern have named arguments like {first_name}? + * @return true if the parsed pattern has at least one named argument. + * @stable ICU 4.8 + */ + UBool hasNamedArguments() const { + return hasArgNames; + } + + /** + * Does the parsed pattern have numbered arguments like {2}? + * @return true if the parsed pattern has at least one numbered argument. + * @stable ICU 4.8 + */ + UBool hasNumberedArguments() const { + return hasArgNumbers; + } + + /** + * Validates and parses an argument name or argument number string. + * An argument name must be a "pattern identifier", that is, it must contain + * no Unicode Pattern_Syntax or Pattern_White_Space characters. + * If it only contains ASCII digits, then it must be a small integer with no leading zero. + * @param name Input string. + * @return >=0 if the name is a valid number, + * ARG_NAME_NOT_NUMBER (-1) if it is a "pattern identifier" but not all ASCII digits, + * ARG_NAME_NOT_VALID (-2) if it is neither. + * @stable ICU 4.8 + */ + static int32_t validateArgumentName(const UnicodeString &name); + + /** + * Returns a version of the parsed pattern string where each ASCII apostrophe + * is doubled (escaped) if it is not already, and if it is not interpreted as quoting syntax. + *

+ * For example, this turns "I don't '{know}' {gender,select,female{h''er}other{h'im}}." + * into "I don''t '{know}' {gender,select,female{h''er}other{h''im}}." + * @return the deep-auto-quoted version of the parsed pattern string. + * @see MessageFormat.autoQuoteApostrophe() + * @stable ICU 4.8 + */ + UnicodeString autoQuoteApostropheDeep() const; + + class Part; + + /** + * Returns the number of "parts" created by parsing the pattern string. + * Returns 0 if no pattern has been parsed or clear() was called. + * @return the number of pattern parts. + * @stable ICU 4.8 + */ + int32_t countParts() const { + return partsLength; + } + + /** + * Gets the i-th pattern "part". + * @param i The index of the Part data. (0..countParts()-1) + * @return the i-th pattern "part". + * @stable ICU 4.8 + */ + const Part &getPart(int32_t i) const { + return parts[i]; + } + + /** + * Returns the UMessagePatternPartType of the i-th pattern "part". + * Convenience method for getPart(i).getType(). + * @param i The index of the Part data. (0..countParts()-1) + * @return The UMessagePatternPartType of the i-th Part. + * @stable ICU 4.8 + */ + UMessagePatternPartType getPartType(int32_t i) const { + return getPart(i).type; + } + + /** + * Returns the pattern index of the specified pattern "part". + * Convenience method for getPart(partIndex).getIndex(). + * @param partIndex The index of the Part data. (0..countParts()-1) + * @return The pattern index of this Part. + * @stable ICU 4.8 + */ + int32_t getPatternIndex(int32_t partIndex) const { + return getPart(partIndex).index; + } + + /** + * Returns the substring of the pattern string indicated by the Part. + * Convenience method for getPatternString().substring(part.getIndex(), part.getLimit()). + * @param part a part of this MessagePattern. + * @return the substring associated with part. + * @stable ICU 4.8 + */ + UnicodeString getSubstring(const Part &part) const { + return msg.tempSubString(part.index, part.length); + } + + /** + * Compares the part's substring with the input string s. + * @param part a part of this MessagePattern. + * @param s a string. + * @return true if getSubstring(part).equals(s). + * @stable ICU 4.8 + */ + UBool partSubstringMatches(const Part &part, const UnicodeString &s) const { + return 0==msg.compare(part.index, part.length, s); + } + + /** + * Returns the numeric value associated with an ARG_INT or ARG_DOUBLE. + * @param part a part of this MessagePattern. + * @return the part's numeric value, or UMSGPAT_NO_NUMERIC_VALUE if this is not a numeric part. + * @stable ICU 4.8 + */ + double getNumericValue(const Part &part) const; + + /** + * Returns the "offset:" value of a PluralFormat argument, or 0 if none is specified. + * @param pluralStart the index of the first PluralFormat argument style part. (0..countParts()-1) + * @return the "offset:" value. + * @stable ICU 4.8 + */ + double getPluralOffset(int32_t pluralStart) const; + + /** + * Returns the index of the ARG|MSG_LIMIT part corresponding to the ARG|MSG_START at start. + * @param start The index of some Part data (0..countParts()-1); + * this Part should be of Type ARG_START or MSG_START. + * @return The first i>start where getPart(i).getType()==ARG|MSG_LIMIT at the same nesting level, + * or start itself if getPartType(msgStart)!=ARG|MSG_START. + * @stable ICU 4.8 + */ + int32_t getLimitPartIndex(int32_t start) const { + int32_t limit=getPart(start).limitPartIndex; + if(limit parts=new ArrayList(); + MessagePatternPartsList *partsList; + Part *parts; + int32_t partsLength; + // ArrayList numericValues; + MessagePatternDoubleList *numericValuesList; + double *numericValues; + int32_t numericValuesLength; + UBool hasArgNames; + UBool hasArgNumbers; + UBool needsAutoQuoting; +}; + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_FORMATTING + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __MESSAGEPATTERN_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/msgfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/msgfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..a8a61f90e3f6a970a40b330c33372de170e2ccde --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/msgfmt.h @@ -0,0 +1,1117 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +* Copyright (C) 2007-2013, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************** +* +* File MSGFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/20/97 helena Finished first cut of implementation. +* 07/22/98 stephen Removed operator!= (defined in Format) +* 08/19/2002 srl Removing Javaisms +*******************************************************************************/ + +#ifndef MSGFMT_H +#define MSGFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Formats messages in a language-neutral way. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/format.h" +#include "unicode/locid.h" +#include "unicode/messagepattern.h" +#include "unicode/parseerr.h" +#include "unicode/plurfmt.h" +#include "unicode/plurrule.h" + +U_CDECL_BEGIN +// Forward declaration. +struct UHashtable; +typedef struct UHashtable UHashtable; /**< @internal */ +U_CDECL_END + +U_NAMESPACE_BEGIN + +class AppendableWrapper; +class DateFormat; +class NumberFormat; + +/** + *

MessageFormat prepares strings for display to users, + * with optional arguments (variables/placeholders). + * The arguments can occur in any order, which is necessary for translation + * into languages with different grammars. + * + *

A MessageFormat is constructed from a pattern string + * with arguments in {curly braces} which will be replaced by formatted values. + * + *

MessageFormat differs from the other Format + * classes in that you create a MessageFormat object with one + * of its constructors (not with a createInstance style factory + * method). Factory methods aren't necessary because MessageFormat + * itself doesn't implement locale-specific behavior. Any locale-specific + * behavior is defined by the pattern that you provide and the + * subformats used for inserted arguments. + * + *

Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers). + * Some of the API methods work only with argument numbers and throw an exception + * if the pattern has named arguments (see {@link #usesNamedArguments()}). + * + *

An argument might not specify any format type. In this case, + * a numeric value is formatted with a default (for the locale) NumberFormat, + * and a date/time value is formatted with a default (for the locale) DateFormat. + * + *

An argument might specify a "simple" type for which the specified + * Format object is created, cached and used. + * + *

An argument might have a "complex" type with nested MessageFormat sub-patterns. + * During formatting, one of these sub-messages is selected according to the argument value + * and recursively formatted. + * + *

After construction, a custom Format object can be set for + * a top-level argument, overriding the default formatting and parsing behavior + * for that argument. + * However, custom formatting can be achieved more simply by writing + * a typeless argument in the pattern string + * and supplying it with a preformatted string value. + * + *

When formatting, MessageFormat takes a collection of argument values + * and writes an output string. + * The argument values may be passed as an array + * (when the pattern contains only numbered arguments) + * or as an array of names and and an array of arguments (which works for both named + * and numbered arguments). + * + *

Each argument is matched with one of the input values by array index or argument name + * and formatted according to its pattern specification + * (or using a custom Format object if one was set). + * A numbered pattern argument is matched with an argument name that contains that number + * as an ASCII-decimal-digit string (without leading zero). + * + *

Patterns and Their Interpretation

+ * + * MessageFormat uses patterns of the following form: + *
+ * message = messageText (argument messageText)*
+ * argument = noneArg | simpleArg | complexArg
+ * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
+ *
+ * noneArg = '{' argNameOrNumber '}'
+ * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
+ * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
+ * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
+ * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
+ * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
+ *
+ * choiceStyle: see {@link ChoiceFormat}
+ * pluralStyle: see {@link PluralFormat}
+ * selectStyle: see {@link SelectFormat}
+ *
+ * argNameOrNumber = argName | argNumber
+ * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
+ * argNumber = '0' | ('1'..'9' ('0'..'9')*)
+ *
+ * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
+ * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText | "::" argSkeletonText
+ * 
+ * + *
    + *
  • messageText can contain quoted literal strings including syntax characters. + * A quoted literal string begins with an ASCII apostrophe and a syntax character + * (usually a {curly brace}) and continues until the next single apostrophe. + * A double ASCII apostrophe inside or outside of a quoted string represents + * one literal apostrophe. + *
  • Quotable syntax characters are the {curly braces} in all messageText parts, + * plus the '#' sign in a messageText immediately inside a pluralStyle, + * and the '|' symbol in a messageText immediately inside a choiceStyle. + *
  • See also {@link #UMessagePatternApostropheMode} + *
  • In argStyleText, every single ASCII apostrophe begins and ends quoted literal text, + * and unquoted {curly braces} must occur in matched pairs. + *
+ * + *

Recommendation: Use the real apostrophe (single quote) character + * \htmlonly’\endhtmlonly (U+2019) for + * human-readable text, and use the ASCII apostrophe ' (U+0027) + * only in program syntax, like quoting in MessageFormat. + * See the annotations for U+0027 Apostrophe in The Unicode Standard. + * + *

The choice argument type is deprecated. + * Use plural arguments for proper plural selection, + * and select arguments for simple selection among a fixed set of choices. + * + *

The argType and argStyle values are used to create + * a Format instance for the format element. The following + * table shows how the values map to Format instances. Combinations not + * shown in the table are illegal. Any argStyleText must + * be a valid pattern string for the Format subclass used. + * + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
argType + * argStyle + * resulting Format object + *
(none) + * null + *
number + * (none) + * NumberFormat.createInstance(getLocale(), status) + *
integer + * NumberFormat.createInstance(getLocale(), kNumberStyle, status) + *
currency + * NumberFormat.createCurrencyInstance(getLocale(), status) + *
percent + * NumberFormat.createPercentInstance(getLocale(), status) + *
argStyleText + * new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status) + *
argSkeletonText + * NumberFormatter::forSkeleton(argSkeletonText, status).locale(getLocale()).toFormat(status) + *
date + * (none) + * DateFormat.createDateInstance(kDefault, getLocale(), status) + *
short + * DateFormat.createDateInstance(kShort, getLocale(), status) + *
medium + * DateFormat.createDateInstance(kDefault, getLocale(), status) + *
long + * DateFormat.createDateInstance(kLong, getLocale(), status) + *
full + * DateFormat.createDateInstance(kFull, getLocale(), status) + *
argStyleText + * new SimpleDateFormat(argStyleText, getLocale(), status) + *
argSkeletonText + * DateFormat::createInstanceForSkeleton(argSkeletonText, getLocale(), status) + *
time + * (none) + * DateFormat.createTimeInstance(kDefault, getLocale(), status) + *
short + * DateFormat.createTimeInstance(kShort, getLocale(), status) + *
medium + * DateFormat.createTimeInstance(kDefault, getLocale(), status) + *
long + * DateFormat.createTimeInstance(kLong, getLocale(), status) + *
full + * DateFormat.createTimeInstance(kFull, getLocale(), status) + *
argStyleText + * new SimpleDateFormat(argStyleText, getLocale(), status) + *
spellout + * argStyleText (optional) + * new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status) + *
    .setDefaultRuleset(argStyleText, status);
+ *
ordinal + * argStyleText (optional) + * new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status) + *
    .setDefaultRuleset(argStyleText, status);
+ *
duration + * argStyleText (optional) + * new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status) + *
    .setDefaultRuleset(argStyleText, status);
+ *
+ *

+ * + *

Argument formatting

+ * + *

Arguments are formatted according to their type, using the default + * ICU formatters for those types, unless otherwise specified.

+ * + *

There are also several ways to control the formatting.

+ * + *

We recommend you use default styles, predefined style values, skeletons, + * or preformatted values, but not pattern strings or custom format objects.

+ * + *

For more details, see the + * ICU User Guide.

+ * + *

Usage Information

+ * + *

Here are some examples of usage: + * Example 1: + * + *

+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     GregorianCalendar cal(success);
+ *     Formattable arguments[] = {
+ *         7L,
+ *         Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
+ *         "a disturbance in the Force"
+ *     };
+ *
+ *     UnicodeString result;
+ *     MessageFormat::format(
+ *          "At {1,time,::jmm} on {1,date,::dMMMM}, there was {2} on planet {0,number}.",
+ *          arguments, 3, result, success );
+ *
+ *     cout << "result: " << result << endl;
+ *     //: At 4:34 PM on March 23, there was a disturbance
+ *     //             in the Force on planet 7.
+ * \endcode
+ * 
+ * + * Typically, the message format will come from resources, and the + * arguments will be dynamically set at runtime. + * + *

Example 2: + * + *

+ *  \code
+ *     success = U_ZERO_ERROR;
+ *     Formattable testArgs[] = {3L, "MyDisk"};
+ *
+ *     MessageFormat form(
+ *         "The disk \"{1}\" contains {0} file(s).", success );
+ *
+ *     UnicodeString string;
+ *     FieldPosition fpos = 0;
+ *     cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
+ *
+ *     // output, with different testArgs:
+ *     // output: The disk "MyDisk" contains 0 file(s).
+ *     // output: The disk "MyDisk" contains 1 file(s).
+ *     // output: The disk "MyDisk" contains 1,273 file(s).
+ *  \endcode
+ *  
+ * + * + *

For messages that include plural forms, you can use a plural argument: + *

+ * \code
+ *  success = U_ZERO_ERROR;
+ *  MessageFormat msgFmt(
+ *       "{num_files, plural, "
+ *       "=0{There are no files on disk \"{disk_name}\".}"
+ *       "=1{There is one file on disk \"{disk_name}\".}"
+ *       "other{There are # files on disk \"{disk_name}\".}}",
+ *      Locale("en"),
+ *      success);
+ *  FieldPosition fpos = 0;
+ *  Formattable testArgs[] = {0L, "MyDisk"};
+ *  UnicodeString testArgsNames[] = {"num_files", "disk_name"};
+ *  UnicodeString result;
+ *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
+ *  testArgs[0] = 3L;
+ *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
+ * \endcode
+ * output:
+ * There are no files on disk "MyDisk".
+ * There are 3 files on "MyDisk".
+ * 
+ * See {@link PluralFormat} and {@link PluralRules} for details. + * + *

Synchronization

+ * + *

MessageFormats are not synchronized. + * It is recommended to create separate format instances for each thread. + * If multiple threads access a format concurrently, it must be synchronized + * externally. + * + * @stable ICU 2.0 + */ +class U_I18N_API MessageFormat : public Format { +public: +#ifndef U_HIDE_OBSOLETE_API + /** + * Enum type for kMaxFormat. + * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6, + * rendering this enum type obsolete. + */ + enum EFormatNumber { + /** + * The maximum number of arguments. + * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6, + * rendering this constant obsolete. + */ + kMaxFormat = 10 + }; +#endif /* U_HIDE_OBSOLETE_API */ + + /** + * Constructs a new MessageFormat using the given pattern and the + * default locale. + * + * @param pattern Pattern used to construct object. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 2.0 + */ + MessageFormat(const UnicodeString& pattern, + UErrorCode &status); + + /** + * Constructs a new MessageFormat using the given pattern and locale. + * @param pattern Pattern used to construct object. + * @param newLocale The locale to use for formatting dates and numbers. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 2.0 + */ + MessageFormat(const UnicodeString& pattern, + const Locale& newLocale, + UErrorCode& status); + /** + * Constructs a new MessageFormat using the given pattern and locale. + * @param pattern Pattern used to construct object. + * @param newLocale The locale to use for formatting dates and numbers. + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 2.0 + */ + MessageFormat(const UnicodeString& pattern, + const Locale& newLocale, + UParseError& parseError, + UErrorCode& status); + /** + * Constructs a new MessageFormat from an existing one. + * @stable ICU 2.0 + */ + MessageFormat(const MessageFormat&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + const MessageFormat& operator=(const MessageFormat&); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~MessageFormat(); + + /** + * Clones this Format object polymorphically. The caller owns the + * result and should delete it when done. + * @stable ICU 2.0 + */ + virtual MessageFormat* clone() const override; + + /** + * Returns true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.0 + */ + virtual bool operator==(const Format& other) const override; + + /** + * Sets the locale to be used for creating argument Format objects. + * @param theLocale the new locale value to be set. + * @stable ICU 2.0 + */ + virtual void setLocale(const Locale& theLocale); + + /** + * Gets the locale used for creating argument Format objects. + * format information. + * @return the locale of the object. + * @stable ICU 2.0 + */ + virtual const Locale& getLocale(void) const; + + /** + * Applies the given pattern string to this message format. + * + * @param pattern The pattern to be applied. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern, + UErrorCode& status); + /** + * Applies the given pattern string to this message format. + * + * @param pattern The pattern to be applied. + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern, + UParseError& parseError, + UErrorCode& status); + + /** + * Sets the UMessagePatternApostropheMode and the pattern used by this message format. + * Parses the pattern and caches Format objects for simple argument types. + * Patterns and their interpretation are specified in the + * class description. + *

+ * This method is best used only once on a given object to avoid confusion about the mode, + * and after constructing the object with an empty pattern string to minimize overhead. + * + * @param pattern The pattern to be applied. + * @param aposMode The new apostrophe mode. + * @param parseError Struct to receive information on the position + * of an error within the pattern. + * Can be nullptr. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @stable ICU 4.8 + */ + virtual void applyPattern(const UnicodeString& pattern, + UMessagePatternApostropheMode aposMode, + UParseError* parseError, + UErrorCode& status); + + /** + * @return this instance's UMessagePatternApostropheMode. + * @stable ICU 4.8 + */ + UMessagePatternApostropheMode getApostropheMode() const { + return msgPattern.getApostropheMode(); + } + + /** + * Returns a pattern that can be used to recreate this object. + * + * @param appendTo Output parameter to receive the pattern. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& toPattern(UnicodeString& appendTo) const; + + /** + * Sets subformats. + * See the class description about format numbering. + * The caller should not delete the Format objects after this call. + * The array formatsToAdopt is not itself adopted. Its + * ownership is retained by the caller. If the call fails because + * memory cannot be allocated, then the formats will be deleted + * by this method, and this object will remain unchanged. + * + *

If this format uses named arguments, the new formats are discarded + * and this format remains unchanged. + * + * @stable ICU 2.0 + * @param formatsToAdopt the format to be adopted. + * @param count the size of the array. + */ + virtual void adoptFormats(Format** formatsToAdopt, int32_t count); + + /** + * Sets subformats. + * See the class description about format numbering. + * Each item in the array is cloned into the internal array. + * If the call fails because memory cannot be allocated, then this + * object will remain unchanged. + * + *

If this format uses named arguments, the new formats are discarded + * and this format remains unchanged. + * + * @stable ICU 2.0 + * @param newFormats the new format to be set. + * @param cnt the size of the array. + */ + virtual void setFormats(const Format** newFormats, int32_t cnt); + + + /** + * Sets one subformat. + * See the class description about format numbering. + * The caller should not delete the Format object after this call. + * If the number is over the number of formats already set, + * the item will be deleted and ignored. + * + *

If this format uses named arguments, the new format is discarded + * and this format remains unchanged. + * + * @stable ICU 2.0 + * @param formatNumber index of the subformat. + * @param formatToAdopt the format to be adopted. + */ + virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt); + + /** + * Sets one subformat. + * See the class description about format numbering. + * If the number is over the number of formats already set, + * the item will be ignored. + * @param formatNumber index of the subformat. + * @param format the format to be set. + * @stable ICU 2.0 + */ + virtual void setFormat(int32_t formatNumber, const Format& format); + + /** + * Gets format names. This function returns formatNames in StringEnumerations + * which can be used with getFormat() and setFormat() to export formattable + * array from current MessageFormat to another. It is the caller's responsibility + * to delete the returned formatNames. + * @param status output param set to success/failure code. + * @stable ICU 4.0 + */ + virtual StringEnumeration* getFormatNames(UErrorCode& status); + + /** + * Gets subformat pointer for given format name. + * This function supports both named and numbered + * arguments. If numbered, the formatName is the + * corresponding UnicodeStrings (e.g. "0", "1", "2"...). + * The returned Format object should not be deleted by the caller, + * nor should the pointer of other object . The pointer and its + * contents remain valid only until the next call to any method + * of this class is made with this object. + * @param formatName the name or number specifying a format + * @param status output param set to success/failure code. + * @stable ICU 4.0 + */ + virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status); + + /** + * Sets one subformat for given format name. + * See the class description about format name. + * This function supports both named and numbered + * arguments-- if numbered, the formatName is the + * corresponding UnicodeStrings (e.g. "0", "1", "2"...). + * If there is no matched formatName or wrong type, + * the item will be ignored. + * @param formatName Name of the subformat. + * @param format the format to be set. + * @param status output param set to success/failure code. + * @stable ICU 4.0 + */ + virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status); + + /** + * Sets one subformat for given format name. + * See the class description about format name. + * This function supports both named and numbered + * arguments-- if numbered, the formatName is the + * corresponding UnicodeStrings (e.g. "0", "1", "2"...). + * If there is no matched formatName or wrong type, + * the item will be ignored. + * The caller should not delete the Format object after this call. + * @param formatName Name of the subformat. + * @param formatToAdopt Format to be adopted. + * @param status output param set to success/failure code. + * @stable ICU 4.0 + */ + virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status); + + /** + * Gets an array of subformats of this object. The returned array + * should not be deleted by the caller, nor should the pointers + * within the array. The array and its contents remain valid only + * until the next call to this format. See the class description + * about format numbering. + * + * @param count output parameter to receive the size of the array + * @return an array of count Format* objects, or nullptr if out of + * memory. Any or all of the array elements may be nullptr. + * @stable ICU 2.0 + */ + virtual const Format** getFormats(int32_t& count) const; + + + using Format::format; + + /** + * Formats the given array of arguments into a user-readable string. + * Does not take ownership of the Formattable* array or its contents. + * + *

If this format uses named arguments, appendTo is unchanged and + * status is set to U_ILLEGAL_ARGUMENT_ERROR. + * + * @param source An array of objects to be formatted. + * @param count The number of elements of 'source'. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param ignore Not used; inherited from base class API. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format(const Formattable* source, + int32_t count, + UnicodeString& appendTo, + FieldPosition& ignore, + UErrorCode& status) const; + + /** + * Formats the given array of arguments into a user-readable string + * using the given pattern. + * + *

If this format uses named arguments, appendTo is unchanged and + * status is set to U_ILLEGAL_ARGUMENT_ERROR. + * + * @param pattern The pattern. + * @param arguments An array of objects to be formatted. + * @param count The number of elements of 'source'. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + static UnicodeString& format(const UnicodeString& pattern, + const Formattable* arguments, + int32_t count, + UnicodeString& appendTo, + UErrorCode& status); + + /** + * Formats the given array of arguments into a user-readable + * string. The array must be stored within a single Formattable + * object of type kArray. If the Formattable object type is not of + * type kArray, then returns a failing UErrorCode. + * + *

If this format uses named arguments, appendTo is unchanged and + * status is set to U_ILLEGAL_ARGUMENT_ERROR. + * + * @param obj A Formattable of type kArray containing + * arguments to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; + + /** + * Formats the given array of arguments into a user-defined argument name + * array. This function supports both named and numbered + * arguments-- if numbered, the formatName is the + * corresponding UnicodeStrings (e.g. "0", "1", "2"...). + * + * @param argumentNames argument name array + * @param arguments An array of objects to be formatted. + * @param count The number of elements of 'argumentNames' and + * arguments. The number of argumentNames and arguments + * must be the same. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.0 + */ + UnicodeString& format(const UnicodeString* argumentNames, + const Formattable* arguments, + int32_t count, + UnicodeString& appendTo, + UErrorCode& status) const; + /** + * Parses the given string into an array of output arguments. + * + * @param source String to be parsed. + * @param pos On input, starting position for parse. On output, + * final position after parse. Unchanged if parse + * fails. + * @param count Output parameter to receive the number of arguments + * parsed. + * @return an array of parsed arguments. The caller owns both + * the array and its contents. + * @stable ICU 2.0 + */ + virtual Formattable* parse(const UnicodeString& source, + ParsePosition& pos, + int32_t& count) const; + + /** + * Parses the given string into an array of output arguments. + * + *

If this format uses named arguments, status is set to + * U_ARGUMENT_TYPE_MISMATCH. + * + * @param source String to be parsed. + * @param count Output param to receive size of returned array. + * @param status Input/output error code. If the + * pattern cannot be parsed, set to failure code. + * @return an array of parsed arguments. The caller owns both + * the array and its contents. Returns nullptr if status is not U_ZERO_ERROR. + * + * @stable ICU 2.0 + */ + virtual Formattable* parse(const UnicodeString& source, + int32_t& count, + UErrorCode& status) const; + + /** + * Parses the given string into an array of output arguments + * stored within a single Formattable of type kArray. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param pos On input, starting position for parse. On output, + * final position after parse. Unchanged if parse + * fails. + * @stable ICU 2.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& pos) const override; + + /** + * Convert an 'apostrophe-friendly' pattern into a standard + * pattern. Standard patterns treat all apostrophes as + * quotes, which is problematic in some languages, e.g. + * French, where apostrophe is commonly used. This utility + * assumes that only an unpaired apostrophe immediately before + * a brace is a true quote. Other unpaired apostrophes are paired, + * and the resulting standard pattern string is returned. + * + *

Note it is not guaranteed that the returned pattern + * is indeed a valid pattern. The only effect is to convert + * between patterns having different quoting semantics. + * + * @param pattern the 'apostrophe-friendly' patttern to convert + * @param status Input/output error code. If the pattern + * cannot be parsed, the failure code is set. + * @return the standard equivalent of the original pattern + * @stable ICU 3.4 + */ + static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern, + UErrorCode& status); + + + /** + * Returns true if this MessageFormat uses named arguments, + * and false otherwise. See class description. + * + * @return true if named arguments are used. + * @stable ICU 4.0 + */ + UBool usesNamedArguments() const; + + +#ifndef U_HIDE_INTERNAL_API + /** + * This API is for ICU internal use only. + * Please do not use it. + * + * Returns argument types count in the parsed pattern. + * Used to distinguish pattern "{0} d" and "d". + * + * @return The number of formattable types in the pattern + * @internal + */ + int32_t getArgTypeCount() const; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. + * This method is to implement a simple version of RTTI, since not all + * C++ compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .      Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +#ifndef U_HIDE_INTERNAL_API + /** + * Compares two Format objects. This is used for constructing the hash + * tables. + * + * @param left pointer to a Format object. Must not be nullptr. + * @param right pointer to a Format object. Must not be nullptr. + * + * @return whether the two objects are the same + * @internal + */ + static UBool equalFormats(const void* left, const void* right); +#endif /* U_HIDE_INTERNAL_API */ + +private: + + Locale fLocale; + MessagePattern msgPattern; + Format** formatAliases; // see getFormats + int32_t formatAliasesCapacity; + + MessageFormat() = delete; // default constructor not implemented + + /** + * This provider helps defer instantiation of a PluralRules object + * until we actually need to select a keyword. + * For example, if the number matches an explicit-value selector like "=1" + * we do not need any PluralRules. + */ + class U_I18N_API PluralSelectorProvider : public PluralFormat::PluralSelector { + public: + PluralSelectorProvider(const MessageFormat &mf, UPluralType type); + virtual ~PluralSelectorProvider(); + virtual UnicodeString select(void *ctx, double number, UErrorCode& ec) const override; + + void reset(); + private: + const MessageFormat &msgFormat; + PluralRules* rules; + UPluralType type; + }; + + /** + * A MessageFormat formats an array of arguments. Each argument + * has an expected type, based on the pattern. For example, if + * the pattern contains the subformat "{3,number,integer}", then + * we expect argument 3 to have type Formattable::kLong. This + * array needs to grow dynamically if the MessageFormat is + * modified. + */ + Formattable::Type* argTypes; + int32_t argTypeCount; + int32_t argTypeCapacity; + + /** + * true if there are different argTypes for the same argument. + * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API + * where the pattern argTypes determine how the va_arg list is read. + */ + UBool hasArgTypeConflicts; + + // Variable-size array management + UBool allocateArgTypes(int32_t capacity, UErrorCode& status); + + /** + * Default Format objects used when no format is specified and a + * numeric or date argument is formatted. These are volatile + * cache objects maintained only for performance. They do not + * participate in operator=(), copy constructor(), nor + * operator==(). + */ + NumberFormat* defaultNumberFormat; + DateFormat* defaultDateFormat; + + UHashtable* cachedFormatters; + UHashtable* customFormatArgStarts; + + PluralSelectorProvider pluralProvider; + PluralSelectorProvider ordinalProvider; + + /** + * Method to retrieve default formats (or nullptr on failure). + * These are semantically const, but may modify *this. + */ + const NumberFormat* getDefaultNumberFormat(UErrorCode&) const; + const DateFormat* getDefaultDateFormat(UErrorCode&) const; + + /** + * Finds the word s, in the keyword list and returns the located index. + * @param s the keyword to be searched for. + * @param list the list of keywords to be searched with. + * @return the index of the list which matches the keyword s. + */ + static int32_t findKeyword( const UnicodeString& s, + const char16_t * const *list); + + /** + * Thin wrapper around the format(... AppendableWrapper ...) variant. + * Wraps the destination UnicodeString into an AppendableWrapper and + * supplies default values for some other parameters. + */ + UnicodeString& format(const Formattable* arguments, + const UnicodeString *argumentNames, + int32_t cnt, + UnicodeString& appendTo, + FieldPosition* pos, + UErrorCode& status) const; + + /** + * Formats the arguments and writes the result into the + * AppendableWrapper, updates the field position. + * + * @param msgStart Index to msgPattern part to start formatting from. + * @param plNumber nullptr except when formatting a plural argument sub-message + * where a '#' is replaced by the format string for this number. + * @param arguments The formattable objects array. (Must not be nullptr.) + * @param argumentNames nullptr if numbered values are used. Otherwise the same + * length as "arguments", and each entry is the name of the + * corresponding argument in "arguments". + * @param cnt The length of arguments (and of argumentNames if that is not nullptr). + * @param appendTo Output parameter to receive the result. + * The result string is appended to existing contents. + * @param pos Field position status. + * @param success The error code status. + */ + void format(int32_t msgStart, + const void *plNumber, + const Formattable* arguments, + const UnicodeString *argumentNames, + int32_t cnt, + AppendableWrapper& appendTo, + FieldPosition* pos, + UErrorCode& success) const; + + UnicodeString getArgName(int32_t partIndex); + + void setArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status); + + void setCustomArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status); + + int32_t nextTopLevelArgStart(int32_t partIndex) const; + + UBool argNameMatches(int32_t partIndex, const UnicodeString& argName, int32_t argNumber); + + void cacheExplicitFormats(UErrorCode& status); + + Format* createAppropriateFormat(UnicodeString& type, + UnicodeString& style, + Formattable::Type& formattableType, + UParseError& parseError, + UErrorCode& ec); + + const Formattable* getArgFromListByName(const Formattable* arguments, + const UnicodeString *argumentNames, + int32_t cnt, UnicodeString& name) const; + + Formattable* parse(int32_t msgStart, + const UnicodeString& source, + ParsePosition& pos, + int32_t& count, + UErrorCode& ec) const; + + FieldPosition* updateMetaData(AppendableWrapper& dest, int32_t prevLength, + FieldPosition* fp, const Formattable* argId) const; + + /** + * Finds the "other" sub-message. + * @param partIndex the index of the first PluralFormat argument style part. + * @return the "other" sub-message start part index. + */ + int32_t findOtherSubMessage(int32_t partIndex) const; + + /** + * Returns the ARG_START index of the first occurrence of the plural number in a sub-message. + * Returns -1 if it is a REPLACE_NUMBER. + * Returns 0 if there is neither. + */ + int32_t findFirstPluralNumberArg(int32_t msgStart, const UnicodeString &argName) const; + + Format* getCachedFormatter(int32_t argumentNumber) const; + + UnicodeString getLiteralStringUntilNextArgument(int32_t from) const; + + void copyObjects(const MessageFormat& that, UErrorCode& ec); + + void formatComplexSubMessage(int32_t msgStart, + const void *plNumber, + const Formattable* arguments, + const UnicodeString *argumentNames, + int32_t cnt, + AppendableWrapper& appendTo, + UErrorCode& success) const; + + /** + * Convenience method that ought to be in NumberFormat + */ + NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const; + + /** + * Returns array of argument types in the parsed pattern + * for use in C API. Only for the use of umsg_vformat(). Not + * for public consumption. + * @param listCount Output parameter to receive the size of array + * @return The array of formattable types in the pattern + */ + const Formattable::Type* getArgTypeList(int32_t& listCount) const { + listCount = argTypeCount; + return argTypes; + } + + /** + * Resets the internal MessagePattern, and other associated caches. + */ + void resetPattern(); + + /** + * A DummyFormatter that we use solely to store a nullptr value. UHash does + * not support storing nullptr values. + */ + class U_I18N_API DummyFormat : public Format { + public: + virtual bool operator==(const Format&) const override; + virtual DummyFormat* clone() const override; + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + UErrorCode& status) const; + virtual UnicodeString& format(const Formattable&, + UnicodeString& appendTo, + FieldPosition&, + UErrorCode& status) const override; + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const override; + virtual void parseObject(const UnicodeString&, + Formattable&, + ParsePosition&) const override; + }; + + friend class MessageFormatAdapter; // getFormatTypeList() access +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _MSGFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normalizer2.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normalizer2.h new file mode 100644 index 0000000000000000000000000000000000000000..972894ec42a4440ac37869a6ad22a35735ab3673 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normalizer2.h @@ -0,0 +1,771 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2009-2013, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: normalizer2.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2009nov22 +* created by: Markus W. Scherer +*/ + +#ifndef __NORMALIZER2_H__ +#define __NORMALIZER2_H__ + +/** + * \file + * \brief C++ API: New API for Unicode Normalization. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_NORMALIZATION + +#include "unicode/stringpiece.h" +#include "unicode/uniset.h" +#include "unicode/unistr.h" +#include "unicode/unorm2.h" + +U_NAMESPACE_BEGIN + +class ByteSink; + +/** + * Unicode normalization functionality for standard Unicode normalization or + * for using custom mapping tables. + * All instances of this class are unmodifiable/immutable. + * Instances returned by getInstance() are singletons that must not be deleted by the caller. + * The Normalizer2 class is not intended for public subclassing. + * + * The primary functions are to produce a normalized string and to detect whether + * a string is already normalized. + * The most commonly used normalization forms are those defined in + * http://www.unicode.org/unicode/reports/tr15/ + * However, this API supports additional normalization forms for specialized purposes. + * For example, NFKC_Casefold is provided via getInstance("nfkc_cf", COMPOSE) + * and can be used in implementations of UTS #46. + * + * Not only are the standard compose and decompose modes supplied, + * but additional modes are provided as documented in the Mode enum. + * + * Some of the functions in this class identify normalization boundaries. + * At a normalization boundary, the portions of the string + * before it and starting from it do not interact and can be handled independently. + * + * The spanQuickCheckYes() stops at a normalization boundary. + * When the goal is a normalized string, then the text before the boundary + * can be copied, and the remainder can be processed with normalizeSecondAndAppend(). + * + * The hasBoundaryBefore(), hasBoundaryAfter() and isInert() functions test whether + * a character is guaranteed to be at a normalization boundary, + * regardless of context. + * This is used for moving from one normalization boundary to the next + * or preceding boundary, and for performing iterative normalization. + * + * Iterative normalization is useful when only a small portion of a + * longer string needs to be processed. + * For example, in ICU, iterative normalization is used by the NormalizationTransliterator + * (to avoid replacing already-normalized text) and ucol_nextSortKeyPart() + * (to process only the substring for which sort key bytes are computed). + * + * The set of normalization boundaries returned by these functions may not be + * complete: There may be more boundaries that could be returned. + * Different functions may return different boundaries. + * @stable ICU 4.4 + */ +class U_COMMON_API Normalizer2 : public UObject { +public: + /** + * Destructor. + * @stable ICU 4.4 + */ + ~Normalizer2(); + + /** + * Returns a Normalizer2 instance for Unicode NFC normalization. + * Same as getInstance(nullptr, "nfc", UNORM2_COMPOSE, errorCode). + * Returns an unmodifiable singleton instance. Do not delete it. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 49 + */ + static const Normalizer2 * + getNFCInstance(UErrorCode &errorCode); + + /** + * Returns a Normalizer2 instance for Unicode NFD normalization. + * Same as getInstance(nullptr, "nfc", UNORM2_DECOMPOSE, errorCode). + * Returns an unmodifiable singleton instance. Do not delete it. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 49 + */ + static const Normalizer2 * + getNFDInstance(UErrorCode &errorCode); + + /** + * Returns a Normalizer2 instance for Unicode NFKC normalization. + * Same as getInstance(nullptr, "nfkc", UNORM2_COMPOSE, errorCode). + * Returns an unmodifiable singleton instance. Do not delete it. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 49 + */ + static const Normalizer2 * + getNFKCInstance(UErrorCode &errorCode); + + /** + * Returns a Normalizer2 instance for Unicode NFKD normalization. + * Same as getInstance(nullptr, "nfkc", UNORM2_DECOMPOSE, errorCode). + * Returns an unmodifiable singleton instance. Do not delete it. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 49 + */ + static const Normalizer2 * + getNFKDInstance(UErrorCode &errorCode); + + /** + * Returns a Normalizer2 instance for Unicode NFKC_Casefold normalization. + * Same as getInstance(nullptr, "nfkc_cf", UNORM2_COMPOSE, errorCode). + * Returns an unmodifiable singleton instance. Do not delete it. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 49 + */ + static const Normalizer2 * + getNFKCCasefoldInstance(UErrorCode &errorCode); + + /** + * Returns a Normalizer2 instance which uses the specified data file + * (packageName/name similar to ucnv_openPackage() and ures_open()/ResourceBundle) + * and which composes or decomposes text according to the specified mode. + * Returns an unmodifiable singleton instance. Do not delete it. + * + * Use packageName=nullptr for data files that are part of ICU's own data. + * Use name="nfc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFC/NFD. + * Use name="nfkc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFKC/NFKD. + * Use name="nfkc_cf" and UNORM2_COMPOSE for Unicode standard NFKC_CF=NFKC_Casefold. + * + * @param packageName nullptr for ICU built-in data, otherwise application data package name + * @param name "nfc" or "nfkc" or "nfkc_cf" or name of custom data file + * @param mode normalization mode (compose or decompose etc.) + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the requested Normalizer2, if successful + * @stable ICU 4.4 + */ + static const Normalizer2 * + getInstance(const char *packageName, + const char *name, + UNormalization2Mode mode, + UErrorCode &errorCode); + + /** + * Returns the normalized form of the source string. + * @param src source string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return normalized src + * @stable ICU 4.4 + */ + UnicodeString + normalize(const UnicodeString &src, UErrorCode &errorCode) const { + UnicodeString result; + normalize(src, result, errorCode); + return result; + } + /** + * Writes the normalized form of the source string to the destination string + * (replacing its contents) and returns the destination string. + * The source and destination strings must be different objects. + * @param src source string + * @param dest destination string; its contents is replaced with normalized src + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.4 + */ + virtual UnicodeString & + normalize(const UnicodeString &src, + UnicodeString &dest, + UErrorCode &errorCode) const = 0; + + /** + * Normalizes a UTF-8 string and optionally records how source substrings + * relate to changed and unchanged result substrings. + * + * Implemented completely for all built-in modes except for FCD. + * The base class implementation converts to & from UTF-16 and does not support edits. + * + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src Source UTF-8 string. + * @param sink A ByteSink to which the normalized UTF-8 result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 60 + */ + virtual void + normalizeUTF8(uint32_t options, StringPiece src, ByteSink &sink, + Edits *edits, UErrorCode &errorCode) const; + + /** + * Appends the normalized form of the second string to the first string + * (merging them at the boundary) and returns the first string. + * The result is normalized if the first string was normalized. + * The first and second strings must be different objects. + * @param first string, should be normalized + * @param second string, will be normalized + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return first + * @stable ICU 4.4 + */ + virtual UnicodeString & + normalizeSecondAndAppend(UnicodeString &first, + const UnicodeString &second, + UErrorCode &errorCode) const = 0; + /** + * Appends the second string to the first string + * (merging them at the boundary) and returns the first string. + * The result is normalized if both the strings were normalized. + * The first and second strings must be different objects. + * @param first string, should be normalized + * @param second string, should be normalized + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return first + * @stable ICU 4.4 + */ + virtual UnicodeString & + append(UnicodeString &first, + const UnicodeString &second, + UErrorCode &errorCode) const = 0; + + /** + * Gets the decomposition mapping of c. + * Roughly equivalent to normalizing the String form of c + * on a UNORM2_DECOMPOSE Normalizer2 instance, but much faster, and except that this function + * returns false and does not write a string + * if c does not have a decomposition mapping in this instance's data. + * This function is independent of the mode of the Normalizer2. + * @param c code point + * @param decomposition String object which will be set to c's + * decomposition mapping, if there is one. + * @return true if c has a decomposition, otherwise false + * @stable ICU 4.6 + */ + virtual UBool + getDecomposition(UChar32 c, UnicodeString &decomposition) const = 0; + + /** + * Gets the raw decomposition mapping of c. + * + * This is similar to the getDecomposition() method but returns the + * raw decomposition mapping as specified in UnicodeData.txt or + * (for custom data) in the mapping files processed by the gennorm2 tool. + * By contrast, getDecomposition() returns the processed, + * recursively-decomposed version of this mapping. + * + * When used on a standard NFKC Normalizer2 instance, + * getRawDecomposition() returns the Unicode Decomposition_Mapping (dm) property. + * + * When used on a standard NFC Normalizer2 instance, + * it returns the Decomposition_Mapping only if the Decomposition_Type (dt) is Canonical (Can); + * in this case, the result contains either one or two code points (=1..4 char16_ts). + * + * This function is independent of the mode of the Normalizer2. + * The default implementation returns false. + * @param c code point + * @param decomposition String object which will be set to c's + * raw decomposition mapping, if there is one. + * @return true if c has a decomposition, otherwise false + * @stable ICU 49 + */ + virtual UBool + getRawDecomposition(UChar32 c, UnicodeString &decomposition) const; + + /** + * Performs pairwise composition of a & b and returns the composite if there is one. + * + * Returns a composite code point c only if c has a two-way mapping to a+b. + * In standard Unicode normalization, this means that + * c has a canonical decomposition to a+b + * and c does not have the Full_Composition_Exclusion property. + * + * This function is independent of the mode of the Normalizer2. + * The default implementation returns a negative value. + * @param a A (normalization starter) code point. + * @param b Another code point. + * @return The non-negative composite code point if there is one; otherwise a negative value. + * @stable ICU 49 + */ + virtual UChar32 + composePair(UChar32 a, UChar32 b) const; + + /** + * Gets the combining class of c. + * The default implementation returns 0 + * but all standard implementations return the Unicode Canonical_Combining_Class value. + * @param c code point + * @return c's combining class + * @stable ICU 49 + */ + virtual uint8_t + getCombiningClass(UChar32 c) const; + + /** + * Tests if the string is normalized. + * Internally, in cases where the quickCheck() method would return "maybe" + * (which is only possible for the two COMPOSE modes) this method + * resolves to "yes" or "no" to provide a definitive result, + * at the cost of doing more work in those cases. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if s is normalized + * @stable ICU 4.4 + */ + virtual UBool + isNormalized(const UnicodeString &s, UErrorCode &errorCode) const = 0; + /** + * Tests if the UTF-8 string is normalized. + * Internally, in cases where the quickCheck() method would return "maybe" + * (which is only possible for the two COMPOSE modes) this method + * resolves to "yes" or "no" to provide a definitive result, + * at the cost of doing more work in those cases. + * + * This works for all normalization modes. + * It is optimized for UTF-8 for all built-in modes except for FCD. + * The base class implementation converts to UTF-16 and calls isNormalized(). + * + * @param s UTF-8 input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if s is normalized + * @stable ICU 60 + */ + virtual UBool + isNormalizedUTF8(StringPiece s, UErrorCode &errorCode) const; + + + /** + * Tests if the string is normalized. + * For the two COMPOSE modes, the result could be "maybe" in cases that + * would take a little more work to resolve definitively. + * Use spanQuickCheckYes() and normalizeSecondAndAppend() for a faster + * combination of quick check + normalization, to avoid + * re-checking the "yes" prefix. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return UNormalizationCheckResult + * @stable ICU 4.4 + */ + virtual UNormalizationCheckResult + quickCheck(const UnicodeString &s, UErrorCode &errorCode) const = 0; + + /** + * Returns the end of the normalized substring of the input string. + * In other words, with end=spanQuickCheckYes(s, ec); + * the substring UnicodeString(s, 0, end) + * will pass the quick check with a "yes" result. + * + * The returned end index is usually one or more characters before the + * "no" or "maybe" character: The end index is at a normalization boundary. + * (See the class documentation for more about normalization boundaries.) + * + * When the goal is a normalized string and most input strings are expected + * to be normalized already, then call this method, + * and if it returns a prefix shorter than the input string, + * copy that prefix and use normalizeSecondAndAppend() for the remainder. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return "yes" span end index + * @stable ICU 4.4 + */ + virtual int32_t + spanQuickCheckYes(const UnicodeString &s, UErrorCode &errorCode) const = 0; + + /** + * Tests if the character always has a normalization boundary before it, + * regardless of context. + * If true, then the character does not normalization-interact with + * preceding characters. + * In other words, a string containing this character can be normalized + * by processing portions before this character and starting from this + * character independently. + * This is used for iterative normalization. See the class documentation for details. + * @param c character to test + * @return true if c has a normalization boundary before it + * @stable ICU 4.4 + */ + virtual UBool hasBoundaryBefore(UChar32 c) const = 0; + + /** + * Tests if the character always has a normalization boundary after it, + * regardless of context. + * If true, then the character does not normalization-interact with + * following characters. + * In other words, a string containing this character can be normalized + * by processing portions up to this character and after this + * character independently. + * This is used for iterative normalization. See the class documentation for details. + * Note that this operation may be significantly slower than hasBoundaryBefore(). + * @param c character to test + * @return true if c has a normalization boundary after it + * @stable ICU 4.4 + */ + virtual UBool hasBoundaryAfter(UChar32 c) const = 0; + + /** + * Tests if the character is normalization-inert. + * If true, then the character does not change, nor normalization-interact with + * preceding or following characters. + * In other words, a string containing this character can be normalized + * by processing portions before this character and after this + * character independently. + * This is used for iterative normalization. See the class documentation for details. + * Note that this operation may be significantly slower than hasBoundaryBefore(). + * @param c character to test + * @return true if c is normalization-inert + * @stable ICU 4.4 + */ + virtual UBool isInert(UChar32 c) const = 0; +}; + +/** + * Normalization filtered by a UnicodeSet. + * Normalizes portions of the text contained in the filter set and leaves + * portions not contained in the filter set unchanged. + * Filtering is done via UnicodeSet::span(..., USET_SPAN_SIMPLE). + * Not-in-the-filter text is treated as "is normalized" and "quick check yes". + * This class implements all of (and only) the Normalizer2 API. + * An instance of this class is unmodifiable/immutable but is constructed and + * must be destructed by the owner. + * @stable ICU 4.4 + */ +class U_COMMON_API FilteredNormalizer2 : public Normalizer2 { +public: + /** + * Constructs a filtered normalizer wrapping any Normalizer2 instance + * and a filter set. + * Both are aliased and must not be modified or deleted while this object + * is used. + * The filter set should be frozen; otherwise the performance will suffer greatly. + * @param n2 wrapped Normalizer2 instance + * @param filterSet UnicodeSet which determines the characters to be normalized + * @stable ICU 4.4 + */ + FilteredNormalizer2(const Normalizer2 &n2, const UnicodeSet &filterSet) : + norm2(n2), set(filterSet) {} + + /** + * Destructor. + * @stable ICU 4.4 + */ + ~FilteredNormalizer2(); + + /** + * Writes the normalized form of the source string to the destination string + * (replacing its contents) and returns the destination string. + * The source and destination strings must be different objects. + * @param src source string + * @param dest destination string; its contents is replaced with normalized src + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return dest + * @stable ICU 4.4 + */ + virtual UnicodeString & + normalize(const UnicodeString &src, + UnicodeString &dest, + UErrorCode &errorCode) const override; + + /** + * Normalizes a UTF-8 string and optionally records how source substrings + * relate to changed and unchanged result substrings. + * + * Implemented completely for most built-in modes except for FCD. + * The base class implementation converts to & from UTF-16 and does not support edits. + * + * @param options Options bit set, usually 0. See U_OMIT_UNCHANGED_TEXT and U_EDITS_NO_RESET. + * @param src Source UTF-8 string. + * @param sink A ByteSink to which the normalized UTF-8 result string is written. + * sink.Flush() is called at the end. + * @param edits Records edits for index mapping, working with styled text, + * and getting only changes (if any). + * The Edits contents is undefined if any error occurs. + * This function calls edits->reset() first unless + * options includes U_EDITS_NO_RESET. edits can be nullptr. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 60 + */ + virtual void + normalizeUTF8(uint32_t options, StringPiece src, ByteSink &sink, + Edits *edits, UErrorCode &errorCode) const override; + + /** + * Appends the normalized form of the second string to the first string + * (merging them at the boundary) and returns the first string. + * The result is normalized if the first string was normalized. + * The first and second strings must be different objects. + * @param first string, should be normalized + * @param second string, will be normalized + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return first + * @stable ICU 4.4 + */ + virtual UnicodeString & + normalizeSecondAndAppend(UnicodeString &first, + const UnicodeString &second, + UErrorCode &errorCode) const override; + /** + * Appends the second string to the first string + * (merging them at the boundary) and returns the first string. + * The result is normalized if both the strings were normalized. + * The first and second strings must be different objects. + * @param first string, should be normalized + * @param second string, should be normalized + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return first + * @stable ICU 4.4 + */ + virtual UnicodeString & + append(UnicodeString &first, + const UnicodeString &second, + UErrorCode &errorCode) const override; + + /** + * Gets the decomposition mapping of c. + * For details see the base class documentation. + * + * This function is independent of the mode of the Normalizer2. + * @param c code point + * @param decomposition String object which will be set to c's + * decomposition mapping, if there is one. + * @return true if c has a decomposition, otherwise false + * @stable ICU 4.6 + */ + virtual UBool + getDecomposition(UChar32 c, UnicodeString &decomposition) const override; + + /** + * Gets the raw decomposition mapping of c. + * For details see the base class documentation. + * + * This function is independent of the mode of the Normalizer2. + * @param c code point + * @param decomposition String object which will be set to c's + * raw decomposition mapping, if there is one. + * @return true if c has a decomposition, otherwise false + * @stable ICU 49 + */ + virtual UBool + getRawDecomposition(UChar32 c, UnicodeString &decomposition) const override; + + /** + * Performs pairwise composition of a & b and returns the composite if there is one. + * For details see the base class documentation. + * + * This function is independent of the mode of the Normalizer2. + * @param a A (normalization starter) code point. + * @param b Another code point. + * @return The non-negative composite code point if there is one; otherwise a negative value. + * @stable ICU 49 + */ + virtual UChar32 + composePair(UChar32 a, UChar32 b) const override; + + /** + * Gets the combining class of c. + * The default implementation returns 0 + * but all standard implementations return the Unicode Canonical_Combining_Class value. + * @param c code point + * @return c's combining class + * @stable ICU 49 + */ + virtual uint8_t + getCombiningClass(UChar32 c) const override; + + /** + * Tests if the string is normalized. + * For details see the Normalizer2 base class documentation. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if s is normalized + * @stable ICU 4.4 + */ + virtual UBool + isNormalized(const UnicodeString &s, UErrorCode &errorCode) const override; + /** + * Tests if the UTF-8 string is normalized. + * Internally, in cases where the quickCheck() method would return "maybe" + * (which is only possible for the two COMPOSE modes) this method + * resolves to "yes" or "no" to provide a definitive result, + * at the cost of doing more work in those cases. + * + * This works for all normalization modes. + * It is optimized for UTF-8 for all built-in modes except for FCD. + * The base class implementation converts to UTF-16 and calls isNormalized(). + * + * @param s UTF-8 input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if s is normalized + * @stable ICU 60 + */ + virtual UBool + isNormalizedUTF8(StringPiece s, UErrorCode &errorCode) const override; + /** + * Tests if the string is normalized. + * For details see the Normalizer2 base class documentation. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return UNormalizationCheckResult + * @stable ICU 4.4 + */ + virtual UNormalizationCheckResult + quickCheck(const UnicodeString &s, UErrorCode &errorCode) const override; + /** + * Returns the end of the normalized substring of the input string. + * For details see the Normalizer2 base class documentation. + * @param s input string + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return "yes" span end index + * @stable ICU 4.4 + */ + virtual int32_t + spanQuickCheckYes(const UnicodeString &s, UErrorCode &errorCode) const override; + + /** + * Tests if the character always has a normalization boundary before it, + * regardless of context. + * For details see the Normalizer2 base class documentation. + * @param c character to test + * @return true if c has a normalization boundary before it + * @stable ICU 4.4 + */ + virtual UBool hasBoundaryBefore(UChar32 c) const override; + + /** + * Tests if the character always has a normalization boundary after it, + * regardless of context. + * For details see the Normalizer2 base class documentation. + * @param c character to test + * @return true if c has a normalization boundary after it + * @stable ICU 4.4 + */ + virtual UBool hasBoundaryAfter(UChar32 c) const override; + + /** + * Tests if the character is normalization-inert. + * For details see the Normalizer2 base class documentation. + * @param c character to test + * @return true if c is normalization-inert + * @stable ICU 4.4 + */ + virtual UBool isInert(UChar32 c) const override; +private: + UnicodeString & + normalize(const UnicodeString &src, + UnicodeString &dest, + USetSpanCondition spanCondition, + UErrorCode &errorCode) const; + + void + normalizeUTF8(uint32_t options, const char *src, int32_t length, + ByteSink &sink, Edits *edits, + USetSpanCondition spanCondition, + UErrorCode &errorCode) const; + + UnicodeString & + normalizeSecondAndAppend(UnicodeString &first, + const UnicodeString &second, + UBool doNormalize, + UErrorCode &errorCode) const; + + const Normalizer2 &norm2; + const UnicodeSet &set; +}; + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_NORMALIZATION + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __NORMALIZER2_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normlzr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normlzr.h new file mode 100644 index 0000000000000000000000000000000000000000..03a7aa080d1a7826f8270ea35f34d15986cc1847 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/normlzr.h @@ -0,0 +1,816 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************** + * COPYRIGHT: + * Copyright (c) 1996-2015, International Business Machines Corporation and + * others. All Rights Reserved. + ******************************************************************** + */ + +#ifndef NORMLZR_H +#define NORMLZR_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Unicode Normalization + */ + +#if !UCONFIG_NO_NORMALIZATION + +#include "unicode/chariter.h" +#include "unicode/normalizer2.h" +#include "unicode/unistr.h" +#include "unicode/unorm.h" +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN +/** + * Old Unicode normalization API. + * + * This API has been replaced by the Normalizer2 class and is only available + * for backward compatibility. This class simply delegates to the Normalizer2 class. + * There is one exception: The new API does not provide a replacement for Normalizer::compare(). + * + * The Normalizer class supports the standard normalization forms described in + * + * Unicode Standard Annex #15: Unicode Normalization Forms. + * + * The Normalizer class consists of two parts: + * - static functions that normalize strings or test if strings are normalized + * - a Normalizer object is an iterator that takes any kind of text and + * provides iteration over its normalized form + * + * The Normalizer class is not suitable for subclassing. + * + * For basic information about normalization forms and details about the C API + * please see the documentation in unorm.h. + * + * The iterator API with the Normalizer constructors and the non-static functions + * use a CharacterIterator as input. It is possible to pass a string which + * is then internally wrapped in a CharacterIterator. + * The input text is not normalized all at once, but incrementally where needed + * (providing efficient random access). + * This allows to pass in a large text but spend only a small amount of time + * normalizing a small part of that text. + * However, if the entire text is normalized, then the iterator will be + * slower than normalizing the entire text at once and iterating over the result. + * A possible use of the Normalizer iterator is also to report an index into the + * original text that is close to where the normalized characters come from. + * + * Important: The iterator API was cleaned up significantly for ICU 2.0. + * The earlier implementation reported the getIndex() inconsistently, + * and previous() could not be used after setIndex(), next(), first(), and current(). + * + * Normalizer allows to start normalizing from anywhere in the input text by + * calling setIndexOnly(), first(), or last(). + * Without calling any of these, the iterator will start at the beginning of the text. + * + * At any time, next() returns the next normalized code point (UChar32), + * with post-increment semantics (like CharacterIterator::next32PostInc()). + * previous() returns the previous normalized code point (UChar32), + * with pre-decrement semantics (like CharacterIterator::previous32()). + * + * current() returns the current code point + * (respectively the one at the newly set index) without moving + * the getIndex(). Note that if the text at the current position + * needs to be normalized, then these functions will do that. + * (This is why current() is not const.) + * It is more efficient to call setIndexOnly() instead, which does not + * normalize. + * + * getIndex() always refers to the position in the input text where the normalized + * code points are returned from. It does not always change with each returned + * code point. + * The code point that is returned from any of the functions + * corresponds to text at or after getIndex(), according to the + * function's iteration semantics (post-increment or pre-decrement). + * + * next() returns a code point from at or after the getIndex() + * from before the next() call. After the next() call, the getIndex() + * might have moved to where the next code point will be returned from + * (from a next() or current() call). + * This is semantically equivalent to array access with array[index++] + * (post-increment semantics). + * + * previous() returns a code point from at or after the getIndex() + * from after the previous() call. + * This is semantically equivalent to array access with array[--index] + * (pre-decrement semantics). + * + * Internally, the Normalizer iterator normalizes a small piece of text + * starting at the getIndex() and ending at a following "safe" index. + * The normalized results is stored in an internal string buffer, and + * the code points are iterated from there. + * With multiple iteration calls, this is repeated until the next piece + * of text needs to be normalized, and the getIndex() needs to be moved. + * + * The following "safe" index, the internal buffer, and the secondary + * iteration index into that buffer are not exposed on the API. + * This also means that it is currently not practical to return to + * a particular, arbitrary position in the text because one would need to + * know, and be able to set, in addition to the getIndex(), at least also the + * current index into the internal buffer. + * It is currently only possible to observe when getIndex() changes + * (with careful consideration of the iteration semantics), + * at which time the internal index will be 0. + * For example, if getIndex() is different after next() than before it, + * then the internal index is 0 and one can return to this getIndex() + * later with setIndexOnly(). + * + * Note: While the setIndex() and getIndex() refer to indices in the + * underlying Unicode input text, the next() and previous() methods + * iterate through characters in the normalized output. + * This means that there is not necessarily a one-to-one correspondence + * between characters returned by next() and previous() and the indices + * passed to and returned from setIndex() and getIndex(). + * It is for this reason that Normalizer does not implement the CharacterIterator interface. + * + * @author Laura Werner, Mark Davis, Markus Scherer + * @stable ICU 2.0 + */ +class U_COMMON_API Normalizer : public UObject { +public: +#ifndef U_HIDE_DEPRECATED_API + /** + * If DONE is returned from an iteration function that returns a code point, + * then there are no more normalization results available. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + enum { + DONE=0xffff + }; + + // Constructors + + /** + * Creates a new Normalizer object for iterating over the + * normalized form of a given string. + *

+ * @param str The string to be normalized. The normalization + * will start at the beginning of the string. + * + * @param mode The normalization mode. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + Normalizer(const UnicodeString& str, UNormalizationMode mode); + + /** + * Creates a new Normalizer object for iterating over the + * normalized form of a given string. + *

+ * @param str The string to be normalized. The normalization + * will start at the beginning of the string. + * + * @param length Length of the string, or -1 if NUL-terminated. + * @param mode The normalization mode. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + Normalizer(ConstChar16Ptr str, int32_t length, UNormalizationMode mode); + + /** + * Creates a new Normalizer object for iterating over the + * normalized form of the given text. + *

+ * @param iter The input text to be normalized. The normalization + * will start at the beginning of the string. + * + * @param mode The normalization mode. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + Normalizer(const CharacterIterator& iter, UNormalizationMode mode); +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Copy constructor. + * @param copy The object to be copied. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + Normalizer(const Normalizer& copy); + + /** + * Destructor + * @deprecated ICU 56 Use Normalizer2 instead. + */ + virtual ~Normalizer(); +#endif // U_FORCE_HIDE_DEPRECATED_API + + //------------------------------------------------------------------------- + // Static utility methods + //------------------------------------------------------------------------- + +#ifndef U_HIDE_DEPRECATED_API + /** + * Normalizes a UnicodeString according to the specified normalization mode. + * This is a wrapper for unorm_normalize(), using UnicodeString's. + * + * The options parameter specifies which optional + * Normalizer features are to be enabled for this operation. + * + * @param source the input string to be normalized. + * @param mode the normalization mode + * @param options the optional features to be enabled (0 for no options) + * @param result The normalized string (on output). + * @param status The error code. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static void U_EXPORT2 normalize(const UnicodeString& source, + UNormalizationMode mode, int32_t options, + UnicodeString& result, + UErrorCode &status); + + /** + * Compose a UnicodeString. + * This is equivalent to normalize() with mode UNORM_NFC or UNORM_NFKC. + * This is a wrapper for unorm_normalize(), using UnicodeString's. + * + * The options parameter specifies which optional + * Normalizer features are to be enabled for this operation. + * + * @param source the string to be composed. + * @param compat Perform compatibility decomposition before composition. + * If this argument is false, only canonical + * decomposition will be performed. + * @param options the optional features to be enabled (0 for no options) + * @param result The composed string (on output). + * @param status The error code. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static void U_EXPORT2 compose(const UnicodeString& source, + UBool compat, int32_t options, + UnicodeString& result, + UErrorCode &status); + + /** + * Static method to decompose a UnicodeString. + * This is equivalent to normalize() with mode UNORM_NFD or UNORM_NFKD. + * This is a wrapper for unorm_normalize(), using UnicodeString's. + * + * The options parameter specifies which optional + * Normalizer features are to be enabled for this operation. + * + * @param source the string to be decomposed. + * @param compat Perform compatibility decomposition. + * If this argument is false, only canonical + * decomposition will be performed. + * @param options the optional features to be enabled (0 for no options) + * @param result The decomposed string (on output). + * @param status The error code. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static void U_EXPORT2 decompose(const UnicodeString& source, + UBool compat, int32_t options, + UnicodeString& result, + UErrorCode &status); + + /** + * Performing quick check on a string, to quickly determine if the string is + * in a particular normalization format. + * This is a wrapper for unorm_quickCheck(), using a UnicodeString. + * + * Three types of result can be returned UNORM_YES, UNORM_NO or + * UNORM_MAYBE. Result UNORM_YES indicates that the argument + * string is in the desired normalized format, UNORM_NO determines that + * argument string is not in the desired normalized format. A + * UNORM_MAYBE result indicates that a more thorough check is required, + * the user may have to put the string in its normalized form and compare the + * results. + * @param source string for determining if it is in a normalized format + * @param mode normalization format + * @param status A reference to a UErrorCode to receive any errors + * @return UNORM_YES, UNORM_NO or UNORM_MAYBE + * + * @see isNormalized + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static inline UNormalizationCheckResult + quickCheck(const UnicodeString &source, UNormalizationMode mode, UErrorCode &status); + + /** + * Performing quick check on a string; same as the other version of quickCheck + * but takes an extra options parameter like most normalization functions. + * + * @param source string for determining if it is in a normalized format + * @param mode normalization format + * @param options the optional features to be enabled (0 for no options) + * @param status A reference to a UErrorCode to receive any errors + * @return UNORM_YES, UNORM_NO or UNORM_MAYBE + * + * @see isNormalized + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static UNormalizationCheckResult + quickCheck(const UnicodeString &source, UNormalizationMode mode, int32_t options, UErrorCode &status); + + /** + * Test if a string is in a given normalization form. + * This is semantically equivalent to source.equals(normalize(source, mode)) . + * + * Unlike unorm_quickCheck(), this function returns a definitive result, + * never a "maybe". + * For NFD, NFKD, and FCD, both functions work exactly the same. + * For NFC and NFKC where quickCheck may return "maybe", this function will + * perform further tests to arrive at a true/false result. + * + * @param src String that is to be tested if it is in a normalization format. + * @param mode Which normalization form to test for. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return Boolean value indicating whether the source string is in the + * "mode" normalization form. + * + * @see quickCheck + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static inline UBool + isNormalized(const UnicodeString &src, UNormalizationMode mode, UErrorCode &errorCode); + + /** + * Test if a string is in a given normalization form; same as the other version of isNormalized + * but takes an extra options parameter like most normalization functions. + * + * @param src String that is to be tested if it is in a normalization format. + * @param mode Which normalization form to test for. + * @param options the optional features to be enabled (0 for no options) + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return Boolean value indicating whether the source string is in the + * "mode" normalization form. + * + * @see quickCheck + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static UBool + isNormalized(const UnicodeString &src, UNormalizationMode mode, int32_t options, UErrorCode &errorCode); + + /** + * Concatenate normalized strings, making sure that the result is normalized as well. + * + * If both the left and the right strings are in + * the normalization form according to "mode/options", + * then the result will be + * + * \code + * dest=normalize(left+right, mode, options) + * \endcode + * + * For details see unorm_concatenate in unorm.h. + * + * @param left Left source string. + * @param right Right source string. + * @param result The output string. + * @param mode The normalization mode. + * @param options A bit set of normalization options. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return result + * + * @see unorm_concatenate + * @see normalize + * @see unorm_next + * @see unorm_previous + * + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static UnicodeString & + U_EXPORT2 concatenate(const UnicodeString &left, const UnicodeString &right, + UnicodeString &result, + UNormalizationMode mode, int32_t options, + UErrorCode &errorCode); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Compare two strings for canonical equivalence. + * Further options include case-insensitive comparison and + * code point order (as opposed to code unit order). + * + * Canonical equivalence between two strings is defined as their normalized + * forms (NFD or NFC) being identical. + * This function compares strings incrementally instead of normalizing + * (and optionally case-folding) both strings entirely, + * improving performance significantly. + * + * Bulk normalization is only necessary if the strings do not fulfill the FCD + * conditions. Only in this case, and only if the strings are relatively long, + * is memory allocated temporarily. + * For FCD strings and short non-FCD strings there is no memory allocation. + * + * Semantically, this is equivalent to + * strcmp[CodePointOrder](NFD(foldCase(s1)), NFD(foldCase(s2))) + * where code point order and foldCase are all optional. + * + * UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match + * the case folding must be performed first, then the normalization. + * + * @param s1 First source string. + * @param s2 Second source string. + * + * @param options A bit set of options: + * - U_FOLD_CASE_DEFAULT or 0 is used for default options: + * Case-sensitive comparison in code unit order, and the input strings + * are quick-checked for FCD. + * + * - UNORM_INPUT_IS_FCD + * Set if the caller knows that both s1 and s2 fulfill the FCD conditions. + * If not set, the function will quickCheck for FCD + * and normalize if necessary. + * + * - U_COMPARE_CODE_POINT_ORDER + * Set to choose code point order instead of code unit order + * (see u_strCompare for details). + * + * - U_COMPARE_IGNORE_CASE + * Set to compare strings case-insensitively using case folding, + * instead of case-sensitively. + * If set, then the following case folding options are used. + * + * - Options as used with case-insensitive comparisons, currently: + * + * - U_FOLD_CASE_EXCLUDE_SPECIAL_I + * (see u_strCaseCompare for details) + * + * - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT + * + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return <0 or 0 or >0 as usual for string comparisons + * + * @see unorm_compare + * @see normalize + * @see UNORM_FCD + * @see u_strCompare + * @see u_strCaseCompare + * + * @stable ICU 2.2 + */ + static inline int32_t + compare(const UnicodeString &s1, const UnicodeString &s2, + uint32_t options, + UErrorCode &errorCode); + +#ifndef U_HIDE_DEPRECATED_API + //------------------------------------------------------------------------- + // Iteration API + //------------------------------------------------------------------------- + + /** + * Return the current character in the normalized text. + * current() may need to normalize some text at getIndex(). + * The getIndex() is not changed. + * + * @return the current normalized code point + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UChar32 current(void); + + /** + * Return the first character in the normalized text. + * This is equivalent to setIndexOnly(startIndex()) followed by next(). + * (Post-increment semantics.) + * + * @return the first normalized code point + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UChar32 first(void); + + /** + * Return the last character in the normalized text. + * This is equivalent to setIndexOnly(endIndex()) followed by previous(). + * (Pre-decrement semantics.) + * + * @return the last normalized code point + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UChar32 last(void); + + /** + * Return the next character in the normalized text. + * (Post-increment semantics.) + * If the end of the text has already been reached, DONE is returned. + * The DONE value could be confused with a U+FFFF non-character code point + * in the text. If this is possible, you can test getIndex()startIndex() || first()!=DONE). (Calling first() will change + * the iterator state!) + * + * The C API unorm_previous() is more efficient and does not have this ambiguity. + * + * @return the previous normalized code point + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UChar32 previous(void); + + /** + * Set the iteration position in the input text that is being normalized, + * without any immediate normalization. + * After setIndexOnly(), getIndex() will return the same index that is + * specified here. + * + * @param index the desired index in the input text. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setIndexOnly(int32_t index); + + /** + * Reset the index to the beginning of the text. + * This is equivalent to setIndexOnly(startIndex)). + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void reset(void); + + /** + * Retrieve the current iteration position in the input text that is + * being normalized. + * + * A following call to next() will return a normalized code point from + * the input text at or after this index. + * + * After a call to previous(), getIndex() will point at or before the + * position in the input text where the normalized code point + * was returned from with previous(). + * + * @return the current index in the input text + * @deprecated ICU 56 Use Normalizer2 instead. + */ + int32_t getIndex(void) const; + + /** + * Retrieve the index of the start of the input text. This is the begin index + * of the CharacterIterator or the start (i.e. index 0) of the string + * over which this Normalizer is iterating. + * + * @return the smallest index in the input text where the Normalizer operates + * @deprecated ICU 56 Use Normalizer2 instead. + */ + int32_t startIndex(void) const; + + /** + * Retrieve the index of the end of the input text. This is the end index + * of the CharacterIterator or the length of the string + * over which this Normalizer is iterating. + * This end index is exclusive, i.e., the Normalizer operates only on characters + * before this index. + * + * @return the first index in the input text where the Normalizer does not operate + * @deprecated ICU 56 Use Normalizer2 instead. + */ + int32_t endIndex(void) const; + + /** + * Returns true when both iterators refer to the same character in the same + * input text. + * + * @param that a Normalizer object to compare this one to + * @return comparison result + * @deprecated ICU 56 Use Normalizer2 instead. + */ + bool operator==(const Normalizer& that) const; + + /** + * Returns false when both iterators refer to the same character in the same + * input text. + * + * @param that a Normalizer object to compare this one to + * @return comparison result + * @deprecated ICU 56 Use Normalizer2 instead. + */ + inline bool operator!=(const Normalizer& that) const; + + /** + * Returns a pointer to a new Normalizer that is a clone of this one. + * The caller is responsible for deleting the new clone. + * @return a pointer to a new Normalizer + * @deprecated ICU 56 Use Normalizer2 instead. + */ + Normalizer* clone() const; + + /** + * Generates a hash code for this iterator. + * + * @return the hash code + * @deprecated ICU 56 Use Normalizer2 instead. + */ + int32_t hashCode(void) const; + + //------------------------------------------------------------------------- + // Property access methods + //------------------------------------------------------------------------- + + /** + * Set the normalization mode for this object. + *

+ * Note:If the normalization mode is changed while iterating + * over a string, calls to {@link #next() } and {@link #previous() } may + * return previously buffers characters in the old normalization mode + * until the iteration is able to re-sync at the next base character. + * It is safest to call {@link #setIndexOnly }, {@link #reset() }, + * {@link #setText }, {@link #first() }, + * {@link #last() }, etc. after calling setMode. + *

+ * @param newMode the new mode for this Normalizer. + * @see #getUMode + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setMode(UNormalizationMode newMode); + + /** + * Return the normalization mode for this object. + * + * This is an unusual name because there used to be a getMode() that + * returned a different type. + * + * @return the mode for this Normalizer + * @see #setMode + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UNormalizationMode getUMode(void) const; + + /** + * Set options that affect this Normalizer's operation. + * Options do not change the basic composition or decomposition operation + * that is being performed, but they control whether + * certain optional portions of the operation are done. + * Currently the only available option is obsolete. + * + * It is possible to specify multiple options that are all turned on or off. + * + * @param option the option(s) whose value is/are to be set. + * @param value the new setting for the option. Use true to + * turn the option(s) on and false to turn it/them off. + * + * @see #getOption + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setOption(int32_t option, + UBool value); + + /** + * Determine whether an option is turned on or off. + * If multiple options are specified, then the result is true if any + * of them are set. + *

+ * @param option the option(s) that are to be checked + * @return true if any of the option(s) are set + * @see #setOption + * @deprecated ICU 56 Use Normalizer2 instead. + */ + UBool getOption(int32_t option) const; + + /** + * Set the input text over which this Normalizer will iterate. + * The iteration position is set to the beginning. + * + * @param newText a string that replaces the current input text + * @param status a UErrorCode + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setText(const UnicodeString& newText, + UErrorCode &status); + + /** + * Set the input text over which this Normalizer will iterate. + * The iteration position is set to the beginning. + * + * @param newText a CharacterIterator object that replaces the current input text + * @param status a UErrorCode + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setText(const CharacterIterator& newText, + UErrorCode &status); + + /** + * Set the input text over which this Normalizer will iterate. + * The iteration position is set to the beginning. + * + * @param newText a string that replaces the current input text + * @param length the length of the string, or -1 if NUL-terminated + * @param status a UErrorCode + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void setText(ConstChar16Ptr newText, + int32_t length, + UErrorCode &status); + /** + * Copies the input text into the UnicodeString argument. + * + * @param result Receives a copy of the text under iteration. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + void getText(UnicodeString& result); + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * @returns a UClassID for this class. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + static UClassID U_EXPORT2 getStaticClassID(); +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * @return a UClassID for the actual class. + * @deprecated ICU 56 Use Normalizer2 instead. + */ + virtual UClassID getDynamicClassID() const override; +#endif // U_FORCE_HIDE_DEPRECATED_API + +private: + //------------------------------------------------------------------------- + // Private functions + //------------------------------------------------------------------------- + + Normalizer() = delete; // default constructor not implemented + Normalizer &operator=(const Normalizer &that) = delete; // assignment operator not implemented + + // Private utility methods for iteration + // For documentation, see the source code + UBool nextNormalize(); + UBool previousNormalize(); + + void init(); + void clearBuffer(void); + + //------------------------------------------------------------------------- + // Private data + //------------------------------------------------------------------------- + + FilteredNormalizer2*fFilteredNorm2; // owned if not nullptr + const Normalizer2 *fNorm2; // not owned; may be equal to fFilteredNorm2 + UNormalizationMode fUMode; // deprecated + int32_t fOptions; + + // The input text and our position in it + CharacterIterator *text; + + // The normalization buffer is the result of normalization + // of the source in [currentIndex..nextIndex[ . + int32_t currentIndex, nextIndex; + + // A buffer for holding intermediate results + UnicodeString buffer; + int32_t bufferPos; +}; + +//------------------------------------------------------------------------- +// Inline implementations +//------------------------------------------------------------------------- + +#ifndef U_HIDE_DEPRECATED_API +inline bool +Normalizer::operator!= (const Normalizer& other) const +{ return ! operator==(other); } + +inline UNormalizationCheckResult +Normalizer::quickCheck(const UnicodeString& source, + UNormalizationMode mode, + UErrorCode &status) { + return quickCheck(source, mode, 0, status); +} + +inline UBool +Normalizer::isNormalized(const UnicodeString& source, + UNormalizationMode mode, + UErrorCode &status) { + return isNormalized(source, mode, 0, status); +} +#endif /* U_HIDE_DEPRECATED_API */ + +inline int32_t +Normalizer::compare(const UnicodeString &s1, const UnicodeString &s2, + uint32_t options, + UErrorCode &errorCode) { + // all argument checking is done in unorm_compare + return unorm_compare(toUCharPtr(s1.getBuffer()), s1.length(), + toUCharPtr(s2.getBuffer()), s2.length(), + options, + &errorCode); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_NORMALIZATION */ + +#endif // NORMLZR_H + +#endif /* U_SHOW_CPLUSPLUS_API */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/nounit.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/nounit.h new file mode 100644 index 0000000000000000000000000000000000000000..96aca35d0132e906dad4d99801308ad4b82e55b0 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/nounit.h @@ -0,0 +1,86 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2009-2017, International Business Machines Corporation, * + * Google, and others. All Rights Reserved. * + ******************************************************************************* + */ + +#ifndef __NOUNIT_H__ +#define __NOUNIT_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/measunit.h" + +/** + * \file + * \brief C++ API: units for percent and permille + */ + +U_NAMESPACE_BEGIN + +/** + * Dimensionless unit for percent and permille. + * Prior to ICU 68, this namespace was a class with the same name. + * @see NumberFormatter + * @stable ICU 68 + */ +namespace NoUnit { + /** + * Returns an instance for the base unit (dimensionless and no scaling). + * + * Prior to ICU 68, this function returned a NoUnit by value. + * + * Since ICU 68, this function returns the same value as the default MeasureUnit constructor. + * + * @return a MeasureUnit instance + * @stable ICU 68 + */ + static inline MeasureUnit U_EXPORT2 base() { + return MeasureUnit(); + } + + /** + * Returns an instance for percent, or 1/100 of a base unit. + * + * Prior to ICU 68, this function returned a NoUnit by value. + * + * Since ICU 68, this function returns the same value as MeasureUnit::getPercent(). + * + * @return a MeasureUnit instance + * @stable ICU 68 + */ + static inline MeasureUnit U_EXPORT2 percent() { + return MeasureUnit::getPercent(); + } + + /** + * Returns an instance for permille, or 1/1000 of a base unit. + * + * Prior to ICU 68, this function returned a NoUnit by value. + * + * Since ICU 68, this function returns the same value as MeasureUnit::getPermille(). + * + * @return a MeasureUnit instance + * @stable ICU 68 + */ + static inline MeasureUnit U_EXPORT2 permille() { + return MeasureUnit::getPermille(); + } +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __NOUNIT_H__ +//eof +// diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..caf98e3dfa6be49e4a9b041ad1a855807c49ab63 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberformatter.h @@ -0,0 +1,2787 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __NUMBERFORMATTER_H__ +#define __NUMBERFORMATTER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/appendable.h" +#include "unicode/bytestream.h" +#include "unicode/currunit.h" +#include "unicode/dcfmtsym.h" +#include "unicode/displayoptions.h" +#include "unicode/fieldpos.h" +#include "unicode/fpositer.h" +#include "unicode/measunit.h" +#include "unicode/nounit.h" +#include "unicode/parseerr.h" +#include "unicode/plurrule.h" +#include "unicode/ucurr.h" +#include "unicode/unum.h" +#include "unicode/unumberformatter.h" +#include "unicode/uobject.h" +#include "unicode/unumberoptions.h" +#include "unicode/formattednumber.h" + +/** + * \file + * \brief C++ API: All-in-one formatter for localized numbers, currencies, and units. + * + * For a full list of options, see icu::number::NumberFormatterSettings. + * + *

+ * // Most basic usage:
+ * NumberFormatter::withLocale(...).format(123).toString();  // 1,234 in en-US
+ *
+ * // Custom notation, unit, and rounding precision:
+ * NumberFormatter::with()
+ *     .notation(Notation::compactShort())
+ *     .unit(CurrencyUnit("EUR", status))
+ *     .precision(Precision::maxDigits(2))
+ *     .locale(...)
+ *     .format(1234)
+ *     .toString();  // €1.2K in en-US
+ *
+ * // Create a formatter in a singleton by value for use later:
+ * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...)
+ *     .unit(NoUnit::percent())
+ *     .precision(Precision::fixedFraction(3));
+ * formatter.format(5.9831).toString();  // 5.983% in en-US
+ *
+ * // Create a "template" in a singleton unique_ptr but without setting a locale until the call site:
+ * std::unique_ptr template = NumberFormatter::with()
+ *     .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
+ *     .unit(MeasureUnit::getMeter())
+ *     .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
+ *     .clone();
+ * template->locale(...).format(1234).toString();  // +1,234 meters in en-US
+ * 
+ * + *

+ * This API offers more features than DecimalFormat and is geared toward new users of ICU. + * + *

+ * NumberFormatter instances (i.e., LocalizedNumberFormatter and UnlocalizedNumberFormatter) + * are immutable and thread safe. This means that invoking a configuration method has no + * effect on the receiving instance; you must store and use the new number formatter instance it returns instead. + * + *

+ * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific());
+ * formatter.precision(Precision.maxFraction(2)); // does nothing!
+ * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0"
+ * 
+ * + *

+ * This API is based on the fluent design pattern popularized by libraries such as Google's Guava. For + * extensive details on the design of this API, read the design doc. + * + * @author Shane Carr + */ + +U_NAMESPACE_BEGIN + +// Forward declarations: +class IFixedDecimal; +class FieldPositionIteratorHandler; +class FormattedStringBuilder; + +namespace numparse { +namespace impl { + +// Forward declarations: +class NumberParserImpl; +class MultiplierParseHandler; + +} +} + +namespace units { + +// Forward declarations: +class UnitsRouter; + +} // namespace units + +namespace number { // icu::number + +// Forward declarations: +class UnlocalizedNumberFormatter; +class LocalizedNumberFormatter; +class SimpleNumberFormatter; +class FormattedNumber; +class Notation; +class ScientificNotation; +class Precision; +class FractionPrecision; +class CurrencyPrecision; +class IncrementPrecision; +class IntegerWidth; + +namespace impl { + +// can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes +/** + * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig. + * + * @internal + */ +typedef int16_t digits_t; + +// can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization +/** + * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built + * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path. + * + * @internal + */ +static constexpr int32_t kInternalDefaultThreshold = 3; + +// Forward declarations: +class Padder; +struct MacroProps; +struct MicroProps; +class DecimalQuantity; +class UFormattedNumberData; +class NumberFormatterImpl; +struct ParsedPatternInfo; +class ScientificModifier; +class MultiplierProducer; +class RoundingImpl; +class ScientificHandler; +class Modifier; +class AffixPatternProvider; +class NumberPropertyMapper; +struct DecimalFormatProperties; +class MultiplierFormatHandler; +class CurrencySymbols; +class GeneratorHelpers; +class DecNum; +class NumberRangeFormatterImpl; +struct RangeMacroProps; +struct UFormattedNumberImpl; +class MutablePatternModifier; +class ImmutablePatternModifier; +struct DecimalFormatWarehouse; +struct SimpleMicroProps; +class AdoptingSignumModifierStore; + +/** + * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp. + * Declared here so it can be friended. + * + * @internal + */ +void touchRangeLocales(impl::RangeMacroProps& macros); + +} // namespace impl + +/** + * Extra name reserved in case it is needed in the future. + * + * @stable ICU 63 + */ +typedef Notation CompactNotation; + +/** + * Extra name reserved in case it is needed in the future. + * + * @stable ICU 63 + */ +typedef Notation SimpleNotation; + +/** + * A class that defines the notation style to be used when formatting numbers in NumberFormatter. + * + * @stable ICU 60 + */ +class U_I18N_API Notation : public UMemory { + public: + /** + * Print the number using scientific notation (also known as scientific form, standard index form, or standard form + * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the + * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more + * digits after the decimal separator, and the corresponding power of 10 displayed after the "E". + * + *

+ * Example outputs in en-US when printing 8.765E4 through 8.765E-3: + * + *

+     * 8.765E4
+     * 8.765E3
+     * 8.765E2
+     * 8.765E1
+     * 8.765E0
+     * 8.765E-1
+     * 8.765E-2
+     * 8.765E-3
+     * 0E0
+     * 
+ * + * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. + * @stable ICU 60 + */ + static ScientificNotation scientific(); + + /** + * Print the number using engineering notation, a variant of scientific notation in which the exponent must be + * divisible by 3. + * + *

+ * Example outputs in en-US when printing 8.765E4 through 8.765E-3: + * + *

+     * 87.65E3
+     * 8.765E3
+     * 876.5E0
+     * 87.65E0
+     * 8.765E0
+     * 876.5E-3
+     * 87.65E-3
+     * 8.765E-3
+     * 0E0
+     * 
+ * + * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. + * @stable ICU 60 + */ + static ScientificNotation engineering(); + + /** + * Print the number using short-form compact notation. + * + *

+ * Compact notation, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with + * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to + * engineering notation in how it scales numbers. + * + *

+ * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing + * screen real estate. + * + *

+ * In short form, the powers of ten are abbreviated. In en-US, the abbreviations are "K" for thousands, "M" + * for millions, "B" for billions, and "T" for trillions. Example outputs in en-US when printing 8.765E7 + * through 8.765E0: + * + *

+     * 88M
+     * 8.8M
+     * 876K
+     * 88K
+     * 8.8K
+     * 876
+     * 88
+     * 8.8
+     * 
+ * + *

+ * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest + * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal + * separator if there is only one digit before the decimal separator. The default compact notation rounding precision + * is equivalent to: + * + *

+     * Precision::integer().withMinDigits(2)
+     * 
+ * + * @return A CompactNotation for passing to the NumberFormatter notation() setter. + * @stable ICU 60 + */ + static CompactNotation compactShort(); + + /** + * Print the number using long-form compact notation. For more information on compact notation, see + * {@link #compactShort}. + * + *

+ * In long form, the powers of ten are spelled out fully. Example outputs in en-US when printing 8.765E7 + * through 8.765E0: + * + *

+     * 88 million
+     * 8.8 million
+     * 876 thousand
+     * 88 thousand
+     * 8.8 thousand
+     * 876
+     * 88
+     * 8.8
+     * 
+ * + * @return A CompactNotation for passing to the NumberFormatter notation() setter. + * @stable ICU 60 + */ + static CompactNotation compactLong(); + + /** + * Print the number using simple notation without any scaling by powers of ten. This is the default behavior. + * + *

+ * Since this is the default behavior, this method needs to be called only when it is necessary to override a + * previous setting. + * + *

+ * Example outputs in en-US when printing 8.765E7 through 8.765E0: + * + *

+     * 87,650,000
+     * 8,765,000
+     * 876,500
+     * 87,650
+     * 8,765
+     * 876.5
+     * 87.65
+     * 8.765
+     * 
+ * + * @return A SimpleNotation for passing to the NumberFormatter notation() setter. + * @stable ICU 60 + */ + static SimpleNotation simple(); + + private: + enum NotationType { + NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR + } fType; + + union NotationUnion { + // For NTN_SCIENTIFIC + /** @internal (private) */ + struct ScientificSettings { + /** @internal (private) */ + int8_t fEngineeringInterval; + /** @internal (private) */ + bool fRequireMinInt; + /** @internal (private) */ + impl::digits_t fMinExponentDigits; + /** @internal (private) */ + UNumberSignDisplay fExponentSignDisplay; + } scientific; + + // For NTN_COMPACT + UNumberCompactStyle compactStyle; + + // For NTN_ERROR + UErrorCode errorCode; + } fUnion; + + typedef NotationUnion::ScientificSettings ScientificSettings; + + Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {} + + Notation(UErrorCode errorCode) : fType(NTN_ERROR) { + fUnion.errorCode = errorCode; + } + + Notation() : fType(NTN_SIMPLE), fUnion() {} + + UBool copyErrorTo(UErrorCode &status) const { + if (fType == NTN_ERROR) { + status = fUnion.errorCode; + return true; + } + return false; + } + + // To allow MacroProps to initialize empty instances: + friend struct impl::MacroProps; + friend class ScientificNotation; + + // To allow implementation to access internal types: + friend class impl::NumberFormatterImpl; + friend class impl::ScientificModifier; + friend class impl::ScientificHandler; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; +}; + +/** + * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter. + * + *

+ * To create a ScientificNotation, use one of the factory methods in {@link Notation}. + * + * @stable ICU 60 + */ +class U_I18N_API ScientificNotation : public Notation { + public: + /** + * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if + * necessary. Useful for fixed-width display. + * + *

+ * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in en-US instead of + * the default "1.23E2". + * + * @param minExponentDigits + * The minimum number of digits to show in the exponent. + * @return A ScientificNotation, for chaining. + * @stable ICU 60 + */ + ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const; + + /** + * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO, + * showing the minus sign but not the plus sign. + * + *

+ * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in en-US + * instead of the default "1.23E2". + * + * @param exponentSignDisplay + * The strategy for displaying the sign in the exponent. + * @return A ScientificNotation, for chaining. + * @stable ICU 60 + */ + ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const; + + private: + // Inherit constructor + using Notation::Notation; + + // Raw constructor for NumberPropertyMapper + ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits, + UNumberSignDisplay fExponentSignDisplay); + + friend class Notation; + + // So that NumberPropertyMapper can create instances + friend class impl::NumberPropertyMapper; +}; + +/** + * Extra name reserved in case it is needed in the future. + * + * @stable ICU 63 + */ +typedef Precision SignificantDigitsPrecision; + +/** + * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter. + * + *

+ * To create a Precision, use one of the factory methods. + * + * @stable ICU 60 + */ +class U_I18N_API Precision : public UMemory { + + public: + /** + * Show all available digits to full precision. + * + *

+ * NOTE: When formatting a double, this method, along with {@link #minFraction} and + * {@link #minSignificantDigits}, will trigger complex algorithm similar to Dragon4 to determine the + * low-order digits and the number of digits to display based on the value of the double. + * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction} + * or {@link #maxSignificantDigits} instead to maximize performance. + * For more information, read the following blog post. + * + *

+ * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/ + * + * @return A Precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static Precision unlimited(); + + /** + * Show numbers rounded if necessary to the nearest integer. + * + * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static FractionPrecision integer(); + + /** + * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). + * Additionally, pad with zeros to ensure that this number of places are always shown. + * + *

+ * Example output with minMaxFractionPlaces = 3: + * + *

+ * 87,650.000
+ * 8,765.000
+ * 876.500
+ * 87.650
+ * 8.765
+ * 0.876
+ * 0.088
+ * 0.009
+ * 0.000 (zero) + * + *

+ * This method is equivalent to {@link #minMaxFraction} with both arguments equal. + * + * @param minMaxFractionPlaces + * The minimum and maximum number of numerals to display after the decimal separator (rounding if too + * long or padding with zeros if too short). + * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces); + + /** + * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if + * necessary. Do not perform rounding (display numbers to their full precision). + * + *

+ * NOTE: If you are formatting doubles, see the performance note in {@link #unlimited}. + * + * @param minFractionPlaces + * The minimum number of numerals to display after the decimal separator (padding with zeros if + * necessary). + * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static FractionPrecision minFraction(int32_t minFractionPlaces); + + /** + * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). + * Unlike the other fraction rounding strategies, this strategy does not pad zeros to the end of the + * number. + * + * @param maxFractionPlaces + * The maximum number of numerals to display after the decimal mark (rounding if necessary). + * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static FractionPrecision maxFraction(int32_t maxFractionPlaces); + + /** + * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator); + * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if + * necessary. + * + * @param minFractionPlaces + * The minimum number of numerals to display after the decimal separator (padding with zeros if + * necessary). + * @param maxFractionPlaces + * The maximum number of numerals to display after the decimal separator (rounding if necessary). + * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces); + + /** + * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally, + * pad with zeros to ensure that this number of significant digits/figures are always shown. + * + *

+ * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal. + * + * @param minMaxSignificantDigits + * The minimum and maximum number of significant digits to display (rounding if too long or padding with + * zeros if too short). + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 62 + */ + static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits); + + /** + * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not + * perform rounding (display numbers to their full precision). + * + *

+ * NOTE: If you are formatting doubles, see the performance note in {@link #unlimited}. + * + * @param minSignificantDigits + * The minimum number of significant digits to display (padding with zeros if too short). + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 62 + */ + static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits); + + /** + * Show numbers rounded if necessary to a certain number of significant digits/figures. + * + * @param maxSignificantDigits + * The maximum number of significant digits to display (rounding if too long). + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 62 + */ + static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits); + + /** + * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at + * least a certain number of significant digits, padding with zeros if necessary. + * + * @param minSignificantDigits + * The minimum number of significant digits to display (padding with zeros if necessary). + * @param maxSignificantDigits + * The maximum number of significant digits to display (rounding if necessary). + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 62 + */ + static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits, + int32_t maxSignificantDigits); + + /** + * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the + * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5. + * + *

+ * In order to ensure that numbers are padded to the appropriate number of fraction places, call + * withMinFraction() on the return value of this method. + * For example, to round to the nearest 0.5 and always display 2 numerals after the + * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run: + * + *

+     * Precision::increment(0.5).withMinFraction(2)
+     * 
+ * + * @param roundingIncrement + * The increment to which to round numbers. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static IncrementPrecision increment(double roundingIncrement); + + /** + * Version of `Precision::increment()` that takes an integer at a particular power of 10. + * + * To round to the nearest 0.5 and display 2 fraction digits, with this function, you should write one of the following: + * + *
+     * Precision::incrementExact(5, -1).withMinFraction(2)
+     * Precision::incrementExact(50, -2).withMinFraction(2)
+     * Precision::incrementExact(50, -2)
+     * 
+ * + * This is analagous to ICU4J `Precision.increment(new BigDecimal("0.50"))`. + * + * This behavior is modeled after ECMA-402. For more information, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingincrement + * + * @param mantissa + * The increment to which to round numbers. + * @param magnitude + * The power of 10 of the ones digit of the mantissa. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 71 + */ + static IncrementPrecision incrementExact(uint64_t mantissa, int16_t magnitude); + + /** + * Show numbers rounded and padded according to the rules for the currency unit. The most common + * rounding precision settings for currencies include Precision::fixedFraction(2), + * Precision::integer(), and Precision::increment(0.05) for cash transactions + * ("nickel rounding"). + * + *

+ * The exact rounding details will be resolved at runtime based on the currency unit specified in the + * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another + * currency, the withCurrency() method can be called on the return value of this method. + * + * @param currencyUsage + * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may + * be limited by the available denominations of cash or coins). + * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + static CurrencyPrecision currency(UCurrencyUsage currencyUsage); + + /** + * Configure how trailing zeros are displayed on numbers. For example, to hide trailing zeros + * when the number is an integer, use UNUM_TRAILING_ZERO_HIDE_IF_WHOLE. + * + * @param trailingZeroDisplay Option to configure the display of trailing zeros. + * @stable ICU 69 + */ + Precision trailingZeroDisplay(UNumberTrailingZeroDisplay trailingZeroDisplay) const; + + private: + enum PrecisionType { + RND_BOGUS, + RND_NONE, + RND_FRACTION, + RND_SIGNIFICANT, + RND_FRACTION_SIGNIFICANT, + + // Used for strange increments like 3.14. + RND_INCREMENT, + + // Used for increments with 1 as the only digit. This is different than fraction + // rounding because it supports having additional trailing zeros. For example, this + // class is used to round with the increment 0.010. + RND_INCREMENT_ONE, + + // Used for increments with 5 as the only digit (nickel rounding). + RND_INCREMENT_FIVE, + + RND_CURRENCY, + RND_ERROR + } fType; + + union PrecisionUnion { + /** @internal (private) */ + struct FractionSignificantSettings { + // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT + /** @internal (private) */ + impl::digits_t fMinFrac; + /** @internal (private) */ + impl::digits_t fMaxFrac; + /** @internal (private) */ + impl::digits_t fMinSig; + /** @internal (private) */ + impl::digits_t fMaxSig; + /** @internal (private) */ + UNumberRoundingPriority fPriority; + /** + * Whether to retain trailing zeros based on the looser strategy. + * @internal (private) + */ + bool fRetain; + } fracSig; + /** @internal (private) */ + struct IncrementSettings { + // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE + // Note: This is a union, so we shouldn't own memory, since + // the default destructor would leak it. + /** @internal (private) */ + uint64_t fIncrement; + /** @internal (private) */ + impl::digits_t fIncrementMagnitude; + /** @internal (private) */ + impl::digits_t fMinFrac; + } increment; + UCurrencyUsage currencyUsage; // For RND_CURRENCY + UErrorCode errorCode; // For RND_ERROR + } fUnion; + + UNumberTrailingZeroDisplay fTrailingZeroDisplay = UNUM_TRAILING_ZERO_AUTO; + + typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings; + typedef PrecisionUnion::IncrementSettings IncrementSettings; + + Precision(const PrecisionType& type, const PrecisionUnion& union_) + : fType(type), fUnion(union_) {} + + Precision(UErrorCode errorCode) : fType(RND_ERROR) { + fUnion.errorCode = errorCode; + } + + Precision() : fType(RND_BOGUS) {} + + bool isBogus() const { + return fType == RND_BOGUS; + } + + UBool copyErrorTo(UErrorCode &status) const { + if (fType == RND_ERROR) { + status = fUnion.errorCode; + return true; + } + return false; + } + + // On the parent type so that this method can be called internally on Precision instances. + Precision withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const; + + static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac); + + static Precision constructSignificant(int32_t minSig, int32_t maxSig); + + static Precision constructFractionSignificant( + const FractionPrecision &base, + int32_t minSig, + int32_t maxSig, + UNumberRoundingPriority priority, + bool retain); + + static IncrementPrecision constructIncrement(uint64_t increment, impl::digits_t magnitude); + + static CurrencyPrecision constructCurrency(UCurrencyUsage usage); + + // To allow MacroProps/MicroProps to initialize bogus instances: + friend struct impl::MacroProps; + friend struct impl::MicroProps; + + // To allow NumberFormatterImpl to access isBogus() and other internal methods: + friend class impl::NumberFormatterImpl; + + // To allow NumberPropertyMapper to create instances from DecimalFormatProperties: + friend class impl::NumberPropertyMapper; + + // To allow access to the main implementation class: + friend class impl::RoundingImpl; + + // To allow child classes to call private methods: + friend class FractionPrecision; + friend class CurrencyPrecision; + friend class IncrementPrecision; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; + + // To allow access to isBogus and the default (bogus) constructor: + friend class units::UnitsRouter; +}; + +/** + * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be + * used when formatting numbers in NumberFormatter. + * + *

+ * To create a FractionPrecision, use one of the factory methods on Precision. + * + * @stable ICU 60 + */ +class U_I18N_API FractionPrecision : public Precision { + public: + /** + * Override maximum fraction digits with maximum significant digits depending on the magnitude + * of the number. See UNumberRoundingPriority. + * + * @param minSignificantDigits + * Pad trailing zeros to achieve this minimum number of significant digits. + * @param maxSignificantDigits + * Round the number to achieve this maximum number of significant digits. + * @param priority + * How to disambiguate between fraction digits and significant digits. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * + * @stable ICU 69 + */ + Precision withSignificantDigits( + int32_t minSignificantDigits, + int32_t maxSignificantDigits, + UNumberRoundingPriority priority) const; + + /** + * Ensure that no less than this number of significant digits are retained when rounding + * according to fraction rules. + * + * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum + * figures set to 2, 3.141 becomes "3.1" instead. + * + * This setting does not affect the number of trailing zeros. For example, 3.01 would print as + * "3", not "3.0". + * + * This is equivalent to `withSignificantDigits(1, minSignificantDigits, RELAXED)`. + * + * @param minSignificantDigits + * The number of significant figures to guarantee. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + Precision withMinDigits(int32_t minSignificantDigits) const; + + /** + * Ensure that no more than this number of significant digits are retained when rounding + * according to fraction rules. + * + * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum + * figures set to 2, 123.4 becomes "120" instead. + * + * This setting does not affect the number of trailing zeros. For example, with fixed fraction + * of 2, 123.4 would become "120.00". + * + * This is equivalent to `withSignificantDigits(1, maxSignificantDigits, STRICT)`. + * + * @param maxSignificantDigits + * Round the number to no more than this number of significant figures. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + Precision withMaxDigits(int32_t maxSignificantDigits) const; + + private: + // Inherit constructor + using Precision::Precision; + + // To allow parent class to call this class's constructor: + friend class Precision; +}; + +/** + * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in + * NumberFormatter. + * + *

+ * To create a CurrencyPrecision, use one of the factory methods on Precision. + * + * @stable ICU 60 + */ +class U_I18N_API CurrencyPrecision : public Precision { + public: + /** + * Associates a currency with this rounding precision. + * + *

+ * Calling this method is not required, because the currency specified in unit() + * is automatically applied to currency rounding precisions. However, + * this method enables you to override that automatic association. + * + *

+ * This method also enables numbers to be formatted using currency rounding rules without explicitly using a + * currency format. + * + * @param currency + * The currency to associate with this rounding precision. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + Precision withCurrency(const CurrencyUnit ¤cy) const; + + private: + // Inherit constructor + using Precision::Precision; + + // To allow parent class to call this class's constructor: + friend class Precision; +}; + +/** + * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in + * NumberFormatter. + * + *

+ * To create an IncrementPrecision, use one of the factory methods on Precision. + * + * @stable ICU 60 + */ +class U_I18N_API IncrementPrecision : public Precision { + public: + /** + * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if + * necessary. By default, no trailing zeros are added. + * + *

+ * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00", + * "0.50", "1.00", and "1.50". + * + *

+ * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment. + * + * @param minFrac The minimum number of digits after the decimal separator. + * @return A precision for chaining or passing to the NumberFormatter precision() setter. + * @stable ICU 60 + */ + Precision withMinFraction(int32_t minFrac) const; + + private: + // Inherit constructor + using Precision::Precision; + + // To allow parent class to call this class's constructor: + friend class Precision; +}; + +/** + * A class that defines the strategy for padding and truncating integers before the decimal separator. + * + *

+ * To create an IntegerWidth, use one of the factory methods. + * + * @stable ICU 60 + * @see NumberFormatter + */ +class U_I18N_API IntegerWidth : public UMemory { + public: + /** + * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator. + * + *

+ * For example, with minInt=3, the number 55 will get printed as "055". + * + * @param minInt + * The minimum number of places before the decimal separator. + * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter. + * @stable ICU 60 + */ + static IntegerWidth zeroFillTo(int32_t minInt); + + /** + * Truncate numbers exceeding a certain number of numerals before the decimal separator. + * + * For example, with maxInt=3, the number 1234 will get printed as "234". + * + * @param maxInt + * The maximum number of places before the decimal separator. maxInt == -1 means no + * truncation. + * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter. + * @stable ICU 60 + */ + IntegerWidth truncateAt(int32_t maxInt); + + private: + union { + struct { + impl::digits_t fMinInt; + impl::digits_t fMaxInt; + bool fFormatFailIfMoreThanMaxDigits; + } minMaxInt; + UErrorCode errorCode; + } fUnion; + bool fHasError = false; + + IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits); + + IntegerWidth(UErrorCode errorCode) { // NOLINT + fUnion.errorCode = errorCode; + fHasError = true; + } + + IntegerWidth() { // NOLINT + fUnion.minMaxInt.fMinInt = -1; + } + + /** Returns the default instance. */ + static IntegerWidth standard() { + return IntegerWidth::zeroFillTo(1); + } + + bool isBogus() const { + return !fHasError && fUnion.minMaxInt.fMinInt == -1; + } + + UBool copyErrorTo(UErrorCode &status) const { + if (fHasError) { + status = fUnion.errorCode; + return true; + } + return false; + } + + void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const; + + bool operator==(const IntegerWidth& other) const; + + // To allow MacroProps/MicroProps to initialize empty instances: + friend struct impl::MacroProps; + friend struct impl::MicroProps; + + // To allow NumberFormatterImpl to access isBogus(): + friend class impl::NumberFormatterImpl; + + // To allow the use of this class when formatting: + friend class impl::MutablePatternModifier; + friend class impl::ImmutablePatternModifier; + + // So that NumberPropertyMapper can create instances + friend class impl::NumberPropertyMapper; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; +}; + +/** + * A class that defines a quantity by which a number should be multiplied when formatting. + * + *

+ * To create a Scale, use one of the factory methods. + * + * @stable ICU 62 + */ +class U_I18N_API Scale : public UMemory { + public: + /** + * Do not change the value of numbers when formatting or parsing. + * + * @return A Scale to prevent any multiplication. + * @stable ICU 62 + */ + static Scale none(); + + /** + * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit: + * + *

+     * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2))
+     * 
+ * + * @return A Scale for passing to the setter in NumberFormatter. + * @stable ICU 62 + */ + static Scale powerOfTen(int32_t power); + + /** + * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions. + * + * This method takes a string in a decimal number format with syntax + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * Also see the version of this method that takes a double. + * + * @return A Scale for passing to the setter in NumberFormatter. + * @stable ICU 62 + */ + static Scale byDecimal(StringPiece multiplicand); + + /** + * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions. + * + * This method takes a double; also see the version of this method that takes an exact decimal. + * + * @return A Scale for passing to the setter in NumberFormatter. + * @stable ICU 62 + */ + static Scale byDouble(double multiplicand); + + /** + * Multiply a number by both a power of ten and by an arbitrary double value. + * + * @return A Scale for passing to the setter in NumberFormatter. + * @stable ICU 62 + */ + static Scale byDoubleAndPowerOfTen(double multiplicand, int32_t power); + + // We need a custom destructor for the DecNum, which means we need to declare + // the copy/move constructor/assignment quartet. + + /** @stable ICU 62 */ + Scale(const Scale& other); + + /** @stable ICU 62 */ + Scale& operator=(const Scale& other); + + /** @stable ICU 62 */ + Scale(Scale&& src) noexcept; + + /** @stable ICU 62 */ + Scale& operator=(Scale&& src) noexcept; + + /** @stable ICU 62 */ + ~Scale(); + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + Scale(int32_t magnitude, impl::DecNum* arbitraryToAdopt); +#endif /* U_HIDE_INTERNAL_API */ + + private: + int32_t fMagnitude; + impl::DecNum* fArbitrary; + UErrorCode fError; + + Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {} + + Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {} + + bool isValid() const { + return fMagnitude != 0 || fArbitrary != nullptr; + } + + UBool copyErrorTo(UErrorCode &status) const { + if (U_FAILURE(fError)) { + status = fError; + return true; + } + return false; + } + + void applyTo(impl::DecimalQuantity& quantity) const; + + void applyReciprocalTo(impl::DecimalQuantity& quantity) const; + + // To allow MacroProps/MicroProps to initialize empty instances: + friend struct impl::MacroProps; + friend struct impl::MicroProps; + + // To allow NumberFormatterImpl to access isBogus() and perform other operations: + friend class impl::NumberFormatterImpl; + + // To allow the helper class MultiplierFormatHandler access to private fields: + friend class impl::MultiplierFormatHandler; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; + + // To allow access to parsing code: + friend class ::icu::numparse::impl::NumberParserImpl; + friend class ::icu::numparse::impl::MultiplierParseHandler; +}; + +namespace impl { + +// Do not enclose entire StringProp with #ifndef U_HIDE_INTERNAL_API, needed for a protected field. +// And do not enclose its class boilerplate within #ifndef U_HIDE_INTERNAL_API. +/** + * Manages NumberFormatterSettings::usage()'s char* instance on the heap. + * @internal + */ +class U_I18N_API StringProp : public UMemory { + + public: + /** @internal */ + ~StringProp(); + + /** @internal */ + StringProp(const StringProp &other); + + /** @internal */ + StringProp &operator=(const StringProp &other); + +#ifndef U_HIDE_INTERNAL_API + + /** @internal */ + StringProp(StringProp &&src) noexcept; + + /** @internal */ + StringProp &operator=(StringProp &&src) noexcept; + + /** @internal */ + int16_t length() const { + return fLength; + } + + /** @internal + * Makes a copy of value. Set to "" to unset. + */ + void set(StringPiece value); + + /** @internal */ + bool isSet() const { + return fLength > 0; + } + +#endif // U_HIDE_INTERNAL_API + + private: + char *fValue; + int16_t fLength; + UErrorCode fError; + + StringProp() : fValue(nullptr), fLength(0), fError(U_ZERO_ERROR) { + } + + /** @internal (private) */ + UBool copyErrorTo(UErrorCode &status) const { + if (U_FAILURE(fError)) { + status = fError; + return true; + } + return false; + } + + // Allow NumberFormatterImpl to access fValue. + friend class impl::NumberFormatterImpl; + + // Allow skeleton generation code to access private members. + friend class impl::GeneratorHelpers; + + // Allow MacroProps/MicroProps to initialize empty instances and to call + // copyErrorTo(). + friend struct impl::MacroProps; +}; + +// Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field +/** @internal */ +class U_I18N_API SymbolsWrapper : public UMemory { + public: + /** @internal */ + SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {} + + /** @internal */ + SymbolsWrapper(const SymbolsWrapper &other); + + /** @internal */ + SymbolsWrapper &operator=(const SymbolsWrapper &other); + + /** @internal */ + SymbolsWrapper(SymbolsWrapper&& src) noexcept; + + /** @internal */ + SymbolsWrapper &operator=(SymbolsWrapper&& src) noexcept; + + /** @internal */ + ~SymbolsWrapper(); + +#ifndef U_HIDE_INTERNAL_API + + /** + * The provided object is copied, but we do not adopt it. + * @internal + */ + void setTo(const DecimalFormatSymbols &dfs); + + /** + * Adopt the provided object. + * @internal + */ + void setTo(const NumberingSystem *ns); + + /** + * Whether the object is currently holding a DecimalFormatSymbols. + * @internal + */ + bool isDecimalFormatSymbols() const; + + /** + * Whether the object is currently holding a NumberingSystem. + * @internal + */ + bool isNumberingSystem() const; + + /** + * Get the DecimalFormatSymbols pointer. No ownership change. + * @internal + */ + const DecimalFormatSymbols *getDecimalFormatSymbols() const; + + /** + * Get the NumberingSystem pointer. No ownership change. + * @internal + */ + const NumberingSystem *getNumberingSystem() const; + +#endif // U_HIDE_INTERNAL_API + + /** @internal */ + UBool copyErrorTo(UErrorCode &status) const { + if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) { + status = U_MEMORY_ALLOCATION_ERROR; + return true; + } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) { + status = U_MEMORY_ALLOCATION_ERROR; + return true; + } + return false; + } + + private: + enum SymbolsPointerType { + SYMPTR_NONE, SYMPTR_DFS, SYMPTR_NS + } fType; + + union { + const DecimalFormatSymbols *dfs; + const NumberingSystem *ns; + } fPtr; + + void doCopyFrom(const SymbolsWrapper &other); + + void doMoveFrom(SymbolsWrapper&& src); + + void doCleanup(); +}; + +// Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field +/** @internal */ +class U_I18N_API Grouper : public UMemory { + public: +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + static Grouper forStrategy(UNumberGroupingStrategy grouping); + + /** + * Resolve the values in Properties to a Grouper object. + * @internal + */ + static Grouper forProperties(const DecimalFormatProperties& properties); + + // Future: static Grouper forProperties(DecimalFormatProperties& properties); + + /** @internal */ + Grouper(int16_t grouping1, int16_t grouping2, int16_t minGrouping, UNumberGroupingStrategy strategy) + : fGrouping1(grouping1), + fGrouping2(grouping2), + fMinGrouping(minGrouping), + fStrategy(strategy) {} + + /** @internal */ + int16_t getPrimary() const; + + /** @internal */ + int16_t getSecondary() const; +#endif // U_HIDE_INTERNAL_API + + private: + /** + * The grouping sizes, with the following special values: + *
    + *
  • -1 = no grouping + *
  • -2 = needs locale data + *
  • -4 = fall back to Western grouping if not in locale + *
+ */ + int16_t fGrouping1; + int16_t fGrouping2; + + /** + * The minimum grouping size, with the following special values: + *
    + *
  • -2 = needs locale data + *
  • -3 = no less than 2 + *
+ */ + int16_t fMinGrouping; + + /** + * The UNumberGroupingStrategy that was used to create this Grouper, or UNUM_GROUPING_COUNT if this + * was not created from a UNumberGroupingStrategy. + */ + UNumberGroupingStrategy fStrategy; + + Grouper() : fGrouping1(-3) {} + + bool isBogus() const { + return fGrouping1 == -3; + } + + /** NON-CONST: mutates the current instance. */ + void setLocaleData(const impl::ParsedPatternInfo &patternInfo, const Locale& locale); + + bool groupAtPosition(int32_t position, const impl::DecimalQuantity &value) const; + + // To allow MacroProps/MicroProps to initialize empty instances: + friend struct MacroProps; + friend struct MicroProps; + friend struct SimpleMicroProps; + + // To allow NumberFormatterImpl to access isBogus() and perform other operations: + friend class NumberFormatterImpl; + friend class ::icu::number::SimpleNumberFormatter; + + // To allow NumberParserImpl to perform setLocaleData(): + friend class ::icu::numparse::impl::NumberParserImpl; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; +}; + +// Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field +/** @internal */ +class U_I18N_API Padder : public UMemory { + public: +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + static Padder none(); + + /** @internal */ + static Padder codePoints(UChar32 cp, int32_t targetWidth, UNumberFormatPadPosition position); + + /** @internal */ + static Padder forProperties(const DecimalFormatProperties& properties); +#endif // U_HIDE_INTERNAL_API + + private: + UChar32 fWidth; // -3 = error; -2 = bogus; -1 = no padding + union { + struct { + int32_t fCp; + UNumberFormatPadPosition fPosition; + } padding; + UErrorCode errorCode; + } fUnion; + + Padder(UChar32 cp, int32_t width, UNumberFormatPadPosition position); + + Padder(int32_t width); + + Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT + fUnion.errorCode = errorCode; + } + + Padder() : fWidth(-2) {} // NOLINT + + bool isBogus() const { + return fWidth == -2; + } + + UBool copyErrorTo(UErrorCode &status) const { + if (fWidth == -3) { + status = fUnion.errorCode; + return true; + } + return false; + } + + bool isValid() const { + return fWidth > 0; + } + + int32_t padAndApply(const impl::Modifier &mod1, const impl::Modifier &mod2, + FormattedStringBuilder &string, int32_t leftIndex, int32_t rightIndex, + UErrorCode &status) const; + + // To allow MacroProps/MicroProps to initialize empty instances: + friend struct MacroProps; + friend struct MicroProps; + + // To allow NumberFormatterImpl to access isBogus() and perform other operations: + friend class impl::NumberFormatterImpl; + + // To allow access to the skeleton generation code: + friend class impl::GeneratorHelpers; +}; + +// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field +/** @internal */ +struct U_I18N_API MacroProps : public UMemory { + /** @internal */ + Notation notation; + + /** @internal */ + MeasureUnit unit; // = MeasureUnit(); (the base dimensionless unit) + + /** @internal */ + MeasureUnit perUnit; // = MeasureUnit(); (the base dimensionless unit) + + /** @internal */ + Precision precision; // = Precision(); (bogus) + + /** @internal */ + UNumberFormatRoundingMode roundingMode = UNUM_ROUND_HALFEVEN; + + /** @internal */ + Grouper grouper; // = Grouper(); (bogus) + + /** @internal */ + Padder padder; // = Padder(); (bogus) + + /** @internal */ + IntegerWidth integerWidth; // = IntegerWidth(); (bogus) + + /** @internal */ + SymbolsWrapper symbols; + + // UNUM_XYZ_COUNT denotes null (bogus) values. + + /** @internal */ + UNumberUnitWidth unitWidth = UNUM_UNIT_WIDTH_COUNT; + + /** @internal */ + UNumberSignDisplay sign = UNUM_SIGN_COUNT; + + /** @internal */ + bool approximately = false; + + /** @internal */ + UNumberDecimalSeparatorDisplay decimal = UNUM_DECIMAL_SEPARATOR_COUNT; + + /** @internal */ + Scale scale; // = Scale(); (benign value) + + /** @internal */ + StringProp usage; // = StringProp(); (no usage) + + /** @internal */ + StringProp unitDisplayCase; // = StringProp(); (nominative) + + /** @internal */ + const AffixPatternProvider* affixProvider = nullptr; // no ownership + + /** @internal */ + const PluralRules* rules = nullptr; // no ownership + + /** @internal */ + int32_t threshold = kInternalDefaultThreshold; + + /** @internal */ + Locale locale; + + // NOTE: Uses default copy and move constructors. + + /** + * Check all members for errors. + * @internal + */ + bool copyErrorTo(UErrorCode &status) const { + return notation.copyErrorTo(status) || precision.copyErrorTo(status) || + padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) || + symbols.copyErrorTo(status) || scale.copyErrorTo(status) || usage.copyErrorTo(status) || + unitDisplayCase.copyErrorTo(status); + } +}; + +} // namespace impl + +#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) +// Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method +// is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation +// inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is +// fully defined. However, since each translation unit explicitly instantiates all the necessary template classes, +// they will all be passed to the linker, and the linker will still find and export all the class members. +#pragma warning(push) +#pragma warning(disable: 4661) +#endif + +/** + * An abstract base class for specifying settings related to number formatting. This class is implemented by + * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. This class is not intended for + * public subclassing. + */ +template +class U_I18N_API NumberFormatterSettings { + public: + /** + * Specifies the notation style (simple, scientific, or compact) for rendering numbers. + * + *
    + *
  • Simple notation: "12,300" + *
  • Scientific notation: "1.23E4" + *
  • Compact notation: "12K" + *
+ * + *

+ * All notation styles will be properly localized with locale data, and all notation styles are compatible with + * units, rounding precisions, and other number formatter settings. + * + *

+ * Pass this method the return value of a {@link Notation} factory method. For example: + * + *

+     * NumberFormatter::with().notation(Notation::compactShort())
+     * 
+ * + * The default is to use simple notation. + * + * @param notation + * The notation strategy to use. + * @return The fluent chain. + * @see Notation + * @stable ICU 60 + */ + Derived notation(const Notation ¬ation) const &; + + /** + * Overload of notation() for use on an rvalue reference. + * + * @param notation + * The notation strategy to use. + * @return The fluent chain. + * @see #notation + * @stable ICU 62 + */ + Derived notation(const Notation ¬ation) &&; + + /** + * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers. + * + *
    + *
  • Unit of measure: "12.3 meters" + *
  • Currency: "$12.30" + *
  • Percent: "12.3%" + *
+ * + * All units will be properly localized with locale data, and all units are compatible with notation styles, + * rounding precisions, and other number formatter settings. + * + * \note If the usage() is set, the output unit **will be changed** to + * produce localised units, according to usage, locale and unit. See + * FormattedNumber::getOutputUnit(). + * + * Pass this method any instance of {@link MeasureUnit}. For units of measure: + * + *
+     * NumberFormatter::with().unit(MeasureUnit::getMeter())
+     * NumberFormatter::with().unit(MeasureUnit::forIdentifier("foot-per-second", status))
+     * 
+ * + * Currency: + * + *
+     * NumberFormatter::with().unit(CurrencyUnit(u"USD", status))
+     * 
+ * + * Percent: + * + *
+     * NumberFormatter::with().unit(NoUnit.percent())
+     * 
+ * + * See {@link #perUnit} for information on how to format strings like "5 meters per second". + * + * The default is to render without units (equivalent to NoUnit.base()). + * + * @param unit + * The unit to render. + * @return The fluent chain. + * @see MeasureUnit + * @see Currency + * @see NoUnit + * @see #perUnit + * @stable ICU 60 + */ + Derived unit(const icu::MeasureUnit &unit) const &; + + /** + * Overload of unit() for use on an rvalue reference. + * + * @param unit + * The unit to render. + * @return The fluent chain. + * @see #unit + * @stable ICU 62 + */ + Derived unit(const icu::MeasureUnit &unit) &&; + + /** + * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory + * methods that return pointers that need ownership. + * + * Note: consider using the MeasureFormat factory methods that return by value. + * + * @param unit + * The unit to render. + * @return The fluent chain. + * @see #unit + * @see MeasureUnit + * @stable ICU 60 + */ + Derived adoptUnit(icu::MeasureUnit *unit) const &; + + /** + * Overload of adoptUnit() for use on an rvalue reference. + * + * @param unit + * The unit to render. + * @return The fluent chain. + * @see #adoptUnit + * @stable ICU 62 + */ + Derived adoptUnit(icu::MeasureUnit *unit) &&; + + /** + * Sets a unit to be used in the denominator. For example, to format "3 m/s", pass METER to the unit and SECOND to + * the perUnit. + * + * Pass this method any instance of {@link MeasureUnit}. Example: + * + *
+     * NumberFormatter::with()
+     *      .unit(MeasureUnit::getMeter())
+     *      .perUnit(MeasureUnit::getSecond())
+     * 
+ * + * The default is not to display any unit in the denominator. + * + * If a per-unit is specified without a primary unit via {@link #unit}, the behavior is undefined. + * + * @param perUnit + * The unit to render in the denominator. + * @return The fluent chain + * @see #unit + * @stable ICU 61 + */ + Derived perUnit(const icu::MeasureUnit &perUnit) const &; + + /** + * Overload of perUnit() for use on an rvalue reference. + * + * @param perUnit + * The unit to render in the denominator. + * @return The fluent chain. + * @see #perUnit + * @stable ICU 62 + */ + Derived perUnit(const icu::MeasureUnit &perUnit) &&; + + /** + * Like perUnit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory + * methods that return pointers that need ownership. + * + * Note: consider using the MeasureFormat factory methods that return by value. + * + * @param perUnit + * The unit to render in the denominator. + * @return The fluent chain. + * @see #perUnit + * @see MeasureUnit + * @stable ICU 61 + */ + Derived adoptPerUnit(icu::MeasureUnit *perUnit) const &; + + /** + * Overload of adoptPerUnit() for use on an rvalue reference. + * + * @param perUnit + * The unit to render in the denominator. + * @return The fluent chain. + * @see #adoptPerUnit + * @stable ICU 62 + */ + Derived adoptPerUnit(icu::MeasureUnit *perUnit) &&; + + /** + * Specifies the rounding precision to use when formatting numbers. + * + *
    + *
  • Round to 3 decimal places: "3.142" + *
  • Round to 3 significant figures: "3.14" + *
  • Round to the closest nickel: "3.15" + *
  • Do not perform rounding: "3.1415926..." + *
+ * + *

+ * Pass this method the return value of one of the factory methods on {@link Precision}. For example: + * + *

+     * NumberFormatter::with().precision(Precision::fixedFraction(2))
+     * 
+ * + *

+ * In most cases, the default rounding strategy is to round to 6 fraction places; i.e., + * Precision.maxFraction(6). The exceptions are if compact notation is being used, then the compact + * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency, + * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for + * details). + * + * @param precision + * The rounding precision to use. + * @return The fluent chain. + * @see Precision + * @stable ICU 62 + */ + Derived precision(const Precision& precision) const &; + + /** + * Overload of precision() for use on an rvalue reference. + * + * @param precision + * The rounding precision to use. + * @return The fluent chain. + * @see #precision + * @stable ICU 62 + */ + Derived precision(const Precision& precision) &&; + + /** + * Specifies how to determine the direction to round a number when it has more digits than fit in the + * desired precision. When formatting 1.235: + * + *

    + *
  • Ceiling rounding mode with integer precision: "2" + *
  • Half-down rounding mode with 2 fixed fraction digits: "1.23" + *
  • Half-up rounding mode with 2 fixed fraction digits: "1.24" + *
+ * + * The default is HALF_EVEN. For more information on rounding mode, see the ICU userguide here: + * + * https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes + * + * @param roundingMode The rounding mode to use. + * @return The fluent chain. + * @stable ICU 62 + */ + Derived roundingMode(UNumberFormatRoundingMode roundingMode) const &; + + /** + * Overload of roundingMode() for use on an rvalue reference. + * + * @param roundingMode The rounding mode to use. + * @return The fluent chain. + * @see #roundingMode + * @stable ICU 62 + */ + Derived roundingMode(UNumberFormatRoundingMode roundingMode) &&; + + /** + * Specifies the grouping strategy to use when formatting numbers. + * + *
    + *
  • Default grouping: "12,300" and "1,230" + *
  • Grouping with at least 2 digits: "12,300" and "1230" + *
  • No grouping: "12300" and "1230" + *
+ * + *

+ * The exact grouping widths will be chosen based on the locale. + * + *

+ * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example: + * + *

+     * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2)
+     * 
+ * + * The default is to perform grouping according to locale data; most locales, but not all locales, + * enable it by default. + * + * @param strategy + * The grouping strategy to use. + * @return The fluent chain. + * @stable ICU 61 + */ + Derived grouping(UNumberGroupingStrategy strategy) const &; + + /** + * Overload of grouping() for use on an rvalue reference. + * + * @param strategy + * The grouping strategy to use. + * @return The fluent chain. + * @see #grouping + * @stable ICU 62 + */ + Derived grouping(UNumberGroupingStrategy strategy) &&; + + /** + * Specifies the minimum and maximum number of digits to render before the decimal mark. + * + *
    + *
  • Zero minimum integer digits: ".08" + *
  • One minimum integer digit: "0.08" + *
  • Two minimum integer digits: "00.08" + *
+ * + *

+ * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example: + * + *

+     * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2))
+     * 
+ * + * The default is to have one minimum integer digit. + * + * @param style + * The integer width to use. + * @return The fluent chain. + * @see IntegerWidth + * @stable ICU 60 + */ + Derived integerWidth(const IntegerWidth &style) const &; + + /** + * Overload of integerWidth() for use on an rvalue reference. + * + * @param style + * The integer width to use. + * @return The fluent chain. + * @see #integerWidth + * @stable ICU 62 + */ + Derived integerWidth(const IntegerWidth &style) &&; + + /** + * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering + * numbers. + * + *
    + *
  • en_US symbols: "12,345.67" + *
  • fr_FR symbols: "12 345,67" + *
  • de_CH symbols: "12’345.67" + *
  • my_MY symbols: "၁၂,၃၄၅.၆၇" + *
+ * + *

+ * Pass this method an instance of {@link DecimalFormatSymbols}. For example: + * + *

+     * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status))
+     * 
+ * + *

+ * Note: DecimalFormatSymbols automatically chooses the best numbering system based on the locale. + * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar + * numbering system. + * + *

+ * Note: The instance of DecimalFormatSymbols will be copied: changes made to the symbols object + * after passing it into the fluent chain will not be seen. + * + *

+ * Note: Calling this method will override any previously specified DecimalFormatSymbols + * or NumberingSystem. + * + *

+ * The default is to choose the symbols based on the locale specified in the fluent chain. + * + * @param symbols + * The DecimalFormatSymbols to use. + * @return The fluent chain. + * @see DecimalFormatSymbols + * @stable ICU 60 + */ + Derived symbols(const DecimalFormatSymbols &symbols) const &; + + /** + * Overload of symbols() for use on an rvalue reference. + * + * @param symbols + * The DecimalFormatSymbols to use. + * @return The fluent chain. + * @see #symbols + * @stable ICU 62 + */ + Derived symbols(const DecimalFormatSymbols &symbols) &&; + + /** + * Specifies that the given numbering system should be used when fetching symbols. + * + *

    + *
  • Latin numbering system: "12,345" + *
  • Myanmar numbering system: "၁၂,၃၄၅" + *
  • Math Sans Bold numbering system: "𝟭𝟮,𝟯𝟰𝟱" + *
+ * + *

+ * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin + * alphabet numbering system (ASCII digits): + * + *

+     * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status))
+     * 
+ * + *

+ * Note: Calling this method will override any previously specified DecimalFormatSymbols + * or NumberingSystem. + * + *

+ * The default is to choose the best numbering system for the locale. + * + *

+ * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods. + * + * @param symbols + * The NumberingSystem to use. + * @return The fluent chain. + * @see NumberingSystem + * @stable ICU 60 + */ + Derived adoptSymbols(NumberingSystem *symbols) const &; + + /** + * Overload of adoptSymbols() for use on an rvalue reference. + * + * @param symbols + * The NumberingSystem to use. + * @return The fluent chain. + * @see #adoptSymbols + * @stable ICU 62 + */ + Derived adoptSymbols(NumberingSystem *symbols) &&; + + /** + * Sets the width of the unit (measure unit or currency). Most common values: + * + *

    + *
  • Short: "$12.00", "12 m" + *
  • ISO Code: "USD 12.00" + *
  • Full name: "12.00 US dollars", "12 meters" + *
+ * + *

+ * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example: + * + *

+     * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
+     * 
+ * + *

+ * The default is the SHORT width. + * + * @param width + * The width to use when rendering numbers. + * @return The fluent chain + * @see UNumberUnitWidth + * @stable ICU 60 + */ + Derived unitWidth(UNumberUnitWidth width) const &; + + /** + * Overload of unitWidth() for use on an rvalue reference. + * + * @param width + * The width to use when rendering numbers. + * @return The fluent chain. + * @see #unitWidth + * @stable ICU 62 + */ + Derived unitWidth(UNumberUnitWidth width) &&; + + /** + * Sets the plus/minus sign display strategy. Most common values: + * + *

    + *
  • Auto: "123", "-123" + *
  • Always: "+123", "-123" + *
  • Accounting: "$123", "($123)" + *
+ * + *

+ * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example: + * + *

+     * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
+     * 
+ * + *

+ * The default is AUTO sign display. + * + * @param style + * The sign display strategy to use when rendering numbers. + * @return The fluent chain + * @see UNumberSignDisplay + * @stable ICU 60 + */ + Derived sign(UNumberSignDisplay style) const &; + + /** + * Overload of sign() for use on an rvalue reference. + * + * @param style + * The sign display strategy to use when rendering numbers. + * @return The fluent chain. + * @see #sign + * @stable ICU 62 + */ + Derived sign(UNumberSignDisplay style) &&; + + /** + * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common + * values: + * + *

    + *
  • Auto: "1" + *
  • Always: "1." + *
+ * + *

+ * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example: + * + *

+     * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS)
+     * 
+ * + *

+ * The default is AUTO decimal separator display. + * + * @param style + * The decimal separator display strategy to use when rendering numbers. + * @return The fluent chain + * @see UNumberDecimalSeparatorDisplay + * @stable ICU 60 + */ + Derived decimal(UNumberDecimalSeparatorDisplay style) const &; + + /** + * Overload of decimal() for use on an rvalue reference. + * + * @param style + * The decimal separator display strategy to use when rendering numbers. + * @return The fluent chain. + * @see #decimal + * @stable ICU 62 + */ + Derived decimal(UNumberDecimalSeparatorDisplay style) &&; + + /** + * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting. + * Most common values: + * + *

    + *
  • Multiply by 100: useful for percentages. + *
  • Multiply by an arbitrary value: useful for unit conversions. + *
+ * + *

+ * Pass an element from a {@link Scale} factory method to this setter. For example: + * + *

+     * NumberFormatter::with().scale(Scale::powerOfTen(2))
+     * 
+ * + *

+ * The default is to not apply any multiplier. + * + * @param scale + * The scale to apply when rendering numbers. + * @return The fluent chain + * @stable ICU 62 + */ + Derived scale(const Scale &scale) const &; + + /** + * Overload of scale() for use on an rvalue reference. + * + * @param scale + * The scale to apply when rendering numbers. + * @return The fluent chain. + * @see #scale + * @stable ICU 62 + */ + Derived scale(const Scale &scale) &&; + + /** + * Specifies the usage for which numbers will be formatted ("person-height", + * "road", "rainfall", etc.) + * + * When a `usage` is specified, the output unit will change depending on the + * `Locale` and the unit quantity. For example, formatting length + * measurements specified in meters: + * + * `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")` + * * When formatting 0.25, the output will be "10 inches". + * * When formatting 1.50, the output will be "4 feet and 11 inches". + * + * The input unit specified via unit() determines the type of measurement + * being formatted (e.g. "length" when the unit is "foot"). The usage + * requested will be looked for only within this category of measurement + * units. + * + * The output unit can be found via FormattedNumber::getOutputUnit(). + * + * If the usage has multiple parts (e.g. "land-agriculture-grain") and does + * not match a known usage preference, the last part will be dropped + * repeatedly until a match is found (e.g. trying "land-agriculture", then + * "land"). If a match is still not found, usage will fall back to + * "default". + * + * Setting usage to an empty string clears the usage (disables usage-based + * localized formatting). + * + * Setting a usage string but not a correct input unit will result in an + * U_ILLEGAL_ARGUMENT_ERROR. + * + * When using usage, specifying rounding or precision is unnecessary. + * Specifying a precision in some manner will override the default + * formatting. + * + * @param usage A `usage` parameter from the units resource. See the + * unitPreferenceData in *source/data/misc/units.txt*, generated from + * `unitPreferenceData` in [CLDR's + * supplemental/units.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/units.xml). + * @return The fluent chain. + * @stable ICU 68 + */ + Derived usage(StringPiece usage) const &; + + /** + * Overload of usage() for use on an rvalue reference. + * + * @param usage The unit `usage`. + * @return The fluent chain. + * @stable ICU 68 + */ + Derived usage(StringPiece usage) &&; + +#ifndef U_HIDE_DRAFT_API + /** + * Specifies the DisplayOptions. For example, UDisplayOptionsGrammaticalCase specifies + * the desired case for a unit formatter's output (e.g. accusative, dative, genitive). + * + * @param displayOptions + * @return The fluent chain. + * @draft ICU 72 + */ + Derived displayOptions(const DisplayOptions &displayOptions) const &; + + /** + * Overload of displayOptions() for use on an rvalue reference. + * + * @param displayOptions + * @return The fluent chain. + * @draft ICU 72 + */ + Derived displayOptions(const DisplayOptions &displayOptions) &&; +#endif // U_HIDE_DRAFT_API + +#ifndef U_HIDE_INTERNAL_API + /** + * NOTE: Use `displayOptions` instead. This method was part of + * an internal technology preview in ICU 69, but will be removed + * in ICU 73, in favor of `displayOptions` + * + * Specifies the desired case for a unit formatter's output (e.g. + * accusative, dative, genitive). + * + * @internal + */ + Derived unitDisplayCase(StringPiece unitDisplayCase) const &; + + /** + * NOTE: Use `displayOptions` instead. This method was part of + * an internal technology preview in ICU 69, but will be removed + * in ICU 73, in favor of `displayOptions` + * + * Overload of unitDisplayCase() for use on an rvalue reference. + * + * @internal + */ + Derived unitDisplayCase(StringPiece unitDisplayCase) &&; +#endif // U_HIDE_INTERNAL_API + +#ifndef U_HIDE_INTERNAL_API + + /** + * Set the padding strategy. May be added in the future; see #13338. + * + * @internal ICU 60: This API is ICU internal only. + */ + Derived padding(const impl::Padder &padder) const &; + + /** @internal */ + Derived padding(const impl::Padder &padder) &&; + + /** + * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to + * be built right away. A threshold of 0 prevents the data structures from being built. + * + * @internal ICU 60: This API is ICU internal only. + */ + Derived threshold(int32_t threshold) const &; + + /** @internal */ + Derived threshold(int32_t threshold) &&; + + /** + * Internal fluent setter to overwrite the entire macros object. + * + * @internal ICU 60: This API is ICU internal only. + */ + Derived macros(const impl::MacroProps& macros) const &; + + /** @internal */ + Derived macros(const impl::MacroProps& macros) &&; + + /** @internal */ + Derived macros(impl::MacroProps&& macros) const &; + + /** @internal */ + Derived macros(impl::MacroProps&& macros) &&; + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Creates a skeleton string representation of this number formatter. A skeleton string is a + * locale-agnostic serialized form of a number formatter. + * + * Not all options are capable of being represented in the skeleton string; for example, a + * DecimalFormatSymbols object. If any such option is encountered, the error code is set to + * U_UNSUPPORTED_ERROR. + * + * The returned skeleton is in normalized form, such that two number formatters with equivalent + * behavior should produce the same skeleton. + * + * For more information on number skeleton strings, see: + * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html + * + * @return A number skeleton string with behavior corresponding to this number formatter. + * @stable ICU 62 + */ + UnicodeString toSkeleton(UErrorCode& status) const; + + /** + * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer + * wrapping a heap-allocated copy of the current object. + * + * This is equivalent to new-ing the move constructor with a value object + * as the argument. + * + * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped + * nullptr on failure. + * @stable ICU 64 + */ + LocalPointer clone() const &; + + /** + * Overload of clone for use on an rvalue reference. + * + * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped + * nullptr on failure. + * @stable ICU 64 + */ + LocalPointer clone() &&; + + /** + * Sets the UErrorCode if an error occurred in the fluent chain. + * Preserves older error codes in the outErrorCode. + * @return true if U_FAILURE(outErrorCode) + * @stable ICU 60 + */ + UBool copyErrorTo(UErrorCode &outErrorCode) const { + if (U_FAILURE(outErrorCode)) { + // Do not overwrite the older error code + return true; + } + fMacros.copyErrorTo(outErrorCode); + return U_FAILURE(outErrorCode); + } + + // NOTE: Uses default copy and move constructors. + + private: + impl::MacroProps fMacros; + + // Don't construct me directly! Use (Un)LocalizedNumberFormatter. + NumberFormatterSettings() = default; + + friend class LocalizedNumberFormatter; + friend class UnlocalizedNumberFormatter; + + // Give NumberRangeFormatter access to the MacroProps + friend void impl::touchRangeLocales(impl::RangeMacroProps& macros); + friend class impl::NumberRangeFormatterImpl; +}; + +// Explicit instantiations in source/i18n/number_fluent.cpp. +// (MSVC treats imports/exports of explicit instantiations differently.) +#ifndef _MSC_VER +extern template class NumberFormatterSettings; +extern template class NumberFormatterSettings; +#endif + +/** + * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified. + * + * Instances of this class are immutable and thread-safe. + * + * @see NumberFormatter + * @stable ICU 60 + */ +class U_I18N_API UnlocalizedNumberFormatter + : public NumberFormatterSettings, public UMemory { + + public: + /** + * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols, + * formats, and other data for number display. + * + * @param locale + * The locale to use when loading data for number formatting. + * @return The fluent chain. + * @stable ICU 60 + */ + LocalizedNumberFormatter locale(const icu::Locale &locale) const &; + + /** + * Overload of locale() for use on an rvalue reference. + * + * @param locale + * The locale to use when loading data for number formatting. + * @return The fluent chain. + * @see #locale + * @stable ICU 62 + */ + LocalizedNumberFormatter locale(const icu::Locale &locale) &&; + + /** + * Default constructor: puts the formatter into a valid but undefined state. + * + * @stable ICU 62 + */ + UnlocalizedNumberFormatter() = default; + + /** + * Returns a copy of this UnlocalizedNumberFormatter. + * @stable ICU 60 + */ + UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other); + + /** + * Move constructor: + * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. + * @stable ICU 62 + */ + UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) noexcept; + + /** + * Copy assignment operator. + * @stable ICU 62 + */ + UnlocalizedNumberFormatter& operator=(const UnlocalizedNumberFormatter& other); + + /** + * Move assignment operator: + * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. + * @stable ICU 62 + */ + UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) noexcept; + + private: + explicit UnlocalizedNumberFormatter(const NumberFormatterSettings& other); + + explicit UnlocalizedNumberFormatter( + NumberFormatterSettings&& src) noexcept; + + // To give the fluent setters access to this class's constructor: + friend class NumberFormatterSettings; + + // To give NumberFormatter::with() access to this class's constructor: + friend class NumberFormatter; +}; + +/** + * A NumberFormatter that has a locale associated with it; this means .format() methods are available. + * + * Instances of this class are immutable and thread-safe. + * + * @see NumberFormatter + * @stable ICU 60 + */ +class U_I18N_API LocalizedNumberFormatter + : public NumberFormatterSettings, public UMemory { + public: + /** + * Format the given integer number to a string using the settings specified in the NumberFormatter fluent + * setting chain. + * + * @param value + * The number to format. + * @param status + * Set to an ErrorCode if one occurred in the setter chain or during formatting. + * @return A FormattedNumber object; call .toString() to get the string. + * @stable ICU 60 + */ + FormattedNumber formatInt(int64_t value, UErrorCode &status) const; + + /** + * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting + * chain. + * + * @param value + * The number to format. + * @param status + * Set to an ErrorCode if one occurred in the setter chain or during formatting. + * @return A FormattedNumber object; call .toString() to get the string. + * @stable ICU 60 + */ + FormattedNumber formatDouble(double value, UErrorCode &status) const; + + /** + * Format the given decimal number to a string using the settings + * specified in the NumberFormatter fluent setting chain. + * The syntax of the unformatted number is a "numeric string" + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * @param value + * The number to format. + * @param status + * Set to an ErrorCode if one occurred in the setter chain or during formatting. + * @return A FormattedNumber object; call .toString() to get the string. + * @stable ICU 60 + */ + FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const; + +#ifndef U_HIDE_INTERNAL_API + + + /** + * @internal + */ + const DecimalFormatSymbols* getDecimalFormatSymbols() const; + + /** Internal method. + * @internal + */ + FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const; + + /** Internal method for DecimalFormat compatibility. + * @internal + */ + void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString& result, UErrorCode& status) const; + + /** + * Internal method for testing. + * @internal + */ + const impl::NumberFormatterImpl* getCompiled() const; + + /** + * Internal method for testing. + * @internal + */ + int32_t getCallCount() const; + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use + * of this number formatter with APIs that need an object of that type, such as MessageFormat. + * + * This API is not intended to be used other than for enabling API compatibility. The formatDouble, + * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format + * object returned by this method. + * + * The caller owns the returned object and must delete it when finished. + * + * @return A Format wrapping this LocalizedNumberFormatter. + * @stable ICU 62 + */ + Format* toFormat(UErrorCode& status) const; + + /** + * Default constructor: puts the formatter into a valid but undefined state. + * + * @stable ICU 62 + */ + LocalizedNumberFormatter() = default; + + /** + * Returns a copy of this LocalizedNumberFormatter. + * @stable ICU 60 + */ + LocalizedNumberFormatter(const LocalizedNumberFormatter &other); + + /** + * Move constructor: + * The source LocalizedNumberFormatter will be left in a valid but undefined state. + * @stable ICU 62 + */ + LocalizedNumberFormatter(LocalizedNumberFormatter&& src) noexcept; + + /** + * Copy assignment operator. + * @stable ICU 62 + */ + LocalizedNumberFormatter& operator=(const LocalizedNumberFormatter& other); + + /** + * Move assignment operator: + * The source LocalizedNumberFormatter will be left in a valid but undefined state. + * @stable ICU 62 + */ + LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) noexcept; + +#ifndef U_HIDE_INTERNAL_API + + /** + * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path + * for the first few calls, and compiling a more efficient data structure if called repeatedly. + * + *

+ * This function is very hot, being called in every call to the number formatting pipeline. + * + * @param results + * The results object. This method will mutate it to save the results. + * @param status + * @internal + */ + void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const; + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own. + * @stable ICU 60 + */ + ~LocalizedNumberFormatter(); + + private: + // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal + // header, and LocalPointer needs the full class definition in order to delete the instance. + const impl::NumberFormatterImpl* fCompiled {nullptr}; + char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t + + // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter + // from a DecimalFormat. + const impl::DecimalFormatWarehouse* fWarehouse {nullptr}; + + explicit LocalizedNumberFormatter(const NumberFormatterSettings& other); + + explicit LocalizedNumberFormatter(NumberFormatterSettings&& src) noexcept; + + LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale); + + LocalizedNumberFormatter(impl::MacroProps &¯os, const Locale &locale); + + void resetCompiled(); + + void lnfMoveHelper(LocalizedNumberFormatter&& src); + + void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status); + + /** + * @return true if the compiled formatter is available. + */ + bool computeCompiled(UErrorCode& status) const; + + // To give the fluent setters access to this class's constructor: + friend class NumberFormatterSettings; + friend class NumberFormatterSettings; + + // To give UnlocalizedNumberFormatter::locale() access to this class's constructor: + friend class UnlocalizedNumberFormatter; +}; + +#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) +// Warning 4661. +#pragma warning(pop) +#endif + +/** + * See the main description in numberformatter.h for documentation and examples. + * + * @stable ICU 60 + */ +class U_I18N_API NumberFormatter final { + public: + /** + * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at + * the call site. + * + * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining. + * @stable ICU 60 + */ + static UnlocalizedNumberFormatter with(); + + /** + * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call + * site. + * + * @param locale + * The locale from which to load formats and symbols for number formatting. + * @return A {@link LocalizedNumberFormatter}, to be used for chaining. + * @stable ICU 60 + */ + static LocalizedNumberFormatter withLocale(const Locale &locale); + + /** + * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based + * on a given number skeleton string. + * + * It is possible for an error to occur while parsing. See the overload of this method if you are + * interested in the location of a possible parse error. + * + * For more information on number skeleton strings, see: + * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html + * + * @param skeleton + * The skeleton string off of which to base this NumberFormatter. + * @param status + * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. + * @return An UnlocalizedNumberFormatter, to be used for chaining. + * @stable ICU 62 + */ + static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status); + + /** + * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based + * on a given number skeleton string. + * + * If an error occurs while parsing the skeleton string, the offset into the skeleton string at + * which the error occurred will be saved into the UParseError, if provided. + * + * For more information on number skeleton strings, see: + * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html + * + * @param skeleton + * The skeleton string off of which to base this NumberFormatter. + * @param perror + * A parse error struct populated if an error occurs when parsing. + * If no error occurs, perror.offset will be set to -1. + * @param status + * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. + * @return An UnlocalizedNumberFormatter, to be used for chaining. + * @stable ICU 64 + */ + static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, + UParseError& perror, UErrorCode& status); + + /** + * Use factory methods instead of the constructor to create a NumberFormatter. + */ + NumberFormatter() = delete; +}; + +} // namespace number +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __NUMBERFORMATTER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberrangeformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberrangeformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..8ca20f31d714c90ec409ebd1bf56189967650bc2 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numberrangeformatter.h @@ -0,0 +1,768 @@ +// © 2018 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __NUMBERRANGEFORMATTER_H__ +#define __NUMBERRANGEFORMATTER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include +#include "unicode/appendable.h" +#include "unicode/fieldpos.h" +#include "unicode/formattedvalue.h" +#include "unicode/fpositer.h" +#include "unicode/numberformatter.h" +#include "unicode/unumberrangeformatter.h" + +/** + * \file + * \brief C++ API: Library for localized formatting of number, currency, and unit ranges. + * + * The main entrypoint to the formatting of ranges of numbers, including currencies and other units of measurement. + *

+ * Usage example: + *

+ *

+ * NumberRangeFormatter::with()
+ *     .identityFallback(UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE)
+ *     .numberFormatterFirst(NumberFormatter::with().adoptUnit(MeasureUnit::createMeter()))
+ *     .numberFormatterSecond(NumberFormatter::with().adoptUnit(MeasureUnit::createKilometer()))
+ *     .locale("en-GB")
+ *     .formatFormattableRange(750, 1.2, status)
+ *     .toString(status);
+ * // => "750 m - 1.2 km"
+ * 
+ *

+ * Like NumberFormatter, NumberRangeFormatter instances (i.e., LocalizedNumberRangeFormatter + * and UnlocalizedNumberRangeFormatter) are immutable and thread-safe. This API is based on the + * fluent design pattern popularized by libraries such as Google's Guava. + * + * @author Shane Carr + */ + + +U_NAMESPACE_BEGIN + +// Forward declarations: +class PluralRules; + +namespace number { // icu::number + +// Forward declarations: +class UnlocalizedNumberRangeFormatter; +class LocalizedNumberRangeFormatter; +class FormattedNumberRange; + +namespace impl { + +// Forward declarations: +struct RangeMacroProps; +class DecimalQuantity; +class UFormattedNumberRangeData; +class NumberRangeFormatterImpl; +struct UFormattedNumberRangeImpl; + +} // namespace impl + +/** + * \cond + * Export an explicit template instantiation. See datefmt.h + * (When building DLLs for Windows this is required.) + */ +#if U_PLATFORM == U_PF_WINDOWS && !defined(U_IN_DOXYGEN) && !defined(U_STATIC_IMPLEMENTATION) +} // namespace icu::number +U_NAMESPACE_END + +template struct U_I18N_API std::atomic< U_NAMESPACE_QUALIFIER number::impl::NumberRangeFormatterImpl*>; + +U_NAMESPACE_BEGIN +namespace number { // icu::number +#endif +/** \endcond */ + +// Other helper classes would go here, but there are none. + +namespace impl { // icu::number::impl + +// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field +/** @internal */ +struct U_I18N_API RangeMacroProps : public UMemory { + /** @internal */ + UnlocalizedNumberFormatter formatter1; // = NumberFormatter::with(); + + /** @internal */ + UnlocalizedNumberFormatter formatter2; // = NumberFormatter::with(); + + /** @internal */ + bool singleFormatter = true; + + /** @internal */ + UNumberRangeCollapse collapse = UNUM_RANGE_COLLAPSE_AUTO; + + /** @internal */ + UNumberRangeIdentityFallback identityFallback = UNUM_IDENTITY_FALLBACK_APPROXIMATELY; + + /** @internal */ + Locale locale; + + // NOTE: Uses default copy and move constructors. + + /** + * Check all members for errors. + * @internal + */ + bool copyErrorTo(UErrorCode &status) const { + return formatter1.copyErrorTo(status) || formatter2.copyErrorTo(status); + } +}; + +} // namespace impl + +/** + * An abstract base class for specifying settings related to number formatting. This class is implemented by + * {@link UnlocalizedNumberRangeFormatter} and {@link LocalizedNumberRangeFormatter}. This class is not intended for + * public subclassing. + */ +template +class U_I18N_API NumberRangeFormatterSettings { + public: + /** + * Sets the NumberFormatter instance to use for the numbers in the range. The same formatter is applied to both + * sides of the range. + *

+ * The NumberFormatter instances must not have a locale applied yet; the locale specified on the + * NumberRangeFormatter will be used. + * + * @param formatter + * The formatter to use for both numbers in the range. + * @return The fluent chain. + * @stable ICU 63 + */ + Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) const &; + + /** + * Overload of numberFormatterBoth() for use on an rvalue reference. + * + * @param formatter + * The formatter to use for both numbers in the range. + * @return The fluent chain. + * @see #numberFormatterBoth + * @stable ICU 63 + */ + Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) &&; + + /** + * Overload of numberFormatterBoth() for use on an rvalue reference. + * + * @param formatter + * The formatter to use for both numbers in the range. + * @return The fluent chain. + * @see #numberFormatterBoth + * @stable ICU 63 + */ + Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) const &; + + /** + * Overload of numberFormatterBoth() for use on an rvalue reference. + * + * @param formatter + * The formatter to use for both numbers in the range. + * @return The fluent chain. + * @see #numberFormatterBoth + * @stable ICU 63 + */ + Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) &&; + + /** + * Sets the NumberFormatter instance to use for the first number in the range. + *

+ * The NumberFormatter instances must not have a locale applied yet; the locale specified on the + * NumberRangeFormatter will be used. + * + * @param formatterFirst + * The formatter to use for the first number in the range. + * @return The fluent chain. + * @stable ICU 63 + */ + Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) const &; + + /** + * Overload of numberFormatterFirst() for use on an rvalue reference. + * + * @param formatterFirst + * The formatter to use for the first number in the range. + * @return The fluent chain. + * @see #numberFormatterFirst + * @stable ICU 63 + */ + Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) &&; + + /** + * Overload of numberFormatterFirst() for use on an rvalue reference. + * + * @param formatterFirst + * The formatter to use for the first number in the range. + * @return The fluent chain. + * @see #numberFormatterFirst + * @stable ICU 63 + */ + Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) const &; + + /** + * Overload of numberFormatterFirst() for use on an rvalue reference. + * + * @param formatterFirst + * The formatter to use for the first number in the range. + * @return The fluent chain. + * @see #numberFormatterFirst + * @stable ICU 63 + */ + Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) &&; + + /** + * Sets the NumberFormatter instance to use for the second number in the range. + *

+ * The NumberFormatter instances must not have a locale applied yet; the locale specified on the + * NumberRangeFormatter will be used. + * + * @param formatterSecond + * The formatter to use for the second number in the range. + * @return The fluent chain. + * @stable ICU 63 + */ + Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) const &; + + /** + * Overload of numberFormatterSecond() for use on an rvalue reference. + * + * @param formatterSecond + * The formatter to use for the second number in the range. + * @return The fluent chain. + * @see #numberFormatterSecond + * @stable ICU 63 + */ + Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) &&; + + /** + * Overload of numberFormatterSecond() for use on an rvalue reference. + * + * @param formatterSecond + * The formatter to use for the second number in the range. + * @return The fluent chain. + * @see #numberFormatterSecond + * @stable ICU 63 + */ + Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) const &; + + /** + * Overload of numberFormatterSecond() for use on an rvalue reference. + * + * @param formatterSecond + * The formatter to use for the second number in the range. + * @return The fluent chain. + * @see #numberFormatterSecond + * @stable ICU 63 + */ + Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) &&; + + /** + * Sets the aggressiveness of "collapsing" fields across the range separator. Possible values: + *

+ *

    + *
  • ALL: "3-5K miles"
  • + *
  • UNIT: "3K - 5K miles"
  • + *
  • NONE: "3K miles - 5K miles"
  • + *
  • AUTO: usually UNIT or NONE, depending on the locale and formatter settings
  • + *
+ *

+ * The default value is AUTO. + * + * @param collapse + * The collapsing strategy to use for this range. + * @return The fluent chain. + * @stable ICU 63 + */ + Derived collapse(UNumberRangeCollapse collapse) const &; + + /** + * Overload of collapse() for use on an rvalue reference. + * + * @param collapse + * The collapsing strategy to use for this range. + * @return The fluent chain. + * @see #collapse + * @stable ICU 63 + */ + Derived collapse(UNumberRangeCollapse collapse) &&; + + /** + * Sets the behavior when the two sides of the range are the same. This could happen if the same two numbers are + * passed to the formatFormattableRange function, or if different numbers are passed to the function but they + * become the same after rounding rules are applied. Possible values: + *

+ *

    + *
  • SINGLE_VALUE: "5 miles"
  • + *
  • APPROXIMATELY_OR_SINGLE_VALUE: "~5 miles" or "5 miles", depending on whether the number was the same before + * rounding was applied
  • + *
  • APPROXIMATELY: "~5 miles"
  • + *
  • RANGE: "5-5 miles" (with collapse=UNIT)
  • + *
+ *

+ * The default value is APPROXIMATELY. + * + * @param identityFallback + * The strategy to use when formatting two numbers that end up being the same. + * @return The fluent chain. + * @stable ICU 63 + */ + Derived identityFallback(UNumberRangeIdentityFallback identityFallback) const &; + + /** + * Overload of identityFallback() for use on an rvalue reference. + * + * @param identityFallback + * The strategy to use when formatting two numbers that end up being the same. + * @return The fluent chain. + * @see #identityFallback + * @stable ICU 63 + */ + Derived identityFallback(UNumberRangeIdentityFallback identityFallback) &&; + + /** + * Returns the current (Un)LocalizedNumberRangeFormatter as a LocalPointer + * wrapping a heap-allocated copy of the current object. + * + * This is equivalent to new-ing the move constructor with a value object + * as the argument. + * + * @return A wrapped (Un)LocalizedNumberRangeFormatter pointer, or a wrapped + * nullptr on failure. + * @stable ICU 64 + */ + LocalPointer clone() const &; + + /** + * Overload of clone for use on an rvalue reference. + * + * @return A wrapped (Un)LocalizedNumberRangeFormatter pointer, or a wrapped + * nullptr on failure. + * @stable ICU 64 + */ + LocalPointer clone() &&; + + /** + * Sets the UErrorCode if an error occurred in the fluent chain. + * Preserves older error codes in the outErrorCode. + * @return true if U_FAILURE(outErrorCode) + * @stable ICU 63 + */ + UBool copyErrorTo(UErrorCode &outErrorCode) const { + if (U_FAILURE(outErrorCode)) { + // Do not overwrite the older error code + return true; + } + fMacros.copyErrorTo(outErrorCode); + return U_FAILURE(outErrorCode); + } + + // NOTE: Uses default copy and move constructors. + + private: + impl::RangeMacroProps fMacros; + + // Don't construct me directly! Use (Un)LocalizedNumberFormatter. + NumberRangeFormatterSettings() = default; + + friend class LocalizedNumberRangeFormatter; + friend class UnlocalizedNumberRangeFormatter; +}; + +// Explicit instantiations in source/i18n/numrange_fluent.cpp. +// (MSVC treats imports/exports of explicit instantiations differently.) +#ifndef _MSC_VER +extern template class NumberRangeFormatterSettings; +extern template class NumberRangeFormatterSettings; +#endif + +/** + * A NumberRangeFormatter that does not yet have a locale. In order to format, a locale must be specified. + * + * Instances of this class are immutable and thread-safe. + * + * @see NumberRangeFormatter + * @stable ICU 63 + */ +class U_I18N_API UnlocalizedNumberRangeFormatter + : public NumberRangeFormatterSettings, public UMemory { + + public: + /** + * Associate the given locale with the number range formatter. The locale is used for picking the + * appropriate symbols, formats, and other data for number display. + * + * @param locale + * The locale to use when loading data for number formatting. + * @return The fluent chain. + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter locale(const icu::Locale &locale) const &; + + /** + * Overload of locale() for use on an rvalue reference. + * + * @param locale + * The locale to use when loading data for number formatting. + * @return The fluent chain. + * @see #locale + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter locale(const icu::Locale &locale) &&; + + /** + * Default constructor: puts the formatter into a valid but undefined state. + * + * @stable ICU 63 + */ + UnlocalizedNumberRangeFormatter() = default; + + /** + * Returns a copy of this UnlocalizedNumberRangeFormatter. + * @stable ICU 63 + */ + UnlocalizedNumberRangeFormatter(const UnlocalizedNumberRangeFormatter &other); + + /** + * Move constructor: + * The source UnlocalizedNumberRangeFormatter will be left in a valid but undefined state. + * @stable ICU 63 + */ + UnlocalizedNumberRangeFormatter(UnlocalizedNumberRangeFormatter&& src) noexcept; + + /** + * Copy assignment operator. + * @stable ICU 63 + */ + UnlocalizedNumberRangeFormatter& operator=(const UnlocalizedNumberRangeFormatter& other); + + /** + * Move assignment operator: + * The source UnlocalizedNumberRangeFormatter will be left in a valid but undefined state. + * @stable ICU 63 + */ + UnlocalizedNumberRangeFormatter& operator=(UnlocalizedNumberRangeFormatter&& src) noexcept; + + private: + explicit UnlocalizedNumberRangeFormatter( + const NumberRangeFormatterSettings& other); + + explicit UnlocalizedNumberRangeFormatter( + NumberRangeFormatterSettings&& src) noexcept; + + // To give the fluent setters access to this class's constructor: + friend class NumberRangeFormatterSettings; + + // To give NumberRangeFormatter::with() access to this class's constructor: + friend class NumberRangeFormatter; +}; + +/** + * A NumberRangeFormatter that has a locale associated with it; this means .formatRange() methods are available. + * + * Instances of this class are immutable and thread-safe. + * + * @see NumberFormatter + * @stable ICU 63 + */ +class U_I18N_API LocalizedNumberRangeFormatter + : public NumberRangeFormatterSettings, public UMemory { + public: + /** + * Format the given Formattables to a string using the settings specified in the NumberRangeFormatter fluent setting + * chain. + * + * @param first + * The first number in the range, usually to the left in LTR locales. + * @param second + * The second number in the range, usually to the right in LTR locales. + * @param status + * Set if an error occurs while formatting. + * @return A FormattedNumberRange object; call .toString() to get the string. + * @stable ICU 63 + */ + FormattedNumberRange formatFormattableRange( + const Formattable& first, const Formattable& second, UErrorCode& status) const; + + /** + * Default constructor: puts the formatter into a valid but undefined state. + * + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter() = default; + + /** + * Returns a copy of this LocalizedNumberRangeFormatter. + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter(const LocalizedNumberRangeFormatter &other); + + /** + * Move constructor: + * The source LocalizedNumberRangeFormatter will be left in a valid but undefined state. + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter(LocalizedNumberRangeFormatter&& src) noexcept; + + /** + * Copy assignment operator. + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter& operator=(const LocalizedNumberRangeFormatter& other); + + /** + * Move assignment operator: + * The source LocalizedNumberRangeFormatter will be left in a valid but undefined state. + * @stable ICU 63 + */ + LocalizedNumberRangeFormatter& operator=(LocalizedNumberRangeFormatter&& src) noexcept; + +#ifndef U_HIDE_INTERNAL_API + + /** + * @param results + * The results object. This method will mutate it to save the results. + * @param equalBeforeRounding + * Whether the number was equal before copying it into a DecimalQuantity. + * Used for determining the identity fallback behavior. + * @param status + * Set if an error occurs while formatting. + * @internal + */ + void formatImpl(impl::UFormattedNumberRangeData& results, bool equalBeforeRounding, + UErrorCode& status) const; + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Destruct this LocalizedNumberRangeFormatter, cleaning up any memory it might own. + * @stable ICU 63 + */ + ~LocalizedNumberRangeFormatter(); + + private: + std::atomic fAtomicFormatter = {}; + + const impl::NumberRangeFormatterImpl* getFormatter(UErrorCode& stauts) const; + + explicit LocalizedNumberRangeFormatter( + const NumberRangeFormatterSettings& other); + + explicit LocalizedNumberRangeFormatter( + NumberRangeFormatterSettings&& src) noexcept; + + LocalizedNumberRangeFormatter(const impl::RangeMacroProps ¯os, const Locale &locale); + + LocalizedNumberRangeFormatter(impl::RangeMacroProps &¯os, const Locale &locale); + + // To give the fluent setters access to this class's constructor: + friend class NumberRangeFormatterSettings; + friend class NumberRangeFormatterSettings; + + // To give UnlocalizedNumberRangeFormatter::locale() access to this class's constructor: + friend class UnlocalizedNumberRangeFormatter; +}; + +/** + * The result of a number range formatting operation. This class allows the result to be exported in several data types, + * including a UnicodeString and a FieldPositionIterator. + * + * Instances of this class are immutable and thread-safe. + * + * @stable ICU 63 + */ +class U_I18N_API FormattedNumberRange : public UMemory, public FormattedValue { + public: + // Copybrief: this method is older than the parent method + /** + * @copybrief FormattedValue::toString() + * + * For more information, see FormattedValue::toString() + * + * @stable ICU 63 + */ + UnicodeString toString(UErrorCode& status) const override; + + // Copydoc: this method is new in ICU 64 + /** @copydoc FormattedValue::toTempString() */ + UnicodeString toTempString(UErrorCode& status) const override; + + // Copybrief: this method is older than the parent method + /** + * @copybrief FormattedValue::appendTo() + * + * For more information, see FormattedValue::appendTo() + * + * @stable ICU 63 + */ + Appendable &appendTo(Appendable &appendable, UErrorCode& status) const override; + + // Copydoc: this method is new in ICU 64 + /** @copydoc FormattedValue::nextPosition() */ + UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; + + /** + * Extracts the formatted range as a pair of decimal numbers. This endpoint + * is useful for obtaining the exact number being printed after scaling + * and rounding have been applied by the number range formatting pipeline. + * + * The syntax of the unformatted numbers is a "numeric string" + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * Example C++17 call site: + * + * auto [ first, second ] = range.getDecimalNumbers(status); + * + * @tparam StringClass A string class compatible with StringByteSink; + * for example, std::string. + * @param status Set if an error occurs. + * @return A pair of StringClasses containing the numeric strings. + * @stable ICU 68 + */ + template + inline std::pair getDecimalNumbers(UErrorCode& status) const; + + /** + * Returns whether the pair of numbers was successfully formatted as a range or whether an identity fallback was + * used. For example, if the first and second number were the same either before or after rounding occurred, an + * identity fallback was used. + * + * @return An indication the resulting identity situation in the formatted number range. + * @stable ICU 63 + * @see UNumberRangeIdentityFallback + */ + UNumberRangeIdentityResult getIdentityResult(UErrorCode& status) const; + + /** + * Default constructor; makes an empty FormattedNumberRange. + * @stable ICU 70 + */ + FormattedNumberRange() + : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} + + /** + * Copying not supported; use move constructor instead. + */ + FormattedNumberRange(const FormattedNumberRange&) = delete; + + /** + * Copying not supported; use move assignment instead. + */ + FormattedNumberRange& operator=(const FormattedNumberRange&) = delete; + + /** + * Move constructor: + * Leaves the source FormattedNumberRange in an undefined state. + * @stable ICU 63 + */ + FormattedNumberRange(FormattedNumberRange&& src) noexcept; + + /** + * Move assignment: + * Leaves the source FormattedNumberRange in an undefined state. + * @stable ICU 63 + */ + FormattedNumberRange& operator=(FormattedNumberRange&& src) noexcept; + + /** + * Destruct an instance of FormattedNumberRange, cleaning up any memory it might own. + * @stable ICU 63 + */ + ~FormattedNumberRange(); + + private: + // Can't use LocalPointer because UFormattedNumberRangeData is forward-declared + const impl::UFormattedNumberRangeData *fData; + + // Error code for the terminal methods + UErrorCode fErrorCode; + + /** + * Internal constructor from data type. Adopts the data pointer. + */ + explicit FormattedNumberRange(impl::UFormattedNumberRangeData *results) + : fData(results), fErrorCode(U_ZERO_ERROR) {} + + explicit FormattedNumberRange(UErrorCode errorCode) + : fData(nullptr), fErrorCode(errorCode) {} + + void getDecimalNumbers(ByteSink& sink1, ByteSink& sink2, UErrorCode& status) const; + + const impl::UFormattedNumberRangeData* getData(UErrorCode& status) const; + + // To allow PluralRules to access the underlying data + friend class ::icu::PluralRules; + + // To give LocalizedNumberRangeFormatter format methods access to this class's constructor: + friend class LocalizedNumberRangeFormatter; + + // To give C API access to internals + friend struct impl::UFormattedNumberRangeImpl; +}; + +// inline impl of @stable ICU 68 method +template +std::pair FormattedNumberRange::getDecimalNumbers(UErrorCode& status) const { + StringClass str1; + StringClass str2; + StringByteSink sink1(&str1); + StringByteSink sink2(&str2); + getDecimalNumbers(sink1, sink2, status); + return std::make_pair(str1, str2); +} + +/** + * See the main description in numberrangeformatter.h for documentation and examples. + * + * @stable ICU 63 + */ +class U_I18N_API NumberRangeFormatter final { + public: + /** + * Call this method at the beginning of a NumberRangeFormatter fluent chain in which the locale is not currently + * known at the call site. + * + * @return An {@link UnlocalizedNumberRangeFormatter}, to be used for chaining. + * @stable ICU 63 + */ + static UnlocalizedNumberRangeFormatter with(); + + /** + * Call this method at the beginning of a NumberRangeFormatter fluent chain in which the locale is known at the call + * site. + * + * @param locale + * The locale from which to load formats and symbols for number range formatting. + * @return A {@link LocalizedNumberRangeFormatter}, to be used for chaining. + * @stable ICU 63 + */ + static LocalizedNumberRangeFormatter withLocale(const Locale &locale); + + /** + * Use factory methods instead of the constructor to create a NumberFormatter. + */ + NumberRangeFormatter() = delete; +}; + +} // namespace number +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __NUMBERRANGEFORMATTER_H__ + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..e1aa3092761dc4ad0e472f0f721dbe82bc9c62e2 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numfmt.h @@ -0,0 +1,1288 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 1997-2016, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************** +* +* File NUMFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 03/18/97 clhuang Updated per C++ implementation. +* 04/17/97 aliu Changed DigitCount to int per code review. +* 07/20/98 stephen JDK 1.2 sync up. Added scientific support. +* Changed naming conventions to match C++ guidelines +* Deprecated Java style constants (eg, INTEGER_FIELD) +******************************************************************************** +*/ + +#ifndef NUMFMT_H +#define NUMFMT_H + + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Compatibility APIs for number formatting. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" +#include "unicode/format.h" +#include "unicode/unum.h" // UNumberFormatStyle +#include "unicode/locid.h" +#include "unicode/stringpiece.h" +#include "unicode/curramt.h" +#include "unicode/udisplaycontext.h" + +class NumberFormatTest; + +U_NAMESPACE_BEGIN + +class SharedNumberFormat; + +#if !UCONFIG_NO_SERVICE +class NumberFormatFactory; +class StringEnumeration; +#endif + +/** + *

IMPORTANT: New users are strongly encouraged to see if + * numberformatter.h fits their use case. Although not deprecated, this header + * is provided for backwards compatibility only. + * + * Abstract base class for all number formats. Provides interface for + * formatting and parsing a number. Also provides methods for + * determining which locales have number formats, and what their names + * are. + * + * \headerfile unicode/numfmt.h "unicode/numfmt.h" + *

+ * NumberFormat helps you to format and parse numbers for any locale. + * Your code can be completely independent of the locale conventions + * for decimal points, thousands-separators, or even the particular + * decimal digits used, or whether the number format is even decimal. + *

+ * To format a number for the current Locale, use one of the static + * factory methods: + * \code + * #include + * #include "unicode/numfmt.h" + * #include "unicode/unistr.h" + * #include "unicode/ustream.h" + * using namespace std; + * + * int main() { + * double myNumber = 7.0; + * UnicodeString myString; + * UErrorCode success = U_ZERO_ERROR; + * NumberFormat* nf = NumberFormat::createInstance(success); + * nf->format(myNumber, myString); + * cout << " Example 1: " << myString << endl; + * } + * \endcode + * Note that there are additional factory methods within subclasses of + * NumberFormat. + *

+ * If you are formatting multiple numbers, it is more efficient to get + * the format and use it multiple times so that the system doesn't + * have to fetch the information about the local language and country + * conventions multiple times. + * \code + * UnicodeString myString; + * UErrorCode success = U_ZERO_ERROR; + * NumberFormat *nf = NumberFormat::createInstance( success ); + * for (int32_t number: {123, 3333, -1234567}) { + * nf->format(number, myString); + * myString += "; "; + * } + * cout << " Example 2: " << myString << endl; + * \endcode + * To format a number for a different Locale, specify it in the + * call to \c createInstance(). + * \code + * nf = NumberFormat::createInstance(Locale::getFrench(), success); + * \endcode + * You can use a \c NumberFormat to parse also. + * \code + * UErrorCode success; + * Formattable result(-999); // initialized with error code + * nf->parse(myString, result, success); + * \endcode + * Use \c createInstance() to get the normal number format for a \c Locale. + * There are other static factory methods available. Use \c createCurrencyInstance() + * to get the currency number format for that country. Use \c createPercentInstance() + * to get a format for displaying percentages. With this format, a + * fraction from 0.53 is displayed as 53%. + *

+ * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance(). + * For example, use\n + * \c createInstance(locale, UNUM_DECIMAL, errorCode) to get the normal number format,\n + * \c createInstance(locale, UNUM_PERCENT, errorCode) to get a format for displaying percentage,\n + * \c createInstance(locale, UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,\n + * \c createInstance(locale, UNUM_CURRENCY, errorCode) to get the currency number format, + * in which the currency is represented by its symbol, for example, "$3.00".\n + * \c createInstance(locale, UNUM_CURRENCY_ISO, errorCode) to get the currency number format, + * in which the currency is represented by its ISO code, for example "USD3.00".\n + * \c createInstance(locale, UNUM_CURRENCY_PLURAL, errorCode) to get the currency number format, + * in which the currency is represented by its full name in plural format, + * for example, "3.00 US dollars" or "1.00 US dollar". + *

+ * You can also control the display of numbers with such methods as + * \c getMinimumFractionDigits(). If you want even more control over the + * format or parsing, or want to give your users more control, you can + * try dynamic_casting the \c NumberFormat you get from the factory methods to a + * \c DecimalFormat. This will work for the vast majority of + * countries; just remember to test for nullptr in case you + * encounter an unusual one. + *

+ * You can also use forms of the parse and format methods with + * \c ParsePosition and \c FieldPosition to allow you to: + *

    + *
  • (a) progressively parse through pieces of a string. + *
  • (b) align the decimal point and other areas. + *
+ * For example, you can align numbers in two ways. + *

+ * If you are using a monospaced font with spacing for alignment, you + * can pass the \c FieldPosition in your format call, with field = + * \c UNUM_INTEGER_FIELD. On output, \c getEndIndex will be set to the offset + * between the last character of the integer and the decimal. Add + * (desiredSpaceCount - getEndIndex) spaces at the front of the + * string. + *

+ * If you are using proportional fonts, instead of padding with + * spaces, measure the width of the string in pixels from the start to + * getEndIndex. Then move the pen by (desiredPixelWidth - + * widthToAlignmentPoint) before drawing the text. It also works + * where there is no decimal, but possibly additional characters at + * the end, e.g. with parentheses in negative numbers: "(12)" for -12. + *

+ * User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + * + * @stable ICU 2.0 + */ +class U_I18N_API NumberFormat : public Format { +public: + /** + * Rounding mode. + * + *

+ * For more detail on rounding modes, see: + * https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes + * + * @stable ICU 2.4 + */ + enum ERoundingMode { + kRoundCeiling, /**< Round towards positive infinity */ + kRoundFloor, /**< Round towards negative infinity */ + kRoundDown, /**< Round towards zero */ + kRoundUp, /**< Round away from zero */ + kRoundHalfEven, /**< Round towards the nearest integer, or + towards the nearest even integer if equidistant */ + kRoundHalfDown, /**< Round towards the nearest integer, or + towards zero if equidistant */ + kRoundHalfUp, /**< Round towards the nearest integer, or + away from zero if equidistant */ + /** + * Return U_FORMAT_INEXACT_ERROR if number does not format exactly. + * @stable ICU 4.8 + */ + kRoundUnnecessary, +#ifndef U_HIDE_DRAFT_API + /** + * Rounds ties toward the odd number. + * @draft ICU 73 + */ + kRoundHalfOdd, + /** + * Rounds ties toward +∞. + * @draft ICU 73 + */ + kRoundHalfCeiling, + /** + * Rounds ties toward -∞. + * @draft ICU 73 + */ + kRoundHalfFloor, +#endif /* U_HIDE_DRAFT_API */ + }; + + /** + * Alignment Field constants used to construct a FieldPosition object. + * Signifies that the position of the integer part or fraction part of + * a formatted number should be returned. + * + * Note: as of ICU 4.4, the values in this enum have been extended to + * support identification of all number format fields, not just those + * pertaining to alignment. + * + * These constants are provided for backwards compatibility only. + * Please use the C style constants defined in the header file unum.h. + * + * @see FieldPosition + * @stable ICU 2.0 + */ + enum EAlignmentFields { + /** @stable ICU 2.0 */ + kIntegerField = UNUM_INTEGER_FIELD, + /** @stable ICU 2.0 */ + kFractionField = UNUM_FRACTION_FIELD, + /** @stable ICU 2.0 */ + kDecimalSeparatorField = UNUM_DECIMAL_SEPARATOR_FIELD, + /** @stable ICU 2.0 */ + kExponentSymbolField = UNUM_EXPONENT_SYMBOL_FIELD, + /** @stable ICU 2.0 */ + kExponentSignField = UNUM_EXPONENT_SIGN_FIELD, + /** @stable ICU 2.0 */ + kExponentField = UNUM_EXPONENT_FIELD, + /** @stable ICU 2.0 */ + kGroupingSeparatorField = UNUM_GROUPING_SEPARATOR_FIELD, + /** @stable ICU 2.0 */ + kCurrencyField = UNUM_CURRENCY_FIELD, + /** @stable ICU 2.0 */ + kPercentField = UNUM_PERCENT_FIELD, + /** @stable ICU 2.0 */ + kPermillField = UNUM_PERMILL_FIELD, + /** @stable ICU 2.0 */ + kSignField = UNUM_SIGN_FIELD, + /** @stable ICU 64 */ + kMeasureUnitField = UNUM_MEASURE_UNIT_FIELD, + /** @stable ICU 64 */ + kCompactField = UNUM_COMPACT_FIELD, + + /** + * These constants are provided for backwards compatibility only. + * Please use the constants defined in the header file unum.h. + */ + /** @stable ICU 2.0 */ + INTEGER_FIELD = UNUM_INTEGER_FIELD, + /** @stable ICU 2.0 */ + FRACTION_FIELD = UNUM_FRACTION_FIELD + }; + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~NumberFormat(); + + /** + * Clones this object polymorphically. + * The caller owns the result and should delete it when done. + * @return clone, or nullptr if an error occurred + * @stable ICU 2.0 + */ + virtual NumberFormat* clone() const override = 0; + + /** + * Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.0 + */ + virtual bool operator==(const Format& other) const override; + + + using Format::format; + + /** + * Format an object to produce a string. This method handles + * Formattable objects with numeric types. If the Formattable + * object type is not a numeric type, then it returns a failing + * UErrorCode. + * + * @param obj The object to format. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; + + /** + * Format an object to produce a string. This method handles + * Formattable objects with numeric types. If the Formattable + * object type is not a numeric type, then it returns a failing + * UErrorCode. + * + * @param obj The object to format. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Can be + * nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const override; + + /** + * Parse a string to produce an object. This methods handles + * parsing of numeric strings into Formattable objects with numeric + * types. + *

+ * Before calling, set parse_pos.index to the offset you want to + * start parsing at in the source. After calling, parse_pos.index + * indicates the position after the successfully parsed text. If + * an error occurs, parse_pos.index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with successful + * parse), while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @return A newly created Formattable* object, or nullptr + * on failure. The caller owns this and should + * delete it when done. + * @stable ICU 2.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const override; + + /** + * Format a double number. These methods call the NumberFormat + * pure virtual format() methods with the default FieldPosition. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format( double number, + UnicodeString& appendTo) const; + + /** + * Format a long number. These methods call the NumberFormat + * pure virtual format() methods with the default FieldPosition. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + UnicodeString& format( int32_t number, + UnicodeString& appendTo) const; + + /** + * Format an int64 number. These methods call the NumberFormat + * pure virtual format() methods with the default FieldPosition. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.8 + */ + UnicodeString& format( int64_t number, + UnicodeString& appendTo) const; + + /** + * Format a double number. Concrete subclasses must implement + * these pure virtual methods. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(double number, + UnicodeString& appendTo, + FieldPosition& pos) const = 0; + /** + * Format a double number. By default, the parent function simply + * calls the base class and does not return an error status. + * Therefore, the status may be ignored in some subclasses. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status error status + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(double number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode &status) const; + /** + * Format a double number. Subclasses must implement + * this method. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(double number, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Format a long number. Concrete subclasses must implement + * these pure virtual methods. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(int32_t number, + UnicodeString& appendTo, + FieldPosition& pos) const = 0; + + /** + * Format a long number. Concrete subclasses may override + * this function to provide status return. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status the output status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(int32_t number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode &status) const; + + /** + * Format an int32 number. Subclasses must implement + * this method. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(int32_t number, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + /** + * Format an int64 number. (Not abstract to retain compatibility + * with earlier releases, however subclasses should override this + * method as it just delegates to format(int32_t number...); + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.8 + */ + virtual UnicodeString& format(int64_t number, + UnicodeString& appendTo, + FieldPosition& pos) const; + + /** + * Format an int64 number. (Not abstract to retain compatibility + * with earlier releases, however subclasses should override this + * method as it just delegates to format(int32_t number...); + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(int64_t number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + /** + * Format an int64 number. Subclasses must implement + * this method. + * + * @param number The value to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(int64_t number, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Format a decimal number. Subclasses must implement + * this method. The syntax of the unformatted number is a "numeric string" + * as defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * @param number The unformatted number, as a string, to be formatted. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * Can be nullptr. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format(StringPiece number, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + +// Can't use #ifndef U_HIDE_INTERNAL_API because these are virtual methods + + /** + * Format a decimal number. + * The number is a DecimalQuantity wrapper onto a floating point decimal number. + * The default implementation in NumberFormat converts the decimal number + * to a double and formats that. Subclasses of NumberFormat that want + * to specifically handle big decimal numbers must override this method. + * class DecimalFormat does so. + * + * @param number The number, a DecimalQuantity format Decimal Floating Point. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(const number::impl::DecimalQuantity &number, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const; + + /** + * Format a decimal number. + * The number is a DecimalQuantity wrapper onto a floating point decimal number. + * The default implementation in NumberFormat converts the decimal number + * to a double and formats that. Subclasses of NumberFormat that want + * to specifically handle big decimal numbers must override this method. + * class DecimalFormat does so. + * + * @param number The number, a DecimalQuantity format Decimal Floating Point. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(const number::impl::DecimalQuantity &number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Return a long if possible (e.g. within range LONG_MAX, + * LONG_MAX], and with no decimals), otherwise a double. If + * IntegerOnly is set, will stop at a decimal point (or equivalent; + * e.g. for rational numbers "1 2/3", will stop after the 1). + *

+ * If no object can be parsed, index is unchanged, and nullptr is + * returned. + *

+ * This is a pure virtual which concrete subclasses must implement. + * + * @param text The text to be parsed. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parsePosition The position to start parsing at on input. + * On output, moved to after the last successfully + * parse character. On parse failure, does not change. + * @stable ICU 2.0 + */ + virtual void parse(const UnicodeString& text, + Formattable& result, + ParsePosition& parsePosition) const = 0; + + /** + * Parse a string as a numeric value, and return a Formattable + * numeric object. This method parses integers only if IntegerOnly + * is set. + * + * @param text The text to be parsed. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param status Output parameter set to a failure error code + * when a failure occurs. The error code when the + * string fails to parse is U_INVALID_FORMAT_ERROR, + * unless overridden by a subclass. + * @see NumberFormat::isParseIntegerOnly + * @stable ICU 2.0 + */ + virtual void parse(const UnicodeString& text, + Formattable& result, + UErrorCode& status) const; + + /** + * Parses text from the given string as a currency amount. Unlike + * the parse() method, this method will attempt to parse a generic + * currency name, searching for a match of this object's locale's + * currency display names, or for a 3-letter ISO currency code. + * This method will fail if this format is not a currency format, + * that is, if it does not contain the currency pattern symbol + * (U+00A4) in its prefix or suffix. + * + * @param text the string to parse + * @param pos input-output position; on input, the position within text + * to match; must have 0 <= pos.getIndex() < text.length(); + * on output, the position after the last matched character. + * If the parse fails, the position in unchanged upon output. + * @return if parse succeeds, a pointer to a newly-created CurrencyAmount + * object (owned by the caller) containing information about + * the parsed currency; if parse fails, this is nullptr. + * @stable ICU 49 + */ + virtual CurrencyAmount* parseCurrency(const UnicodeString& text, + ParsePosition& pos) const; + + /** + * Return true if this format will parse numbers as integers + * only. For example in the English locale, with ParseIntegerOnly + * true, the string "1234." would be parsed as the integer value + * 1234 and parsing would stop at the "." character. Of course, + * the exact format accepted by the parse operation is locale + * dependent and determined by sub-classes of NumberFormat. + * @return true if this format will parse numbers as integers + * only. + * @stable ICU 2.0 + */ + UBool isParseIntegerOnly(void) const; + + /** + * Sets whether or not numbers should be parsed as integers only. + * @param value set True, this format will parse numbers as integers + * only. + * @see isParseIntegerOnly + * @stable ICU 2.0 + */ + virtual void setParseIntegerOnly(UBool value); + + /** + * Sets whether lenient parsing should be enabled (it is off by default). + * + * @param enable \c true if lenient parsing should be used, + * \c false otherwise. + * @stable ICU 4.8 + */ + virtual void setLenient(UBool enable); + + /** + * Returns whether lenient parsing is enabled (it is off by default). + * + * @return \c true if lenient parsing is enabled, + * \c false otherwise. + * @see #setLenient + * @stable ICU 4.8 + */ + virtual UBool isLenient(void) const; + + /** + * Create a default style NumberFormat for the current default locale. + * The default formatting style is locale dependent. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createInstance(UErrorCode&); + + /** + * Create a default style NumberFormat for the specified locale. + * The default formatting style is locale dependent. + * @param inLocale the given locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale, + UErrorCode&); + + /** + * Create a specific style NumberFormat for the specified locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param desiredLocale the given locale. + * @param style the given style. + * @param errorCode Output param filled with success/failure status. + * @return A new NumberFormat instance. + * @stable ICU 4.8 + */ + static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale, + UNumberFormatStyle style, + UErrorCode& errorCode); + +#ifndef U_HIDE_INTERNAL_API + + /** + * ICU use only. + * Creates NumberFormat instance without using the cache. + * @internal + */ + static NumberFormat* internalCreateInstance( + const Locale& desiredLocale, + UNumberFormatStyle style, + UErrorCode& errorCode); + + /** + * ICU use only. + * Returns handle to the shared, cached NumberFormat instance for given + * locale. On success, caller must call removeRef() on returned value + * once it is done with the shared instance. + * @internal + */ + static const SharedNumberFormat* U_EXPORT2 createSharedInstance( + const Locale& inLocale, UNumberFormatStyle style, UErrorCode& status); + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Returns a currency format for the current default locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&); + + /** + * Returns a currency format for the specified locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param inLocale the given locale. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale, + UErrorCode&); + + /** + * Returns a percentage format for the current default locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&); + + /** + * Returns a percentage format for the specified locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param inLocale the given locale. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale, + UErrorCode&); + + /** + * Returns a scientific format for the current default locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&); + + /** + * Returns a scientific format for the specified locale. + *

+ * NOTE: New users are strongly encouraged to use + * {@link icu::number::NumberFormatter} instead of NumberFormat. + * @param inLocale the given locale. + * @stable ICU 2.0 + */ + static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale, + UErrorCode&); + + /** + * Get the set of Locales for which NumberFormats are installed. + * @param count Output param to receive the size of the locales + * @stable ICU 2.0 + */ + static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); + +#if !UCONFIG_NO_SERVICE + /** + * Register a new NumberFormatFactory. The factory will be adopted. + * Because ICU may choose to cache NumberFormat objects internally, + * this must be called at application startup, prior to any calls to + * NumberFormat::createInstance to avoid undefined behavior. + * @param toAdopt the NumberFormatFactory instance to be adopted + * @param status the in/out status code, no special meanings are assigned + * @return a registry key that can be used to unregister this factory + * @stable ICU 2.6 + */ + static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status); + + /** + * Unregister a previously-registered NumberFormatFactory using the key returned from the + * register call. Key becomes invalid after a successful call and should not be used again. + * The NumberFormatFactory corresponding to the key will be deleted. + * Because ICU may choose to cache NumberFormat objects internally, + * this should be called during application shutdown, after all calls to + * NumberFormat::createInstance to avoid undefined behavior. + * @param key the registry key returned by a previous call to registerFactory + * @param status the in/out status code, no special meanings are assigned + * @return true if the factory for the key was successfully unregistered + * @stable ICU 2.6 + */ + static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); + + /** + * Return a StringEnumeration over the locales available at the time of the call, + * including registered locales. + * @return a StringEnumeration over the locales available at the time of the call + * @stable ICU 2.6 + */ + static StringEnumeration* U_EXPORT2 getAvailableLocales(void); +#endif /* UCONFIG_NO_SERVICE */ + + /** + * Returns true if grouping is used in this format. For example, + * in the English locale, with grouping on, the number 1234567 + * might be formatted as "1,234,567". The grouping separator as + * well as the size of each group is locale dependent and is + * determined by sub-classes of NumberFormat. + * @see setGroupingUsed + * @stable ICU 2.0 + */ + UBool isGroupingUsed(void) const; + + /** + * Set whether or not grouping will be used in this format. + * @param newValue True, grouping will be used in this format. + * @see getGroupingUsed + * @stable ICU 2.0 + */ + virtual void setGroupingUsed(UBool newValue); + + /** + * Returns the maximum number of digits allowed in the integer portion of a + * number. + * @return the maximum number of digits allowed in the integer portion of a + * number. + * @see setMaximumIntegerDigits + * @stable ICU 2.0 + */ + int32_t getMaximumIntegerDigits(void) const; + + /** + * Sets the maximum number of digits allowed in the integer portion of a + * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the + * new value for maximumIntegerDigits is less than the current value + * of minimumIntegerDigits, then minimumIntegerDigits will also be set to + * the new value. + * + * @param newValue the new value for the maximum number of digits + * allowed in the integer portion of a number. + * @see getMaximumIntegerDigits + * @stable ICU 2.0 + */ + virtual void setMaximumIntegerDigits(int32_t newValue); + + /** + * Returns the minimum number of digits allowed in the integer portion of a + * number. + * @return the minimum number of digits allowed in the integer portion of a + * number. + * @see setMinimumIntegerDigits + * @stable ICU 2.0 + */ + int32_t getMinimumIntegerDigits(void) const; + + /** + * Sets the minimum number of digits allowed in the integer portion of a + * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the + * new value for minimumIntegerDigits exceeds the current value + * of maximumIntegerDigits, then maximumIntegerDigits will also be set to + * the new value. + * @param newValue the new value to be set. + * @see getMinimumIntegerDigits + * @stable ICU 2.0 + */ + virtual void setMinimumIntegerDigits(int32_t newValue); + + /** + * Returns the maximum number of digits allowed in the fraction portion of a + * number. + * @return the maximum number of digits allowed in the fraction portion of a + * number. + * @see setMaximumFractionDigits + * @stable ICU 2.0 + */ + int32_t getMaximumFractionDigits(void) const; + + /** + * Sets the maximum number of digits allowed in the fraction portion of a + * number. maximumFractionDigits must be >= minimumFractionDigits. If the + * new value for maximumFractionDigits is less than the current value + * of minimumFractionDigits, then minimumFractionDigits will also be set to + * the new value. + * @param newValue the new value to be set. + * @see getMaximumFractionDigits + * @stable ICU 2.0 + */ + virtual void setMaximumFractionDigits(int32_t newValue); + + /** + * Returns the minimum number of digits allowed in the fraction portion of a + * number. + * @return the minimum number of digits allowed in the fraction portion of a + * number. + * @see setMinimumFractionDigits + * @stable ICU 2.0 + */ + int32_t getMinimumFractionDigits(void) const; + + /** + * Sets the minimum number of digits allowed in the fraction portion of a + * number. minimumFractionDigits must be <= maximumFractionDigits. If the + * new value for minimumFractionDigits exceeds the current value + * of maximumFractionDigits, then maximumIntegerDigits will also be set to + * the new value + * @param newValue the new value to be set. + * @see getMinimumFractionDigits + * @stable ICU 2.0 + */ + virtual void setMinimumFractionDigits(int32_t newValue); + + /** + * Sets the currency used to display currency + * amounts. This takes effect immediately, if this format is a + * currency format. If this format is not a currency format, then + * the currency is used if and when this object becomes a + * currency format. + * @param theCurrency a 3-letter ISO code indicating new currency + * to use. It need not be null-terminated. May be the empty + * string or nullptr to indicate no currency. + * @param ec input-output error code + * @stable ICU 3.0 + */ + virtual void setCurrency(const char16_t* theCurrency, UErrorCode& ec); + + /** + * Gets the currency used to display currency + * amounts. This may be an empty string for some subclasses. + * @return a 3-letter null-terminated ISO code indicating + * the currency in use, or a pointer to the empty string. + * @stable ICU 2.6 + */ + const char16_t* getCurrency() const; + + /** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. + * @param value The UDisplayContext value to set. + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @stable ICU 53 + */ + virtual void setContext(UDisplayContext value, UErrorCode& status); + + /** + * Get the formatter's UDisplayContext value for the specified UDisplayContextType, + * such as UDISPCTX_TYPE_CAPITALIZATION. + * @param type The UDisplayContextType whose value to return + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @return The UDisplayContextValue for the specified type. + * @stable ICU 53 + */ + virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; + + /** + * Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary + * if the subclass does not support rounding. + * @return A rounding mode + * @stable ICU 60 + */ + virtual ERoundingMode getRoundingMode(void) const; + + /** + * Set the rounding mode. If a subclass does not support rounding, this will do nothing. + * @param roundingMode A rounding mode + * @stable ICU 60 + */ + virtual void setRoundingMode(ERoundingMode roundingMode); + +public: + + /** + * Return the class ID for this class. This is useful for + * comparing to a return value from getDynamicClassID(). Note that, + * because NumberFormat is an abstract base class, no fully constructed object + * will have the class ID returned by NumberFormat::getStaticClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. + * This method is to implement a simple version of RTTI, since not all + * C++ compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + *

+ * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + +protected: + + /** + * Default constructor for subclass use only. + * @stable ICU 2.0 + */ + NumberFormat(); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + NumberFormat(const NumberFormat&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + NumberFormat& operator=(const NumberFormat&); + + /** + * Returns the currency in effect for this formatter. Subclasses + * should override this method as needed. Unlike getCurrency(), + * this method should never return "". + * @result output parameter for null-terminated result, which must + * have a capacity of at least 4 + * @internal + */ + virtual void getEffectiveCurrency(char16_t* result, UErrorCode& ec) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Creates the specified number format style of the desired locale. + * If mustBeDecimalFormat is true, then the returned pointer is + * either a DecimalFormat or it is nullptr. + * @internal + */ + static NumberFormat* makeInstance(const Locale& desiredLocale, + UNumberFormatStyle style, + UBool mustBeDecimalFormat, + UErrorCode& errorCode); +#endif /* U_HIDE_INTERNAL_API */ + +private: + + static UBool isStyleSupported(UNumberFormatStyle style); + + /** + * Creates the specified decimal format style of the desired locale. + * @param desiredLocale the given locale. + * @param style the given style. + * @param errorCode Output param filled with success/failure status. + * @return A new NumberFormat instance. + */ + static NumberFormat* makeInstance(const Locale& desiredLocale, + UNumberFormatStyle style, + UErrorCode& errorCode); + + UBool fGroupingUsed; + int32_t fMaxIntegerDigits; + int32_t fMinIntegerDigits; + int32_t fMaxFractionDigits; + int32_t fMinFractionDigits; + + protected: + /** \internal */ + static const int32_t gDefaultMaxIntegerDigits; + /** \internal */ + static const int32_t gDefaultMinIntegerDigits; + + private: + UBool fParseIntegerOnly; + UBool fLenient; // true => lenient parse is enabled + + // ISO currency code + char16_t fCurrency[4]; + + UDisplayContext fCapitalizationContext; + + friend class ICUNumberFormatFactory; // access to makeInstance + friend class ICUNumberFormatService; + friend class ::NumberFormatTest; // access to isStyleSupported() +}; + +#if !UCONFIG_NO_SERVICE +/** + * A NumberFormatFactory is used to register new number formats. The factory + * should be able to create any of the predefined formats for each locale it + * supports. When registered, the locales it supports extend or override the + * locale already supported by ICU. + * + * @stable ICU 2.6 + */ +class U_I18N_API NumberFormatFactory : public UObject { +public: + + /** + * Destructor + * @stable ICU 3.0 + */ + virtual ~NumberFormatFactory(); + + /** + * Return true if this factory will be visible. Default is true. + * If not visible, the locales supported by this factory will not + * be listed by getAvailableLocales. + * @stable ICU 2.6 + */ + virtual UBool visible(void) const = 0; + + /** + * Return the locale names directly supported by this factory. The number of names + * is returned in count; + * @stable ICU 2.6 + */ + virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0; + + /** + * Return a number format of the appropriate type. If the locale + * is not supported, return null. If the locale is supported, but + * the type is not provided by this service, return null. Otherwise + * return an appropriate instance of NumberFormat. + * @stable ICU 2.6 + */ + virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0; +}; + +/** + * A NumberFormatFactory that supports a single locale. It can be visible or invisible. + * @stable ICU 2.6 + */ +class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory { +protected: + /** + * True if the locale supported by this factory is visible. + * @stable ICU 2.6 + */ + const UBool _visible; + + /** + * The locale supported by this factory, as a UnicodeString. + * @stable ICU 2.6 + */ + UnicodeString _id; + +public: + /** + * @stable ICU 2.6 + */ + SimpleNumberFormatFactory(const Locale& locale, UBool visible = true); + + /** + * @stable ICU 3.0 + */ + virtual ~SimpleNumberFormatFactory(); + + /** + * @stable ICU 2.6 + */ + virtual UBool visible(void) const override; + + /** + * @stable ICU 2.6 + */ + virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const override; +}; +#endif /* #if !UCONFIG_NO_SERVICE */ + +// ------------------------------------- + +inline UBool +NumberFormat::isParseIntegerOnly() const +{ + return fParseIntegerOnly; +} + +inline UBool +NumberFormat::isLenient() const +{ + return fLenient; +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _NUMFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numsys.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numsys.h new file mode 100644 index 0000000000000000000000000000000000000000..51a6e147b10792d353490fe0f9fdc1723cf17d58 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/numsys.h @@ -0,0 +1,220 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2014, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* +* File NUMSYS.H +* +* Modification History:* +* Date Name Description +* +******************************************************************************** +*/ + +#ifndef NUMSYS +#define NUMSYS + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: NumberingSystem object + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/format.h" +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN + +// can't be #ifndef U_HIDE_INTERNAL_API; needed for char[] field size +/** + * Size of a numbering system name. + * @internal + */ +constexpr const size_t kInternalNumSysNameCapacity = 8; + +/** + * Defines numbering systems. A numbering system describes the scheme by which + * numbers are to be presented to the end user. In its simplest form, a numbering + * system describes the set of digit characters that are to be used to display + * numbers, such as Western digits, Thai digits, Arabic-Indic digits, etc., in a + * positional numbering system with a specified radix (typically 10). + * More complicated numbering systems are algorithmic in nature, and require use + * of an RBNF formatter ( rule based number formatter ), in order to calculate + * the characters to be displayed for a given number. Examples of algorithmic + * numbering systems include Roman numerals, Chinese numerals, and Hebrew numerals. + * Formatting rules for many commonly used numbering systems are included in + * the ICU package, based on the numbering system rules defined in CLDR. + * Alternate numbering systems can be specified to a locale by using the + * numbers locale keyword. + */ + +class U_I18N_API NumberingSystem : public UObject { +public: + + /** + * Default Constructor. + * + * @stable ICU 4.2 + */ + NumberingSystem(); + + /** + * Copy constructor. + * @stable ICU 4.2 + */ + NumberingSystem(const NumberingSystem& other); + + /** + * Copy assignment. + * @stable ICU 4.2 + */ + NumberingSystem& operator=(const NumberingSystem& other) = default; + + /** + * Destructor. + * @stable ICU 4.2 + */ + virtual ~NumberingSystem(); + + /** + * Create the default numbering system associated with the specified locale. + * @param inLocale The given locale. + * @param status ICU status + * @stable ICU 4.2 + */ + static NumberingSystem* U_EXPORT2 createInstance(const Locale & inLocale, UErrorCode& status); + + /** + * Create the default numbering system associated with the default locale. + * @stable ICU 4.2 + */ + static NumberingSystem* U_EXPORT2 createInstance(UErrorCode& status); + + /** + * Create a numbering system using the specified radix, type, and description. + * @param radix The radix (base) for this numbering system. + * @param isAlgorithmic true if the numbering system is algorithmic rather than numeric. + * @param description The string representing the set of digits used in a numeric system, or the name of the RBNF + * ruleset to be used in an algorithmic system. + * @param status ICU status + * @stable ICU 4.2 + */ + static NumberingSystem* U_EXPORT2 createInstance(int32_t radix, UBool isAlgorithmic, const UnicodeString& description, UErrorCode& status ); + + /** + * Return a StringEnumeration over all the names of numbering systems known to ICU. + * The numbering system names will be in alphabetical (invariant) order. + * + * The returned StringEnumeration is owned by the caller, who must delete it when + * finished with it. + * + * @stable ICU 4.2 + */ + static StringEnumeration * U_EXPORT2 getAvailableNames(UErrorCode& status); + + /** + * Create a numbering system from one of the predefined numbering systems specified + * by CLDR and known to ICU, such as "latn", "arabext", or "hanidec"; the full list + * is returned by unumsys_openAvailableNames. Note that some of the names listed at + * http://unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - e.g. + * default, native, traditional, finance - do not identify specific numbering systems, + * but rather key values that may only be used as part of a locale, which in turn + * defines how they are mapped to a specific numbering system such as "latn" or "hant". + * + * @param name The name of the numbering system. + * @param status ICU status; set to U_UNSUPPORTED_ERROR if numbering system not found. + * @return The NumberingSystem instance, or nullptr if not found. + * @stable ICU 4.2 + */ + static NumberingSystem* U_EXPORT2 createInstanceByName(const char* name, UErrorCode& status); + + + /** + * Returns the radix of this numbering system. Simple positional numbering systems + * typically have radix 10, but might have a radix of e.g. 16 for hexadecimal. The + * radix is less well-defined for non-positional algorithmic systems. + * @stable ICU 4.2 + */ + int32_t getRadix() const; + + /** + * Returns the name of this numbering system if it was created using one of the predefined names + * known to ICU. Otherwise, returns nullptr. + * The predefined names are identical to the numbering system names as defined by + * the BCP47 definition in Unicode CLDR. + * See also, http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml + * @stable ICU 4.6 + */ + const char * getName() const; + + /** + * Returns the description string of this numbering system. For simple + * positional systems this is the ordered string of digits (with length matching + * the radix), e.g. "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D" + * for "hanidec"; it would be "0123456789ABCDEF" for hexadecimal. For + * algorithmic systems this is the name of the RBNF ruleset used for formatting, + * e.g. "zh/SpelloutRules/%spellout-cardinal" for "hans" or "%greek-upper" for + * "grek". + * @stable ICU 4.2 + */ + virtual UnicodeString getDescription() const; + + + + /** + * Returns true if the given numbering system is algorithmic + * + * @return true if the numbering system is algorithmic. + * Otherwise, return false. + * @stable ICU 4.2 + */ + UBool isAlgorithmic() const; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 4.2 + * + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 4.2 + */ + virtual UClassID getDynamicClassID() const override; + + +private: + UnicodeString desc; + int32_t radix; + UBool algorithmic; + char name[kInternalNumSysNameCapacity+1]; + + void setRadix(int32_t radix); + + void setAlgorithmic(UBool algorithmic); + + void setDesc(const UnicodeString &desc); + + void setName(const char* name); +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _NUMSYS +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parseerr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parseerr.h new file mode 100644 index 0000000000000000000000000000000000000000..c23cc273b828ebcfd8814f4ab22c9663d53cd293 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parseerr.h @@ -0,0 +1,94 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2005, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 03/14/00 aliu Creation. +* 06/27/00 aliu Change from C++ class to C struct +********************************************************************** +*/ +#ifndef PARSEERR_H +#define PARSEERR_H + +#include "unicode/utypes.h" + + +/** + * \file + * \brief C API: Parse Error Information + */ +/** + * The capacity of the context strings in UParseError. + * @stable ICU 2.0 + */ +enum { U_PARSE_CONTEXT_LEN = 16 }; + +/** + * A UParseError struct is used to returned detailed information about + * parsing errors. It is used by ICU parsing engines that parse long + * rules, patterns, or programs, where the text being parsed is long + * enough that more information than a UErrorCode is needed to + * localize the error. + * + *

The line, offset, and context fields are optional; parsing + * engines may choose not to use to use them. + * + *

The preContext and postContext strings include some part of the + * context surrounding the error. If the source text is "let for=7" + * and "for" is the error (e.g., because it is a reserved word), then + * some examples of what a parser might produce are the following: + * + *

+ * preContext   postContext
+ * ""           ""            The parser does not support context
+ * "let "       "=7"          Pre- and post-context only
+ * "let "       "for=7"       Pre- and post-context and error text
+ * ""           "for"         Error text only
+ * 
+ * + *

Examples of engines which use UParseError (or may use it in the + * future) are Transliterator, RuleBasedBreakIterator, and + * RegexPattern. + * + * @stable ICU 2.0 + */ +typedef struct UParseError { + + /** + * The line on which the error occurred. If the parser uses this + * field, it sets it to the line number of the source text line on + * which the error appears, which will be a value >= 1. If the + * parse does not support line numbers, the value will be <= 0. + * @stable ICU 2.0 + */ + int32_t line; + + /** + * The character offset to the error. If the line field is >= 1, + * then this is the offset from the start of the line. Otherwise, + * this is the offset from the start of the text. If the parser + * does not support this field, it will have a value < 0. + * @stable ICU 2.0 + */ + int32_t offset; + + /** + * Textual context before the error. Null-terminated. The empty + * string if not supported by parser. + * @stable ICU 2.0 + */ + UChar preContext[U_PARSE_CONTEXT_LEN]; + + /** + * The error itself and/or textual context after the error. + * Null-terminated. The empty string if not supported by parser. + * @stable ICU 2.0 + */ + UChar postContext[U_PARSE_CONTEXT_LEN]; + +} UParseError; + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parsepos.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parsepos.h new file mode 100644 index 0000000000000000000000000000000000000000..d33a812ad0b4f384a2c5f6eea25e216b6797f792 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/parsepos.h @@ -0,0 +1,237 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +* Copyright (C) 1997-2005, International Business Machines Corporation and others. All Rights Reserved. +******************************************************************************* +* +* File PARSEPOS.H +* +* Modification History: +* +* Date Name Description +* 07/09/97 helena Converted from java. +* 07/17/98 stephen Added errorIndex support. +* 05/11/99 stephen Cleaned up. +******************************************************************************* +*/ + +#ifndef PARSEPOS_H +#define PARSEPOS_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + + +U_NAMESPACE_BEGIN + +/** + * \file + * \brief C++ API: Canonical Iterator + */ +/** + * ParsePosition is a simple class used by Format + * and its subclasses to keep track of the current position during parsing. + * The parseObject method in the various Format + * classes requires a ParsePosition object as an argument. + * + *

+ * By design, as you parse through a string with different formats, + * you can use the same ParsePosition, since the index parameter + * records the current position. + * + * The ParsePosition class is not suitable for subclassing. + * + * @version 1.3 10/30/97 + * @author Mark Davis, Helena Shih + * @see java.text.Format + */ + +class U_COMMON_API ParsePosition : public UObject { +public: + /** + * Default constructor, the index starts with 0 as default. + * @stable ICU 2.0 + */ + ParsePosition() + : UObject(), + index(0), + errorIndex(-1) + {} + + /** + * Create a new ParsePosition with the given initial index. + * @param newIndex the new text offset. + * @stable ICU 2.0 + */ + ParsePosition(int32_t newIndex) + : UObject(), + index(newIndex), + errorIndex(-1) + {} + + /** + * Copy constructor + * @param copy the object to be copied from. + * @stable ICU 2.0 + */ + ParsePosition(const ParsePosition& copy) + : UObject(copy), + index(copy.index), + errorIndex(copy.errorIndex) + {} + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~ParsePosition(); + + /** + * Assignment operator + * @stable ICU 2.0 + */ + inline ParsePosition& operator=(const ParsePosition& copy); + + /** + * Equality operator. + * @return true if the two parse positions are equal, false otherwise. + * @stable ICU 2.0 + */ + inline bool operator==(const ParsePosition& that) const; + + /** + * Equality operator. + * @return true if the two parse positions are not equal, false otherwise. + * @stable ICU 2.0 + */ + inline bool operator!=(const ParsePosition& that) const; + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + ParsePosition *clone() const; + + /** + * Retrieve the current parse position. On input to a parse method, this + * is the index of the character at which parsing will begin; on output, it + * is the index of the character following the last character parsed. + * @return the current index. + * @stable ICU 2.0 + */ + inline int32_t getIndex(void) const; + + /** + * Set the current parse position. + * @param index the new index. + * @stable ICU 2.0 + */ + inline void setIndex(int32_t index); + + /** + * Set the index at which a parse error occurred. Formatters + * should set this before returning an error code from their + * parseObject method. The default value is -1 if this is not + * set. + * @stable ICU 2.0 + */ + inline void setErrorIndex(int32_t ei); + + /** + * Retrieve the index at which an error occurred, or -1 if the + * error index has not been set. + * @stable ICU 2.0 + */ + inline int32_t getErrorIndex(void) const; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + +private: + /** + * Input: the place you start parsing. + *
Output: position where the parse stopped. + * This is designed to be used serially, + * with each call setting index up for the next one. + */ + int32_t index; + + /** + * The index at which a parse error occurred. + */ + int32_t errorIndex; + +}; + +inline ParsePosition& +ParsePosition::operator=(const ParsePosition& copy) +{ + index = copy.index; + errorIndex = copy.errorIndex; + return *this; +} + +inline bool +ParsePosition::operator==(const ParsePosition& copy) const +{ + if(index != copy.index || errorIndex != copy.errorIndex) + return false; + else + return true; +} + +inline bool +ParsePosition::operator!=(const ParsePosition& copy) const +{ + return !operator==(copy); +} + +inline int32_t +ParsePosition::getIndex() const +{ + return index; +} + +inline void +ParsePosition::setIndex(int32_t offset) +{ + this->index = offset; +} + +inline int32_t +ParsePosition::getErrorIndex() const +{ + return errorIndex; +} + +inline void +ParsePosition::setErrorIndex(int32_t ei) +{ + this->errorIndex = ei; +} +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/platform.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..a997843660c9ade396a29c6e569dee44764b9e9e --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/platform.h @@ -0,0 +1,881 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* FILE NAME : platform.h +* +* Date Name Description +* 05/13/98 nos Creation (content moved here from ptypes.h). +* 03/02/99 stephen Added AS400 support. +* 03/30/99 stephen Added Linux support. +* 04/13/99 stephen Reworked for autoconf. +****************************************************************************** +*/ + +#ifndef _PLATFORM_H +#define _PLATFORM_H + +#include "unicode/uconfig.h" +#include "unicode/uvernum.h" + +/** + * \file + * \brief Basic types for the platform. + * + * This file used to be generated by autoconf/configure. + * Starting with ICU 49, platform.h is a normal source file, + * to simplify cross-compiling and working with non-autoconf/make build systems. + * + * When a value in this file does not work on a platform, then please + * try to derive it from the U_PLATFORM value + * (for which we might need a new value constant in rare cases) + * and/or from other macros that are predefined by the compiler + * or defined in standard (POSIX or platform or compiler) headers. + * + * As a temporary workaround, you can add an explicit \#define for some macros + * before it is first tested, or add an equivalent -D macro definition + * to the compiler's command line. + * + * Note: Some compilers provide ways to show the predefined macros. + * For example, with gcc you can compile an empty .c file and have the compiler + * print the predefined macros with + * \code + * gcc -E -dM -x c /dev/null | sort + * \endcode + * (You can provide an actual empty .c file rather than /dev/null. + * -x c++ is for C++.) + */ + +/** + * Define some things so that they can be documented. + * @internal + */ +#ifdef U_IN_DOXYGEN +/* + * Problem: "platform.h:335: warning: documentation for unknown define U_HAVE_STD_STRING found." means that U_HAVE_STD_STRING is not documented. + * Solution: #define any defines for non @internal API here, so that they are visible in the docs. If you just set PREDEFINED in Doxyfile.in, they won't be documented. + */ + +/* None for now. */ +#endif + +/** + * \def U_PLATFORM + * The U_PLATFORM macro defines the platform we're on. + * + * We used to define one different, value-less macro per platform. + * That made it hard to know the set of relevant platforms and macros, + * and hard to deal with variants of platforms. + * + * Starting with ICU 49, we define platforms as numeric macros, + * with ranges of values for related platforms and their variants. + * The U_PLATFORM macro is set to one of these values. + * + * Historical note from the Solaris Wikipedia article: + * AT&T and Sun collaborated on a project to merge the most popular Unix variants + * on the market at that time: BSD, System V, and Xenix. + * This became Unix System V Release 4 (SVR4). + * + * @internal + */ + +/** Unknown platform. @internal */ +#define U_PF_UNKNOWN 0 +/** Windows @internal */ +#define U_PF_WINDOWS 1000 +/** MinGW. Windows, calls to Win32 API, but using GNU gcc and binutils. @internal */ +#define U_PF_MINGW 1800 +/** + * Cygwin. Windows, calls to cygwin1.dll for Posix functions, + * using MSVC or GNU gcc and binutils. + * @internal + */ +#define U_PF_CYGWIN 1900 +/* Reserve 2000 for U_PF_UNIX? */ +/** HP-UX is based on UNIX System V. @internal */ +#define U_PF_HPUX 2100 +/** Solaris is a Unix operating system based on SVR4. @internal */ +#define U_PF_SOLARIS 2600 +/** BSD is a UNIX operating system derivative. @internal */ +#define U_PF_BSD 3000 +/** AIX is based on UNIX System V Releases and 4.3 BSD. @internal */ +#define U_PF_AIX 3100 +/** IRIX is based on UNIX System V with BSD extensions. @internal */ +#define U_PF_IRIX 3200 +/** + * Darwin is a POSIX-compliant operating system, composed of code developed by Apple, + * as well as code derived from NeXTSTEP, BSD, and other projects, + * built around the Mach kernel. + * Darwin forms the core set of components upon which Mac OS X, Apple TV, and iOS are based. + * (Original description modified from WikiPedia.) + * @internal + */ +#define U_PF_DARWIN 3500 +/** iPhone OS (iOS) is a derivative of Mac OS X. @internal */ +#define U_PF_IPHONE 3550 +/** QNX is a commercial Unix-like real-time operating system related to BSD. @internal */ +#define U_PF_QNX 3700 +/** Linux is a Unix-like operating system. @internal */ +#define U_PF_LINUX 4000 +/** + * Native Client is pretty close to Linux. + * See https://developer.chrome.com/native-client and + * http://www.chromium.org/nativeclient + * @internal + */ +#define U_PF_BROWSER_NATIVE_CLIENT 4020 +/** Android is based on Linux. @internal */ +#define U_PF_ANDROID 4050 +/** Fuchsia is a POSIX-ish platform. @internal */ +#define U_PF_FUCHSIA 4100 +/* Maximum value for Linux-based platform is 4499 */ +/** + * Emscripten is a C++ transpiler for the Web that can target asm.js or + * WebAssembly. It provides some POSIX-compatible wrappers and stubs and + * some Linux-like functionality, but is not fully compatible with + * either. + * @internal + */ +#define U_PF_EMSCRIPTEN 5010 +/** z/OS is the successor to OS/390 which was the successor to MVS. @internal */ +#define U_PF_OS390 9000 +/** "IBM i" is the current name of what used to be i5/OS and earlier OS/400. @internal */ +#define U_PF_OS400 9400 + +#ifdef U_PLATFORM + /* Use the predefined value. */ +#elif defined(__MINGW32__) +# define U_PLATFORM U_PF_MINGW +#elif defined(__CYGWIN__) +# define U_PLATFORM U_PF_CYGWIN +#elif defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) +# define U_PLATFORM U_PF_WINDOWS +#elif defined(__ANDROID__) +# define U_PLATFORM U_PF_ANDROID + /* Android wchar_t support depends on the API level. */ +# include +#elif defined(__pnacl__) || defined(__native_client__) +# define U_PLATFORM U_PF_BROWSER_NATIVE_CLIENT +#elif defined(__Fuchsia__) +# define U_PLATFORM U_PF_FUCHSIA +#elif defined(linux) || defined(__linux__) || defined(__linux) +# define U_PLATFORM U_PF_LINUX +#elif defined(__APPLE__) && defined(__MACH__) +# include +# if (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) && (defined(TARGET_OS_MACCATALYST) && !TARGET_OS_MACCATALYST) /* variant of TARGET_OS_MAC */ +# define U_PLATFORM U_PF_IPHONE +# else +# define U_PLATFORM U_PF_DARWIN +# endif +#elif defined(BSD) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__MirBSD__) +# if defined(__FreeBSD__) +# include +# endif +# define U_PLATFORM U_PF_BSD +#elif defined(sun) || defined(__sun) + /* Check defined(__SVR4) || defined(__svr4__) to distinguish Solaris from SunOS? */ +# define U_PLATFORM U_PF_SOLARIS +# if defined(__GNUC__) + /* Solaris/GCC needs this header file to get the proper endianness. Normally, this + * header file is included with stddef.h but on Solairs/GCC, the GCC version of stddef.h + * is included which does not include this header file. + */ +# include +# endif +#elif defined(_AIX) || defined(__TOS_AIX__) +# define U_PLATFORM U_PF_AIX +#elif defined(_hpux) || defined(hpux) || defined(__hpux) +# define U_PLATFORM U_PF_HPUX +#elif defined(sgi) || defined(__sgi) +# define U_PLATFORM U_PF_IRIX +#elif defined(__QNX__) || defined(__QNXNTO__) +# define U_PLATFORM U_PF_QNX +#elif defined(__TOS_MVS__) +# define U_PLATFORM U_PF_OS390 +#elif defined(__OS400__) || defined(__TOS_OS400__) +# define U_PLATFORM U_PF_OS400 +#elif defined(__EMSCRIPTEN__) +# define U_PLATFORM U_PF_EMSCRIPTEN +#else +# define U_PLATFORM U_PF_UNKNOWN +#endif + +/** + * \def CYGWINMSVC + * Defined if this is Windows with Cygwin, but using MSVC rather than gcc. + * Otherwise undefined. + * @internal + */ +/* Commented out because this is already set in mh-cygwin-msvc +#if U_PLATFORM == U_PF_CYGWIN && defined(_MSC_VER) +# define CYGWINMSVC +#endif +*/ +#ifdef U_IN_DOXYGEN +# define CYGWINMSVC +#endif + +/** + * \def U_PLATFORM_USES_ONLY_WIN32_API + * Defines whether the platform uses only the Win32 API. + * Set to 1 for Windows/MSVC and MinGW but not Cygwin. + * @internal + */ +#ifdef U_PLATFORM_USES_ONLY_WIN32_API + /* Use the predefined value. */ +#elif (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_MINGW) || defined(CYGWINMSVC) +# define U_PLATFORM_USES_ONLY_WIN32_API 1 +#else + /* Cygwin implements POSIX. */ +# define U_PLATFORM_USES_ONLY_WIN32_API 0 +#endif + +/** + * \def U_PLATFORM_HAS_WIN32_API + * Defines whether the Win32 API is available on the platform. + * Set to 1 for Windows/MSVC, MinGW and Cygwin. + * @internal + */ +#ifdef U_PLATFORM_HAS_WIN32_API + /* Use the predefined value. */ +#elif U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN +# define U_PLATFORM_HAS_WIN32_API 1 +#else +# define U_PLATFORM_HAS_WIN32_API 0 +#endif + +/** + * \def U_PLATFORM_HAS_WINUWP_API + * Defines whether target is intended for Universal Windows Platform API + * Set to 1 for Windows10 Release Solution Configuration + * @internal + */ +#ifdef U_PLATFORM_HAS_WINUWP_API + /* Use the predefined value. */ +#else +# define U_PLATFORM_HAS_WINUWP_API 0 +#endif + +/** + * \def U_PLATFORM_IMPLEMENTS_POSIX + * Defines whether the platform implements (most of) the POSIX API. + * Set to 1 for Cygwin and most other platforms. + * @internal + */ +#ifdef U_PLATFORM_IMPLEMENTS_POSIX + /* Use the predefined value. */ +#elif U_PLATFORM_USES_ONLY_WIN32_API +# define U_PLATFORM_IMPLEMENTS_POSIX 0 +#else +# define U_PLATFORM_IMPLEMENTS_POSIX 1 +#endif + +/** + * \def U_PLATFORM_IS_LINUX_BASED + * Defines whether the platform is Linux or one of its derivatives. + * @internal + */ +#ifdef U_PLATFORM_IS_LINUX_BASED + /* Use the predefined value. */ +#elif U_PF_LINUX <= U_PLATFORM && U_PLATFORM <= 4499 +# define U_PLATFORM_IS_LINUX_BASED 1 +#else +# define U_PLATFORM_IS_LINUX_BASED 0 +#endif + +/** + * \def U_PLATFORM_IS_DARWIN_BASED + * Defines whether the platform is Darwin or one of its derivatives. + * @internal + */ +#ifdef U_PLATFORM_IS_DARWIN_BASED + /* Use the predefined value. */ +#elif U_PF_DARWIN <= U_PLATFORM && U_PLATFORM <= U_PF_IPHONE +# define U_PLATFORM_IS_DARWIN_BASED 1 +#else +# define U_PLATFORM_IS_DARWIN_BASED 0 +#endif + +/** + * \def U_HAVE_STDINT_H + * Defines whether stdint.h is available. It is a C99 standard header. + * We used to include inttypes.h which includes stdint.h but we usually do not need + * the additional definitions from inttypes.h. + * @internal + */ +#ifdef U_HAVE_STDINT_H + /* Use the predefined value. */ +#elif U_PLATFORM_USES_ONLY_WIN32_API +# if defined(__BORLANDC__) || U_PLATFORM == U_PF_MINGW || (defined(_MSC_VER) && _MSC_VER>=1600) + /* Windows Visual Studio 9 and below do not have stdint.h & inttypes.h, but VS 2010 adds them. */ +# define U_HAVE_STDINT_H 1 +# else +# define U_HAVE_STDINT_H 0 +# endif +#elif U_PLATFORM == U_PF_SOLARIS + /* Solaris has inttypes.h but not stdint.h. */ +# define U_HAVE_STDINT_H 0 +#elif U_PLATFORM == U_PF_AIX && !defined(_AIX51) && defined(_POWER) + /* PPC AIX <= 4.3 has inttypes.h but not stdint.h. */ +# define U_HAVE_STDINT_H 0 +#else +# define U_HAVE_STDINT_H 1 +#endif + +/** + * \def U_HAVE_INTTYPES_H + * Defines whether inttypes.h is available. It is a C99 standard header. + * We include inttypes.h where it is available but stdint.h is not. + * @internal + */ +#ifdef U_HAVE_INTTYPES_H + /* Use the predefined value. */ +#elif U_PLATFORM == U_PF_SOLARIS + /* Solaris has inttypes.h but not stdint.h. */ +# define U_HAVE_INTTYPES_H 1 +#elif U_PLATFORM == U_PF_AIX && !defined(_AIX51) && defined(_POWER) + /* PPC AIX <= 4.3 has inttypes.h but not stdint.h. */ +# define U_HAVE_INTTYPES_H 1 +#else + /* Most platforms have both inttypes.h and stdint.h, or neither. */ +# define U_HAVE_INTTYPES_H U_HAVE_STDINT_H +#endif + +/*===========================================================================*/ +/** @{ Compiler and environment features */ +/*===========================================================================*/ + +/** + * \def U_GCC_MAJOR_MINOR + * Indicates whether the compiler is gcc (test for != 0), + * and if so, contains its major (times 100) and minor version numbers. + * If the compiler is not gcc, then U_GCC_MAJOR_MINOR == 0. + * + * For example, for testing for whether we have gcc, and whether it's 4.6 or higher, + * use "#if U_GCC_MAJOR_MINOR >= 406". + * @internal + */ +#ifdef __GNUC__ +# define U_GCC_MAJOR_MINOR (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define U_GCC_MAJOR_MINOR 0 +#endif + +/** + * \def U_IS_BIG_ENDIAN + * Determines the endianness of the platform. + * @internal + */ +#ifdef U_IS_BIG_ENDIAN + /* Use the predefined value. */ +#elif defined(BYTE_ORDER) && defined(BIG_ENDIAN) +# define U_IS_BIG_ENDIAN (BYTE_ORDER == BIG_ENDIAN) +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) + /* gcc */ +# define U_IS_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#elif defined(__BIG_ENDIAN__) || defined(_BIG_ENDIAN) +# define U_IS_BIG_ENDIAN 1 +#elif defined(__LITTLE_ENDIAN__) || defined(_LITTLE_ENDIAN) +# define U_IS_BIG_ENDIAN 0 +#elif U_PLATFORM == U_PF_OS390 || U_PLATFORM == U_PF_OS400 || defined(__s390__) || defined(__s390x__) + /* These platforms do not appear to predefine any endianness macros. */ +# define U_IS_BIG_ENDIAN 1 +#elif defined(_PA_RISC1_0) || defined(_PA_RISC1_1) || defined(_PA_RISC2_0) + /* HPPA do not appear to predefine any endianness macros. */ +# define U_IS_BIG_ENDIAN 1 +#elif defined(sparc) || defined(__sparc) || defined(__sparc__) + /* Some sparc based systems (e.g. Linux) do not predefine any endianness macros. */ +# define U_IS_BIG_ENDIAN 1 +#else +# define U_IS_BIG_ENDIAN 0 +#endif + +/** + * \def U_HAVE_PLACEMENT_NEW + * Determines whether to override placement new and delete for STL. + * @stable ICU 2.6 + */ +#ifdef U_HAVE_PLACEMENT_NEW + /* Use the predefined value. */ +#elif defined(__BORLANDC__) +# define U_HAVE_PLACEMENT_NEW 0 +#else +# define U_HAVE_PLACEMENT_NEW 1 +#endif + +/** + * \def U_HAVE_DEBUG_LOCATION_NEW + * Define this to define the MFC debug version of the operator new. + * + * @stable ICU 3.4 + */ +#ifdef U_HAVE_DEBUG_LOCATION_NEW + /* Use the predefined value. */ +#elif defined(_MSC_VER) +# define U_HAVE_DEBUG_LOCATION_NEW 1 +#else +# define U_HAVE_DEBUG_LOCATION_NEW 0 +#endif + +/* Compatibility with compilers other than clang: http://clang.llvm.org/docs/LanguageExtensions.html */ +#ifdef __has_attribute +# define UPRV_HAS_ATTRIBUTE(x) __has_attribute(x) +#else +# define UPRV_HAS_ATTRIBUTE(x) 0 +#endif +#ifdef __has_cpp_attribute +# define UPRV_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define UPRV_HAS_CPP_ATTRIBUTE(x) 0 +#endif +#ifdef __has_declspec_attribute +# define UPRV_HAS_DECLSPEC_ATTRIBUTE(x) __has_declspec_attribute(x) +#else +# define UPRV_HAS_DECLSPEC_ATTRIBUTE(x) 0 +#endif +#ifdef __has_builtin +# define UPRV_HAS_BUILTIN(x) __has_builtin(x) +#else +# define UPRV_HAS_BUILTIN(x) 0 +#endif +#ifdef __has_feature +# define UPRV_HAS_FEATURE(x) __has_feature(x) +#else +# define UPRV_HAS_FEATURE(x) 0 +#endif +#ifdef __has_extension +# define UPRV_HAS_EXTENSION(x) __has_extension(x) +#else +# define UPRV_HAS_EXTENSION(x) 0 +#endif +#ifdef __has_warning +# define UPRV_HAS_WARNING(x) __has_warning(x) +#else +# define UPRV_HAS_WARNING(x) 0 +#endif + + +#if defined(__clang__) +#define UPRV_NO_SANITIZE_UNDEFINED __attribute__((no_sanitize("undefined"))) +#else +#define UPRV_NO_SANITIZE_UNDEFINED +#endif + +/** + * \def U_MALLOC_ATTR + * Attribute to mark functions as malloc-like + * @internal + */ +#if defined(__GNUC__) && __GNUC__>=3 +# define U_MALLOC_ATTR __attribute__ ((__malloc__)) +#else +# define U_MALLOC_ATTR +#endif + +/** + * \def U_ALLOC_SIZE_ATTR + * Attribute to specify the size of the allocated buffer for malloc-like functions + * @internal + */ +#if (defined(__GNUC__) && \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) || \ + UPRV_HAS_ATTRIBUTE(alloc_size) +# define U_ALLOC_SIZE_ATTR(X) __attribute__ ((alloc_size(X))) +# define U_ALLOC_SIZE_ATTR2(X,Y) __attribute__ ((alloc_size(X,Y))) +#else +# define U_ALLOC_SIZE_ATTR(X) +# define U_ALLOC_SIZE_ATTR2(X,Y) +#endif + +/** + * \def U_CPLUSPLUS_VERSION + * 0 if no C++; 1, 11, 14, ... if C++. + * Support for specific features cannot always be determined by the C++ version alone. + * @internal + */ +#ifdef U_CPLUSPLUS_VERSION +# if U_CPLUSPLUS_VERSION != 0 && !defined(__cplusplus) +# undef U_CPLUSPLUS_VERSION +# define U_CPLUSPLUS_VERSION 0 +# endif + /* Otherwise use the predefined value. */ +#elif !defined(__cplusplus) +# define U_CPLUSPLUS_VERSION 0 +#elif __cplusplus >= 201402L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define U_CPLUSPLUS_VERSION 14 +#elif __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) +# define U_CPLUSPLUS_VERSION 11 +#else + // C++98 or C++03 +# define U_CPLUSPLUS_VERSION 1 +#endif + +/** + * \def U_FALLTHROUGH + * Annotate intentional fall-through between switch labels. + * http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough + * @internal + */ +#ifndef __cplusplus + // Not for C. +#elif defined(U_FALLTHROUGH) + // Use the predefined value. +#elif defined(__clang__) + // Test for compiler vs. feature separately. + // Other compilers might choke on the feature test. +# if UPRV_HAS_CPP_ATTRIBUTE(clang::fallthrough) || \ + (UPRV_HAS_FEATURE(cxx_attributes) && \ + UPRV_HAS_WARNING("-Wimplicit-fallthrough")) +# define U_FALLTHROUGH [[clang::fallthrough]] +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 7) +# define U_FALLTHROUGH __attribute__((fallthrough)) +#endif + +#ifndef U_FALLTHROUGH +# define U_FALLTHROUGH +#endif + +/** @} */ + +/*===========================================================================*/ +/** @{ Character data types */ +/*===========================================================================*/ + +/** + * U_CHARSET_FAMILY is equal to this value when the platform is an ASCII based platform. + * @stable ICU 2.0 + */ +#define U_ASCII_FAMILY 0 + +/** + * U_CHARSET_FAMILY is equal to this value when the platform is an EBCDIC based platform. + * @stable ICU 2.0 + */ +#define U_EBCDIC_FAMILY 1 + +/** + * \def U_CHARSET_FAMILY + * + *

These definitions allow to specify the encoding of text + * in the char data type as defined by the platform and the compiler. + * It is enough to determine the code point values of "invariant characters", + * which are the ones shared by all encodings that are in use + * on a given platform.

+ * + *

Those "invariant characters" should be all the uppercase and lowercase + * latin letters, the digits, the space, and "basic punctuation". + * Also, '\\n', '\\r', '\\t' should be available.

+ * + *

The list of "invariant characters" is:
+ * \code + * A-Z a-z 0-9 SPACE " % & ' ( ) * + , - . / : ; < = > ? _ + * \endcode + *
+ * (52 letters + 10 numbers + 20 punc/sym/space = 82 total)

+ * + *

This matches the IBM Syntactic Character Set (CS 640).

+ * + *

In other words, all the graphic characters in 7-bit ASCII should + * be safely accessible except the following:

+ * + * \code + * '\' + * '[' + * ']' + * '{' + * '}' + * '^' + * '~' + * '!' + * '#' + * '|' + * '$' + * '@' + * '`' + * \endcode + * @stable ICU 2.0 + */ +#ifdef U_CHARSET_FAMILY + /* Use the predefined value. */ +#elif U_PLATFORM == U_PF_OS390 && (!defined(__CHARSET_LIB) || !__CHARSET_LIB) +# define U_CHARSET_FAMILY U_EBCDIC_FAMILY +#elif U_PLATFORM == U_PF_OS400 && !defined(__UTF32__) +# define U_CHARSET_FAMILY U_EBCDIC_FAMILY +#else +# define U_CHARSET_FAMILY U_ASCII_FAMILY +#endif + +/** + * \def U_CHARSET_IS_UTF8 + * + * Hardcode the default charset to UTF-8. + * + * If this is set to 1, then + * - ICU will assume that all non-invariant char*, StringPiece, std::string etc. + * contain UTF-8 text, regardless of what the system API uses + * - some ICU code will use fast functions like u_strFromUTF8() + * rather than the more general and more heavy-weight conversion API (ucnv.h) + * - ucnv_getDefaultName() always returns "UTF-8" + * - ucnv_setDefaultName() is disabled and will not change the default charset + * - static builds of ICU are smaller + * - more functionality is available with the UCONFIG_NO_CONVERSION build-time + * configuration option (see unicode/uconfig.h) + * - the UCONFIG_NO_CONVERSION build option in uconfig.h is more usable + * + * @stable ICU 4.2 + * @see UCONFIG_NO_CONVERSION + */ +#ifdef U_CHARSET_IS_UTF8 + /* Use the predefined value. */ +#elif U_PLATFORM_IS_LINUX_BASED || U_PLATFORM_IS_DARWIN_BASED || \ + U_PLATFORM == U_PF_EMSCRIPTEN +# define U_CHARSET_IS_UTF8 1 +#else +# define U_CHARSET_IS_UTF8 0 +#endif + +/** @} */ + +/*===========================================================================*/ +/** @{ Information about wchar support */ +/*===========================================================================*/ + +/** + * \def U_HAVE_WCHAR_H + * Indicates whether is available (1) or not (0). Set to 1 by default. + * + * @stable ICU 2.0 + */ +#ifdef U_HAVE_WCHAR_H + /* Use the predefined value. */ +#elif U_PLATFORM == U_PF_ANDROID && __ANDROID_API__ < 9 + /* + * Android before Gingerbread (Android 2.3, API level 9) did not support wchar_t. + * The type and header existed, but the library functions did not work as expected. + * The size of wchar_t was 1 but L"xyz" string literals had 32-bit units anyway. + */ +# define U_HAVE_WCHAR_H 0 +#else +# define U_HAVE_WCHAR_H 1 +#endif + +/** + * \def U_SIZEOF_WCHAR_T + * U_SIZEOF_WCHAR_T==sizeof(wchar_t) + * + * @stable ICU 2.0 + */ +#ifdef U_SIZEOF_WCHAR_T + /* Use the predefined value. */ +#elif (U_PLATFORM == U_PF_ANDROID && __ANDROID_API__ < 9) + /* + * Classic Mac OS and Mac OS X before 10.3 (Panther) did not support wchar_t or wstring. + * Newer Mac OS X has size 4. + */ +# define U_SIZEOF_WCHAR_T 1 +#elif U_PLATFORM_HAS_WIN32_API || U_PLATFORM == U_PF_CYGWIN +# define U_SIZEOF_WCHAR_T 2 +#elif U_PLATFORM == U_PF_AIX + /* + * AIX 6.1 information, section "Wide character data representation": + * "... the wchar_t datatype is 32-bit in the 64-bit environment and + * 16-bit in the 32-bit environment." + * and + * "All locales use Unicode for their wide character code values (process code), + * except the IBM-eucTW codeset." + */ +# ifdef __64BIT__ +# define U_SIZEOF_WCHAR_T 4 +# else +# define U_SIZEOF_WCHAR_T 2 +# endif +#elif U_PLATFORM == U_PF_OS390 + /* + * z/OS V1R11 information center, section "LP64 | ILP32": + * "In 31-bit mode, the size of long and pointers is 4 bytes and the size of wchar_t is 2 bytes. + * Under LP64, the size of long and pointer is 8 bytes and the size of wchar_t is 4 bytes." + */ +# ifdef _LP64 +# define U_SIZEOF_WCHAR_T 4 +# else +# define U_SIZEOF_WCHAR_T 2 +# endif +#elif U_PLATFORM == U_PF_OS400 +# if defined(__UTF32__) + /* + * LOCALETYPE(*LOCALEUTF) is specified. + * Wide-character strings are in UTF-32, + * narrow-character strings are in UTF-8. + */ +# define U_SIZEOF_WCHAR_T 4 +# elif defined(__UCS2__) + /* + * LOCALETYPE(*LOCALEUCS2) is specified. + * Wide-character strings are in UCS-2, + * narrow-character strings are in EBCDIC. + */ +# define U_SIZEOF_WCHAR_T 2 +# else + /* + * LOCALETYPE(*CLD) or LOCALETYPE(*LOCALE) is specified. + * Wide-character strings are in 16-bit EBCDIC, + * narrow-character strings are in EBCDIC. + */ +# define U_SIZEOF_WCHAR_T 2 +# endif +#else +# define U_SIZEOF_WCHAR_T 4 +#endif + +#ifndef U_HAVE_WCSCPY +#define U_HAVE_WCSCPY U_HAVE_WCHAR_H +#endif + +/** @} */ + +/** + * \def U_HAVE_CHAR16_T + * Defines whether the char16_t type is available for UTF-16 + * and u"abc" UTF-16 string literals are supported. + * This is a new standard type and standard string literal syntax in C++11 + * but has been available in some compilers before. + * @internal + */ +#ifdef U_HAVE_CHAR16_T + /* Use the predefined value. */ +#else + /* + * Notes: + * C++11 and C11 require support for UTF-16 literals + * TODO: Fix for plain C. Doesn't work on Mac. + */ +# if U_CPLUSPLUS_VERSION >= 11 || (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) +# define U_HAVE_CHAR16_T 1 +# else +# define U_HAVE_CHAR16_T 0 +# endif +#endif + +/** + * @{ + * \def U_DECLARE_UTF16 + * Do not use this macro because it is not defined on all platforms. + * Use the UNICODE_STRING or U_STRING_DECL macros instead. + * @internal + */ +#ifdef U_DECLARE_UTF16 + /* Use the predefined value. */ +#elif U_HAVE_CHAR16_T \ + || (defined(__xlC__) && defined(__IBM_UTF_LITERAL) && U_SIZEOF_WCHAR_T != 2) \ + || (defined(__HP_aCC) && __HP_aCC >= 035000) \ + || (defined(__HP_cc) && __HP_cc >= 111106) \ + || (defined(U_IN_DOXYGEN)) +# define U_DECLARE_UTF16(string) u ## string +#elif U_SIZEOF_WCHAR_T == 2 \ + && (U_CHARSET_FAMILY == 0 || (U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400 && defined(__UCS2__))) +# define U_DECLARE_UTF16(string) L ## string +#else + /* Leave U_DECLARE_UTF16 undefined. See unistr.h. */ +#endif + +/** @} */ + +/*===========================================================================*/ +/** @{ Symbol import-export control */ +/*===========================================================================*/ + +#ifdef U_EXPORT + /* Use the predefined value. */ +#elif defined(U_STATIC_IMPLEMENTATION) +# define U_EXPORT +#elif defined(_MSC_VER) || (UPRV_HAS_DECLSPEC_ATTRIBUTE(__dllexport__) && \ + UPRV_HAS_DECLSPEC_ATTRIBUTE(__dllimport__)) +# define U_EXPORT __declspec(dllexport) +#elif defined(__GNUC__) +# define U_EXPORT __attribute__((visibility("default"))) +#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550) \ + || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x550) +# define U_EXPORT __global +/*#elif defined(__HP_aCC) || defined(__HP_cc) +# define U_EXPORT __declspec(dllexport)*/ +#else +# define U_EXPORT +#endif + +/* U_CALLCONV is related to U_EXPORT2 */ +#ifdef U_EXPORT2 + /* Use the predefined value. */ +#elif defined(_MSC_VER) +# define U_EXPORT2 __cdecl +#else +# define U_EXPORT2 +#endif + +#ifdef U_IMPORT + /* Use the predefined value. */ +#elif defined(_MSC_VER) || (UPRV_HAS_DECLSPEC_ATTRIBUTE(__dllexport__) && \ + UPRV_HAS_DECLSPEC_ATTRIBUTE(__dllimport__)) + /* Windows needs to export/import data. */ +# define U_IMPORT __declspec(dllimport) +#else +# define U_IMPORT +#endif + +/** + * \def U_HIDDEN + * This is used to mark internal structs declared within external classes, + * to prevent the internal structs from having the same visibility as the + * class within which they are declared. + * @internal + */ +#ifdef U_HIDDEN + /* Use the predefined value. */ +#elif defined(__GNUC__) +# define U_HIDDEN __attribute__((visibility("hidden"))) +#else +# define U_HIDDEN +#endif + +/** + * \def U_CALLCONV + * Similar to U_CDECL_BEGIN/U_CDECL_END, this qualifier is necessary + * in callback function typedefs to make sure that the calling convention + * is compatible. + * + * This is only used for non-ICU-API functions. + * When a function is a public ICU API, + * you must use the U_CAPI and U_EXPORT2 qualifiers. + * + * Please note, you need to use U_CALLCONV after the *. + * + * NO : "static const char U_CALLCONV *func( . . . )" + * YES: "static const char* U_CALLCONV func( . . . )" + * + * @stable ICU 2.0 + */ +#if U_PLATFORM == U_PF_OS390 && defined(__cplusplus) +# define U_CALLCONV __cdecl +#else +# define U_CALLCONV U_EXPORT2 +#endif + +/** + * \def U_CALLCONV_FPTR + * Similar to U_CALLCONV, but only used on function pointers. + * @internal + */ +#if U_PLATFORM == U_PF_OS390 && defined(__cplusplus) +# define U_CALLCONV_FPTR U_CALLCONV +#else +# define U_CALLCONV_FPTR +#endif +/** @} */ + +#endif // _PLATFORM_H diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..8e6cbb445405917250b662d59313174ae5fa1e09 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurfmt.h @@ -0,0 +1,606 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2014, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* + +* File PLURFMT.H +******************************************************************************** +*/ + +#ifndef PLURFMT +#define PLURFMT + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: PluralFormat object + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/messagepattern.h" +#include "unicode/numfmt.h" +#include "unicode/plurrule.h" + +U_NAMESPACE_BEGIN + +class Hashtable; +class NFRule; + +/** + *

+ * PluralFormat supports the creation of internationalized + * messages with plural inflection. It is based on plural + * selection, i.e. the caller specifies messages for each + * plural case that can appear in the user's language and the + * PluralFormat selects the appropriate message based on + * the number. + *

+ *

The Problem of Plural Forms in Internationalized Messages

+ *

+ * Different languages have different ways to inflect + * plurals. Creating internationalized messages that include plural + * forms is only feasible when the framework is able to handle plural + * forms of all languages correctly. ChoiceFormat + * doesn't handle this well, because it attaches a number interval to + * each message and selects the message whose interval contains a + * given number. This can only handle a finite number of + * intervals. But in some languages, like Polish, one plural case + * applies to infinitely many intervals (e.g., the plural case applies to + * numbers ending with 2, 3, or 4 except those ending with 12, 13, or + * 14). Thus ChoiceFormat is not adequate. + *

+ * PluralFormat deals with this by breaking the problem + * into two parts: + *

    + *
  • It uses PluralRules that can define more complex + * conditions for a plural case than just a single interval. These plural + * rules define both what plural cases exist in a language, and to + * which numbers these cases apply. + *
  • It provides predefined plural rules for many languages. Thus, the programmer + * need not worry about the plural cases of a language and + * does not have to define the plural cases; they can simply + * use the predefined keywords. The whole plural formatting of messages can + * be done using localized patterns from resource bundles. For predefined plural + * rules, see the CLDR Language Plural Rules page at + * https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html + *
+ *

+ *

Usage of PluralFormat

+ *

Note: Typically, plural formatting is done via MessageFormat + * with a plural argument type, + * rather than using a stand-alone PluralFormat. + *

+ * This discussion assumes that you use PluralFormat with + * a predefined set of plural rules. You can create one using one of + * the constructors that takes a locale object. To + * specify the message pattern, you can either pass it to the + * constructor or set it explicitly using the + * applyPattern() method. The format() + * method takes a number object and selects the message of the + * matching plural case. This message will be returned. + *

+ *
Patterns and Their Interpretation
+ *

+ * The pattern text defines the message output for each plural case of the + * specified locale. Syntax: + *

+ * pluralStyle = [offsetValue] (selector '{' message '}')+
+ * offsetValue = "offset:" number
+ * selector = explicitValue | keyword
+ * explicitValue = '=' number  // adjacent, no white space in between
+ * keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
+ * message: see {@link MessageFormat}
+ * 
+ * Pattern_White_Space between syntax elements is ignored, except + * between the {curly braces} and their sub-message, + * and between the '=' and the number of an explicitValue. + * + *

+ * There are 6 predefined casekeyword in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and + * 'other'. You always have to define a message text for the default plural case + * other which is contained in every rule set. + * If you do not specify a message text for a particular plural case, the + * message text of the plural case other gets assigned to this + * plural case. + *

+ * When formatting, the input number is first matched against the explicitValue clauses. + * If there is no exact-number match, then a keyword is selected by calling + * the PluralRules with the input number minus the offset. + * (The offset defaults to 0 if it is omitted from the pattern string.) + * If there is no clause with that keyword, then the "other" clauses is returned. + *

+ * An unquoted pound sign (#) in the selected sub-message + * itself (i.e., outside of arguments nested in the sub-message) + * is replaced by the input number minus the offset. + * The number-minus-offset value is formatted using a + * NumberFormat for the PluralFormat's locale. If you + * need special number formatting, you have to use a MessageFormat + * and explicitly specify a NumberFormat argument. + * Note: That argument is formatting without subtracting the offset! + * If you need a custom format and have a non-zero offset, then you need to pass the + * number-minus-offset value as a separate parameter. + *

+ * For a usage example, see the {@link MessageFormat} class documentation. + * + *

Defining Custom Plural Rules

+ *

If you need to use PluralFormat with custom rules, you can + * create a PluralRules object and pass it to + * PluralFormat's constructor. If you also specify a locale in this + * constructor, this locale will be used to format the number in the message + * texts. + *

+ * For more information about PluralRules, see + * {@link PluralRules}. + *

+ * + * ported from Java + * @stable ICU 4.0 + */ + +class U_I18N_API PluralFormat : public Format { +public: + + /** + * Creates a new cardinal-number PluralFormat for the default locale. + * This locale will be used to get the set of plural rules and for standard + * number formatting. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(UErrorCode& status); + + /** + * Creates a new cardinal-number PluralFormat for a given locale. + * @param locale the PluralFormat will be configured with + * rules for this locale. This locale will also be used for + * standard number formatting. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const Locale& locale, UErrorCode& status); + + /** + * Creates a new PluralFormat for a given set of rules. + * The standard number formatting will be done using the default locale. + * @param rules defines the behavior of the PluralFormat + * object. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const PluralRules& rules, UErrorCode& status); + + /** + * Creates a new PluralFormat for a given set of rules. + * The standard number formatting will be done using the given locale. + * @param locale the default number formatting will be done using this + * locale. + * @param rules defines the behavior of the PluralFormat + * object. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + *

+ *

Sample code

+ * \snippet samples/plurfmtsample/plurfmtsample.cpp PluralFormatExample1 + * \snippet samples/plurfmtsample/plurfmtsample.cpp PluralFormatExample + *

+ */ + PluralFormat(const Locale& locale, const PluralRules& rules, UErrorCode& status); + + /** + * Creates a new PluralFormat for the plural type. + * The standard number formatting will be done using the given locale. + * @param locale the default number formatting will be done using this + * locale. + * @param type The plural type (e.g., cardinal or ordinal). + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 50 + */ + PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status); + + /** + * Creates a new cardinal-number PluralFormat for a given pattern string. + * The default locale will be used to get the set of plural rules and for + * standard number formatting. + * @param pattern the pattern for this PluralFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const UnicodeString& pattern, UErrorCode& status); + + /** + * Creates a new cardinal-number PluralFormat for a given pattern string and + * locale. + * The locale will be used to get the set of plural rules and for + * standard number formatting. + * @param locale the PluralFormat will be configured with + * rules for this locale. This locale will also be used for + * standard number formatting. + * @param pattern the pattern for this PluralFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const Locale& locale, const UnicodeString& pattern, UErrorCode& status); + + /** + * Creates a new PluralFormat for a given set of rules, a + * pattern and a locale. + * @param rules defines the behavior of the PluralFormat + * object. + * @param pattern the pattern for this PluralFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const PluralRules& rules, + const UnicodeString& pattern, + UErrorCode& status); + + /** + * Creates a new PluralFormat for a given set of rules, a + * pattern and a locale. + * @param locale the PluralFormat will be configured with + * rules for this locale. This locale will also be used for + * standard number formatting. + * @param rules defines the behavior of the PluralFormat + * object. + * @param pattern the pattern for this PluralFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + PluralFormat(const Locale& locale, + const PluralRules& rules, + const UnicodeString& pattern, + UErrorCode& status); + + /** + * Creates a new PluralFormat for a plural type, a + * pattern and a locale. + * @param locale the PluralFormat will be configured with + * rules for this locale. This locale will also be used for + * standard number formatting. + * @param type The plural type (e.g., cardinal or ordinal). + * @param pattern the pattern for this PluralFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 50 + */ + PluralFormat(const Locale& locale, + UPluralType type, + const UnicodeString& pattern, + UErrorCode& status); + + /** + * copy constructor. + * @stable ICU 4.0 + */ + PluralFormat(const PluralFormat& other); + + /** + * Destructor. + * @stable ICU 4.0 + */ + virtual ~PluralFormat(); + + /** + * Sets the pattern used by this plural format. + * The method parses the pattern and creates a map of format strings + * for the plural rules. + * Patterns and their interpretation are specified in the class description. + * + * @param pattern the pattern for this plural format + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + void applyPattern(const UnicodeString& pattern, UErrorCode& status); + + + using Format::format; + + /** + * Formats a plural message for a given number. + * + * @param number a number for which the plural message should be formatted + * for. If no pattern has been applied to this + * PluralFormat object yet, the formatted number + * will be returned. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return the string containing the formatted plural message. + * @stable ICU 4.0 + */ + UnicodeString format(int32_t number, UErrorCode& status) const; + + /** + * Formats a plural message for a given number. + * + * @param number a number for which the plural message should be formatted + * for. If no pattern has been applied to this + * PluralFormat object yet, the formatted number + * will be returned. + * @param status output param set to success or failure code on exit, which + * must not indicate a failure before the function call. + * @return the string containing the formatted plural message. + * @stable ICU 4.0 + */ + UnicodeString format(double number, UErrorCode& status) const; + + /** + * Formats a plural message for a given number. + * + * @param number a number for which the plural message should be formatted + * for. If no pattern has been applied to this + * PluralFormat object yet, the formatted number + * will be returned. + * @param appendTo output parameter to receive result. + * result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return the string containing the formatted plural message. + * @stable ICU 4.0 + */ + UnicodeString& format(int32_t number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Formats a plural message for a given number. + * + * @param number a number for which the plural message should be formatted + * for. If no pattern has been applied to this + * PluralFormat object yet, the formatted number + * will be returned. + * @param appendTo output parameter to receive result. + * result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return the string containing the formatted plural message. + * @stable ICU 4.0 + */ + UnicodeString& format(double number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Sets the locale used by this PluraFormat object. + * Note: Calling this method resets this PluraFormat object, + * i.e., a pattern that was applied previously will be removed, + * and the NumberFormat is set to the default number format for + * the locale. The resulting format behaves the same as one + * constructed from {@link #PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status)} + * with UPLURAL_TYPE_CARDINAL. + * @param locale the locale to use to configure the formatter. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @deprecated ICU 50 This method clears the pattern and might create + * a different kind of PluralRules instance; + * use one of the constructors to create a new instance instead. + */ + void setLocale(const Locale& locale, UErrorCode& status); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Sets the number format used by this formatter. You only need to + * call this if you want a different number format than the default + * formatter for the locale. + * @param format the number format to use. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.0 + */ + void setNumberFormat(const NumberFormat* format, UErrorCode& status); + + /** + * Assignment operator + * + * @param other the PluralFormat object to copy from. + * @stable ICU 4.0 + */ + PluralFormat& operator=(const PluralFormat& other); + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the PluralFormat object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 4.0 + */ + virtual bool operator==(const Format& other) const override; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the PluralFormat object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 4.0 + */ + virtual bool operator!=(const Format& other) const; + + /** + * Clones this Format object polymorphically. The caller owns the + * result and should delete it when done. + * @stable ICU 4.0 + */ + virtual PluralFormat* clone() const override; + + /** + * Formats a plural message for a number taken from a Formattable object. + * + * @param obj The object containing a number for which the + * plural message should be formatted. + * The object must be of a numeric type. + * @param appendTo output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.0 + */ + UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; + + /** + * Returns the pattern from applyPattern() or constructor(). + * + * @param appendTo output parameter to receive result. + * Result is appended to existing contents. + * @return the UnicodeString with inserted pattern. + * @stable ICU 4.0 + */ + UnicodeString& toPattern(UnicodeString& appendTo); + + /** + * This method is not yet supported by PluralFormat. + *

+ * Before calling, set parse_pos.index to the offset you want to start + * parsing at in the source. After calling, parse_pos.index is the end of + * the text you parsed. If error occurs, index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with a successful parse), + * while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @stable ICU 4.0 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 4.0 + * + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 4.0 + */ + virtual UClassID getDynamicClassID() const override; + +private: + /** + * @internal (private) + */ + class U_I18N_API PluralSelector : public UMemory { + public: + virtual ~PluralSelector(); + /** + * Given a number, returns the appropriate PluralFormat keyword. + * + * @param context worker object for the selector. + * @param number The number to be plural-formatted. + * @param ec Error code. + * @return The selected PluralFormat keyword. + * @internal (private) + */ + virtual UnicodeString select(void *context, double number, UErrorCode& ec) const = 0; + }; + + class U_I18N_API PluralSelectorAdapter : public PluralSelector { + public: + PluralSelectorAdapter() : pluralRules(nullptr) { + } + + virtual ~PluralSelectorAdapter(); + + virtual UnicodeString select(void *context, double number, UErrorCode& /*ec*/) const override; + + void reset(); + + PluralRules* pluralRules; + }; + + Locale locale; + MessagePattern msgPattern; + NumberFormat* numberFormat; + double offset; + PluralSelectorAdapter pluralRulesWrapper; + + PluralFormat() = delete; // default constructor not implemented + void init(const PluralRules* rules, UPluralType type, UErrorCode& status); + /** + * Copies dynamically allocated values (pointer fields). + * Others are copied using their copy constructors and assignment operators. + */ + void copyObjects(const PluralFormat& other); + + UnicodeString& format(const Formattable& numberObject, double number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Finds the PluralFormat sub-message for the given number, or the "other" sub-message. + * @param pattern A MessagePattern. + * @param partIndex the index of the first PluralFormat argument style part. + * @param selector the PluralSelector for mapping the number (minus offset) to a keyword. + * @param context worker object for the selector. + * @param number a number to be matched to one of the PluralFormat argument's explicit values, + * or mapped via the PluralSelector. + * @param ec ICU error code. + * @return the sub-message start part index. + */ + static int32_t findSubMessage( + const MessagePattern& pattern, int32_t partIndex, + const PluralSelector& selector, void *context, double number, UErrorCode& ec); + + void parseType(const UnicodeString& source, const NFRule *rbnfLenientScanner, + Formattable& result, FieldPosition& pos) const; + + friend class MessageFormat; + friend class NFRule; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _PLURFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurrule.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurrule.h new file mode 100644 index 0000000000000000000000000000000000000000..b7d95175f558c03941ac0ec8a37a156c989a704a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/plurrule.h @@ -0,0 +1,591 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2008-2015, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* +* File PLURRULE.H +* +* Modification History:* +* Date Name Description +* +******************************************************************************** +*/ + +#ifndef PLURRULE +#define PLURRULE + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: PluralRules object + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/format.h" +#include "unicode/upluralrules.h" +#ifndef U_HIDE_INTERNAL_API +#include "unicode/numfmt.h" +#endif /* U_HIDE_INTERNAL_API */ + +/** + * Value returned by PluralRules::getUniqueKeywordValue() when there is no + * unique value to return. + * @stable ICU 4.8 + */ +#define UPLRULES_NO_UNIQUE_VALUE ((double)-0.00123456777) + +U_NAMESPACE_BEGIN + +class Hashtable; +class IFixedDecimal; +class FixedDecimal; +class RuleChain; +class PluralRuleParser; +class PluralKeywordEnumeration; +class AndConstraint; +class SharedPluralRules; +class StandardPluralRanges; + +namespace number { +class FormattedNumber; +class FormattedNumberRange; +namespace impl { +class UFormattedNumberRangeData; +class DecimalQuantity; +class DecNum; +} +} + +#ifndef U_HIDE_INTERNAL_API +using icu::number::impl::DecimalQuantity; +#endif /* U_HIDE_INTERNAL_API */ + +/** + * Defines rules for mapping non-negative numeric values onto a small set of + * keywords. Rules are constructed from a text description, consisting + * of a series of keywords and conditions. The {@link #select} method + * examines each condition in order and returns the keyword for the + * first condition that matches the number. If none match, + * default rule(other) is returned. + * + * For more information, details, and tips for writing rules, see the + * LDML spec, Part 3.5 Language Plural Rules: + * https://www.unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules + * + * Examples:

+ *   "one: n is 1; few: n in 2..4"
+ * This defines two rules, for 'one' and 'few'. The condition for + * 'one' is "n is 1" which means that the number must be equal to + * 1 for this condition to pass. The condition for 'few' is + * "n in 2..4" which means that the number must be between 2 and + * 4 inclusive for this condition to pass. All other numbers + * are assigned the keyword "other" by the default rule. + *

+ *    "zero: n is 0; one: n is 1; zero: n mod 100 in 1..19"
+ * This illustrates that the same keyword can be defined multiple times. + * Each rule is examined in order, and the first keyword whose condition + * passes is the one returned. Also notes that a modulus is applied + * to n in the last rule. Thus its condition holds for 119, 219, 319... + *

+ *    "one: n is 1; few: n mod 10 in 2..4 and n mod 100 not in 12..14"
+ * This illustrates conjunction and negation. The condition for 'few' + * has two parts, both of which must be met: "n mod 10 in 2..4" and + * "n mod 100 not in 12..14". The first part applies a modulus to n + * before the test as in the previous example. The second part applies + * a different modulus and also uses negation, thus it matches all + * numbers _not_ in 12, 13, 14, 112, 113, 114, 212, 213, 214... + *

+ *

+ * Syntax:

+ * \code
+ * rules         = rule (';' rule)*
+ * rule          = keyword ':' condition
+ * keyword       = 
+ * condition     = and_condition ('or' and_condition)*
+ * and_condition = relation ('and' relation)*
+ * relation      = is_relation | in_relation | within_relation | 'n' 
+ * is_relation   = expr 'is' ('not')? value
+ * in_relation   = expr ('not')? 'in' range_list
+ * within_relation = expr ('not')? 'within' range
+ * expr          = ('n' | 'i' | 'f' | 'v' | 'j') ('mod' value)?
+ * range_list    = (range | value) (',' range_list)*
+ * value         = digit+  ('.' digit+)?
+ * digit         = 0|1|2|3|4|5|6|7|8|9
+ * range         = value'..'value
+ * \endcode
+ * 

+ *

+ *

+ * The i, f, and v values are defined as follows: + *

+ *
    + *
  • i to be the integer digits.
  • + *
  • f to be the visible fractional digits, as an integer.
  • + *
  • v to be the number of visible fraction digits.
  • + *
  • j is defined to only match integers. That is j is 3 fails if v != 0 (eg for 3.1 or 3.0).
  • + *
+ *

+ * Examples are in the following table: + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
nifv
1.0101
1.00102
1.3131
1.03132
1.231232
+ *

+ * The difference between 'in' and 'within' is that 'in' only includes integers in the specified range, while 'within' + * includes all values. Using 'within' with a range_list consisting entirely of values is the same as using 'in' (it's + * not an error). + *

+ + * An "identifier" is a sequence of characters that do not have the + * Unicode Pattern_Syntax or Pattern_White_Space properties. + *

+ * The difference between 'in' and 'within' is that 'in' only includes + * integers in the specified range, while 'within' includes all values. + * Using 'within' with a range_list consisting entirely of values is the + * same as using 'in' (it's not an error). + *

+ *

+ * Keywords + * could be defined by users or from ICU locale data. There are 6 + * predefined values in ICU - 'zero', 'one', 'two', 'few', 'many' and + * 'other'. Callers need to check the value of keyword returned by + * {@link #select} method. + *

+ * + * Examples:
+ * UnicodeString keyword = pl->select(number);
+ * if (keyword== UnicodeString("one") {
+ *     ...
+ * }
+ * else if ( ... )
+ * 
+ * Note:
+ *

+ * ICU defines plural rules for many locales based on CLDR Language Plural Rules. + * For these predefined rules, see CLDR page at + * https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html + *

+ */ +class U_I18N_API PluralRules : public UObject { +public: + + /** + * Constructor. + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * + * @stable ICU 4.0 + */ + PluralRules(UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 4.0 + */ + PluralRules(const PluralRules& other); + + /** + * Destructor. + * @stable ICU 4.0 + */ + virtual ~PluralRules(); + + /** + * Clone + * @stable ICU 4.0 + */ + PluralRules* clone() const; + + /** + * Assignment operator. + * @stable ICU 4.0 + */ + PluralRules& operator=(const PluralRules&); + + /** + * Creates a PluralRules from a description if it is parsable, otherwise + * returns nullptr. + * + * @param description rule description + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return new PluralRules pointer. nullptr if there is an error. + * @stable ICU 4.0 + */ + static PluralRules* U_EXPORT2 createRules(const UnicodeString& description, + UErrorCode& status); + + /** + * The default rules that accept any number. + * + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return new PluralRules pointer. nullptr if there is an error. + * @stable ICU 4.0 + */ + static PluralRules* U_EXPORT2 createDefaultRules(UErrorCode& status); + + /** + * Provides access to the predefined cardinal-number PluralRules for a given + * locale. + * Same as forLocale(locale, UPLURAL_TYPE_CARDINAL, status). + * + * @param locale The locale for which a PluralRules object is + * returned. + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return The predefined PluralRules object pointer for + * this locale. If there's no predefined rules for this locale, + * the rules for the closest parent in the locale hierarchy + * that has one will be returned. The final fallback always + * returns the default 'other' rules. + * @stable ICU 4.0 + */ + static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UErrorCode& status); + + /** + * Provides access to the predefined PluralRules for a given + * locale and the plural type. + * + * @param locale The locale for which a PluralRules object is + * returned. + * @param type The plural type (e.g., cardinal or ordinal). + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return The predefined PluralRules object pointer for + * this locale. If there's no predefined rules for this locale, + * the rules for the closest parent in the locale hierarchy + * that has one will be returned. The final fallback always + * returns the default 'other' rules. + * @stable ICU 50 + */ + static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UPluralType type, UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Return a StringEnumeration over the locales for which there is plurals data. + * @return a StringEnumeration over the locales available. + * @internal + */ + static StringEnumeration* U_EXPORT2 getAvailableLocales(UErrorCode &status); + + /** + * For ICU use only. + * creates a SharedPluralRules object + * @internal + */ + static PluralRules* U_EXPORT2 internalForLocale(const Locale& locale, UPluralType type, UErrorCode& status); + + /** + * For ICU use only. + * Returns handle to the shared, cached PluralRules instance. + * Caller must call removeRef() on returned value once it is done with + * the shared instance. + * @internal + */ + static const SharedPluralRules* U_EXPORT2 createSharedInstance( + const Locale& locale, UPluralType type, UErrorCode& status); + + +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Given an integer, returns the keyword of the first rule + * that applies to the number. This function can be used with + * isKeyword* functions to determine the keyword for default plural rules. + * + * @param number The number for which the rule has to be determined. + * @return The keyword of the selected rule. + * @stable ICU 4.0 + */ + UnicodeString select(int32_t number) const; + + /** + * Given a floating-point number, returns the keyword of the first rule + * that applies to the number. This function can be used with + * isKeyword* functions to determine the keyword for default plural rules. + * + * @param number The number for which the rule has to be determined. + * @return The keyword of the selected rule. + * @stable ICU 4.0 + */ + UnicodeString select(double number) const; + + /** + * Given a formatted number, returns the keyword of the first rule + * that applies to the number. This function can be used with + * isKeyword* functions to determine the keyword for default plural rules. + * + * A FormattedNumber allows you to specify an exponent or trailing zeros, + * which can affect the plural category. To get a FormattedNumber, see + * NumberFormatter. + * + * @param number The number for which the rule has to be determined. + * @param status Set if an error occurs while selecting plural keyword. + * This could happen if the FormattedNumber is invalid. + * @return The keyword of the selected rule. + * @stable ICU 64 + */ + UnicodeString select(const number::FormattedNumber& number, UErrorCode& status) const; + + /** + * Given a formatted number range, returns the overall plural form of the + * range. For example, "3-5" returns "other" in English. + * + * To get a FormattedNumberRange, see NumberRangeFormatter. + * + * This method only works if PluralRules was created with a locale. If it was created + * from PluralRules::createRules(), this method sets status code U_UNSUPPORTED_ERROR. + * + * @param range The number range onto which the rules will be applied. + * @param status Set if an error occurs while selecting plural keyword. + * This could happen if the FormattedNumberRange is invalid, + * or if plural ranges data is unavailable. + * @return The keyword of the selected rule. + * @stable ICU 68 + */ + UnicodeString select(const number::FormattedNumberRange& range, UErrorCode& status) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * @internal + */ + UnicodeString select(const IFixedDecimal &number) const; + /** + * @internal + */ + UnicodeString select(const number::impl::UFormattedNumberRangeData* urange, UErrorCode& status) const; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Returns a list of all rule keywords used in this PluralRules + * object. The rule 'other' is always present by default. + * + * @param status Output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return StringEnumeration with the keywords. + * The caller must delete the object. + * @stable ICU 4.0 + */ + StringEnumeration* getKeywords(UErrorCode& status) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Deprecated Function, does not return useful results. + * + * Originally intended to return a unique value for this keyword if it exists, + * else the constant UPLRULES_NO_UNIQUE_VALUE. + * + * @param keyword The keyword. + * @return Stub deprecated function returns UPLRULES_NO_UNIQUE_VALUE always. + * @deprecated ICU 55 + */ + double getUniqueKeywordValue(const UnicodeString& keyword); + + /** + * Deprecated Function, does not produce useful results. + * + * Originally intended to return all the values for which select() would return the keyword. + * If the keyword is unknown, returns no values, but this is not an error. If + * the number of values is unlimited, returns no values and -1 as the + * count. + * + * The number of returned values is typically small. + * + * @param keyword The keyword. + * @param dest Array into which to put the returned values. May + * be nullptr if destCapacity is 0. + * @param destCapacity The capacity of the array, must be at least 0. + * @param status The error code. Deprecated function, always sets U_UNSUPPORTED_ERROR. + * @return The count of values available, or -1. This count + * can be larger than destCapacity, but no more than + * destCapacity values will be written. + * @deprecated ICU 55 + */ + int32_t getAllKeywordValues(const UnicodeString &keyword, + double *dest, int32_t destCapacity, + UErrorCode& status); +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Returns sample values for which select() would return the keyword. If + * the keyword is unknown, returns no values, but this is not an error. + * + * The number of returned values is typically small. + * + * @param keyword The keyword. + * @param dest Array into which to put the returned values. May + * be nullptr if destCapacity is 0. + * @param destCapacity The capacity of the array, must be at least 0. + * @param status The error code. + * @return The count of values written. + * If more than destCapacity samples are available, then + * only destCapacity are written, and destCapacity is returned as the count, + * rather than setting a U_BUFFER_OVERFLOW_ERROR. + * (The actual number of keyword values could be unlimited.) + * @stable ICU 4.8 + */ + int32_t getSamples(const UnicodeString &keyword, + double *dest, int32_t destCapacity, + UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Internal-only function that returns DecimalQuantitys instead of doubles. + * + * Returns sample values for which select() would return the keyword. If + * the keyword is unknown, returns no values, but this is not an error. + * + * The number of returned values is typically small. + * + * @param keyword The keyword. + * @param dest Array into which to put the returned values. May + * be nullptr if destCapacity is 0. + * @param destCapacity The capacity of the array, must be at least 0. + * @param status The error code. + * @return The count of values written. + * If more than destCapacity samples are available, then + * only destCapacity are written, and destCapacity is returned as the count, + * rather than setting a U_BUFFER_OVERFLOW_ERROR. + * (The actual number of keyword values could be unlimited.) + * @internal + */ + int32_t getSamples(const UnicodeString &keyword, + DecimalQuantity *dest, int32_t destCapacity, + UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Returns true if the given keyword is defined in this + * PluralRules object. + * + * @param keyword the input keyword. + * @return true if the input keyword is defined. + * Otherwise, return false. + * @stable ICU 4.0 + */ + UBool isKeyword(const UnicodeString& keyword) const; + + + /** + * Returns keyword for default plural form. + * + * @return keyword for default plural form. + * @stable ICU 4.0 + */ + UnicodeString getKeywordOther() const; + +#ifndef U_HIDE_INTERNAL_API + /** + * + * @internal + */ + UnicodeString getRules() const; +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Compares the equality of two PluralRules objects. + * + * @param other The other PluralRules object to be compared with. + * @return true if the given PluralRules is the same as this + * PluralRules; false otherwise. + * @stable ICU 4.0 + */ + virtual bool operator==(const PluralRules& other) const; + + /** + * Compares the inequality of two PluralRules objects. + * + * @param other The PluralRules object to be compared with. + * @return true if the given PluralRules is not the same as this + * PluralRules; false otherwise. + * @stable ICU 4.0 + */ + bool operator!=(const PluralRules& other) const {return !operator==(other);} + + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 4.0 + * + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 4.0 + */ + virtual UClassID getDynamicClassID() const override; + + +private: + RuleChain *mRules; + StandardPluralRanges *mStandardPluralRanges; + + PluralRules() = delete; // default constructor not implemented + UnicodeString getRuleFromResource(const Locale& locale, UPluralType type, UErrorCode& status); + RuleChain *rulesForKeyword(const UnicodeString &keyword) const; + PluralRules *clone(UErrorCode& status) const; + + /** + * An internal status variable used to indicate that the object is in an 'invalid' state. + * Used by copy constructor, the assignment operator and the clone method. + */ + UErrorCode mInternalStatus; + + friend class PluralRuleParser; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _PLURRULE +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ptypes.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ptypes.h new file mode 100644 index 0000000000000000000000000000000000000000..70324ffee3b9c4f1d2399e2c1dfb2c14df26e652 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ptypes.h @@ -0,0 +1,130 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1997-2012, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* FILE NAME : ptypes.h +* +* Date Name Description +* 05/13/98 nos Creation (content moved here from ptypes.h). +* 03/02/99 stephen Added AS400 support. +* 03/30/99 stephen Added Linux support. +* 04/13/99 stephen Reworked for autoconf. +* 09/18/08 srl Moved basic types back to ptypes.h from platform.h +****************************************************************************** +*/ + +/** + * \file + * \brief C API: Definitions of integer types of various widths + */ + +#ifndef _PTYPES_H +#define _PTYPES_H + +/** + * \def __STDC_LIMIT_MACROS + * According to the Linux stdint.h, the ISO C99 standard specifies that in C++ implementations + * macros like INT32_MIN and UINTPTR_MAX should only be defined if explicitly requested. + * We need to define __STDC_LIMIT_MACROS before including stdint.h in C++ code + * that uses such limit macros. + * @internal + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS +#endif + +/* NULL, size_t, wchar_t */ +#include + +/* + * If all compilers provided all of the C99 headers and types, + * we would just unconditionally #include here + * and not need any of the stuff after including platform.h. + */ + +/* Find out if we have stdint.h etc. */ +#include "unicode/platform.h" + +/*===========================================================================*/ +/* Generic data types */ +/*===========================================================================*/ + +/* If your platform does not have the header, you may + need to edit the typedefs in the #else section below. + Use #if...#else...#endif with predefined compiler macros if possible. */ +#if U_HAVE_STDINT_H + +/* + * We mostly need (which defines the standard integer types) but not . + * includes and adds the printf/scanf helpers PRId32, SCNx16 etc. + * which we almost never use, plus stuff like imaxabs() which we never use. + */ +#include + +#if U_PLATFORM == U_PF_OS390 +/* The features header is needed to get (u)int64_t sometimes. */ +#include +/* z/OS has , but some versions are missing uint8_t (APAR PK62248). */ +#if !defined(__uint8_t) +#define __uint8_t 1 +typedef unsigned char uint8_t; +#endif +#endif /* U_PLATFORM == U_PF_OS390 */ + +#elif U_HAVE_INTTYPES_H + +# include + +#else /* neither U_HAVE_STDINT_H nor U_HAVE_INTTYPES_H */ + +/// \cond +#if ! U_HAVE_INT8_T +typedef signed char int8_t; +#endif + +#if ! U_HAVE_UINT8_T +typedef unsigned char uint8_t; +#endif + +#if ! U_HAVE_INT16_T +typedef signed short int16_t; +#endif + +#if ! U_HAVE_UINT16_T +typedef unsigned short uint16_t; +#endif + +#if ! U_HAVE_INT32_T +typedef signed int int32_t; +#endif + +#if ! U_HAVE_UINT32_T +typedef unsigned int uint32_t; +#endif + +#if ! U_HAVE_INT64_T +#ifdef _MSC_VER + typedef signed __int64 int64_t; +#else + typedef signed long long int64_t; +#endif +#endif + +#if ! U_HAVE_UINT64_T +#ifdef _MSC_VER + typedef unsigned __int64 uint64_t; +#else + typedef unsigned long long uint64_t; +#endif +#endif +/// \endcond + +#endif /* U_HAVE_STDINT_H / U_HAVE_INTTYPES_H */ + +#endif /* _PTYPES_H */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/putil.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/putil.h new file mode 100644 index 0000000000000000000000000000000000000000..500c21252fc2d72976e4bbcd66f67dd6c936b7bc --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/putil.h @@ -0,0 +1,183 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1997-2014, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* FILE NAME : putil.h +* +* Date Name Description +* 05/14/98 nos Creation (content moved here from utypes.h). +* 06/17/99 erm Added IEEE_754 +* 07/22/98 stephen Added IEEEremainder, max, min, trunc +* 08/13/98 stephen Added isNegativeInfinity, isPositiveInfinity +* 08/24/98 stephen Added longBitsFromDouble +* 03/02/99 stephen Removed openFile(). Added AS400 support. +* 04/15/99 stephen Converted to C +* 11/15/99 helena Integrated S/390 changes for IEEE support. +* 01/11/00 helena Added u_getVersion. +****************************************************************************** +*/ + +#ifndef PUTIL_H +#define PUTIL_H + +#include "unicode/utypes.h" + /** + * \file + * \brief C API: Platform Utilities + */ + +/*==========================================================================*/ +/* Platform utilities */ +/*==========================================================================*/ + +/** + * Platform utilities isolates the platform dependencies of the + * library. For each platform which this code is ported to, these + * functions may have to be re-implemented. + */ + +/** + * Return the ICU data directory. + * The data directory is where common format ICU data files (.dat files) + * are loaded from. Note that normal use of the built-in ICU + * facilities does not require loading of an external data file; + * unless you are adding custom data to ICU, the data directory + * does not need to be set. + * + * The data directory is determined as follows: + * If u_setDataDirectory() has been called, that is it, otherwise + * if the ICU_DATA environment variable is set, use that, otherwise + * If a data directory was specified at ICU build time + * + * \code + * #define ICU_DATA_DIR "path" + * \endcode + * use that, + * otherwise no data directory is available. + * + * @return the data directory, or an empty string ("") if no data directory has + * been specified. + * + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 u_getDataDirectory(void); + + +/** + * Set the ICU data directory. + * The data directory is where common format ICU data files (.dat files) + * are loaded from. Note that normal use of the built-in ICU + * facilities does not require loading of an external data file; + * unless you are adding custom data to ICU, the data directory + * does not need to be set. + * + * This function should be called at most once in a process, before the + * first ICU operation (e.g., u_init()) that will require the loading of an + * ICU data file. + * This function is not thread-safe. Use it before calling ICU APIs from + * multiple threads. + * + * @param directory The directory to be set. + * + * @see u_init + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 u_setDataDirectory(const char *directory); + +#ifndef U_HIDE_INTERNAL_API +/** + * Return the time zone files override directory, or an empty string if + * no directory was specified. Certain time zone resources will be preferentially + * loaded from individual files in this directory. + * + * @return the time zone data override directory. + * @internal + */ +U_CAPI const char * U_EXPORT2 u_getTimeZoneFilesDirectory(UErrorCode *status); + +/** + * Set the time zone files override directory. + * This function is not thread safe; it must not be called concurrently with + * u_getTimeZoneFilesDirectory() or any other use of ICU time zone functions. + * This function should only be called before using any ICU service that + * will access the time zone data. + * @internal + */ +U_CAPI void U_EXPORT2 u_setTimeZoneFilesDirectory(const char *path, UErrorCode *status); +#endif /* U_HIDE_INTERNAL_API */ + + +/** + * @{ + * Filesystem file and path separator characters. + * Example: '/' and ':' on Unix, '\\' and ';' on Windows. + * @stable ICU 2.0 + */ +#if U_PLATFORM_USES_ONLY_WIN32_API +# define U_FILE_SEP_CHAR '\\' +# define U_FILE_ALT_SEP_CHAR '/' +# define U_PATH_SEP_CHAR ';' +# define U_FILE_SEP_STRING "\\" +# define U_FILE_ALT_SEP_STRING "/" +# define U_PATH_SEP_STRING ";" +#else +# define U_FILE_SEP_CHAR '/' +# define U_FILE_ALT_SEP_CHAR '/' +# define U_PATH_SEP_CHAR ':' +# define U_FILE_SEP_STRING "/" +# define U_FILE_ALT_SEP_STRING "/" +# define U_PATH_SEP_STRING ":" +#endif + +/** @} */ + +/** + * Convert char characters to UChar characters. + * This utility function is useful only for "invariant characters" + * that are encoded in the platform default encoding. + * They are a small, constant subset of the encoding and include + * just the latin letters, digits, and some punctuation. + * For details, see U_CHARSET_FAMILY. + * + * @param cs Input string, points to length + * character bytes from a subset of the platform encoding. + * @param us Output string, points to memory for length + * Unicode characters. + * @param length The number of characters to convert; this may + * include the terminating NUL. + * + * @see U_CHARSET_FAMILY + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_charsToUChars(const char *cs, UChar *us, int32_t length); + +/** + * Convert UChar characters to char characters. + * This utility function is useful only for "invariant characters" + * that can be encoded in the platform default encoding. + * They are a small, constant subset of the encoding and include + * just the latin letters, digits, and some punctuation. + * For details, see U_CHARSET_FAMILY. + * + * @param us Input string, points to length + * Unicode characters that can be encoded with the + * codepage-invariant subset of the platform encoding. + * @param cs Output string, points to memory for length + * character bytes. + * @param length The number of characters to convert; this may + * include the terminating NUL. + * + * @see U_CHARSET_FAMILY + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_UCharsToChars(const UChar *us, char *cs, int32_t length); + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbbi.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbbi.h new file mode 100644 index 0000000000000000000000000000000000000000..418b52e41f42dc2f3e809b2ad2f928eb17b47967 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbbi.h @@ -0,0 +1,745 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +*************************************************************************** +* Copyright (C) 1999-2016 International Business Machines Corporation * +* and others. All rights reserved. * +*************************************************************************** + +********************************************************************** +* Date Name Description +* 10/22/99 alan Creation. +* 11/11/99 rgillam Complete port from Java. +********************************************************************** +*/ + +#ifndef RBBI_H +#define RBBI_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Rule Based Break Iterator + */ + +#if !UCONFIG_NO_BREAK_ITERATION + +#include "unicode/brkiter.h" +#include "unicode/udata.h" +#include "unicode/parseerr.h" +#include "unicode/schriter.h" + +struct UCPTrie; + +U_NAMESPACE_BEGIN + +/** @internal */ +class LanguageBreakEngine; +struct RBBIDataHeader; +class RBBIDataWrapper; +class UnhandledEngine; +class UStack; + +/** + * + * A subclass of BreakIterator whose behavior is specified using a list of rules. + *

Instances of this class are most commonly created by the factory methods of + * BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc., + * and then used via the abstract API in class BreakIterator

+ * + *

See the ICU User Guide for information on Break Iterator Rules.

+ * + *

This class is not intended to be subclassed.

+ */ +class U_COMMON_API RuleBasedBreakIterator /*final*/ : public BreakIterator { + +private: + /** + * The UText through which this BreakIterator accesses the text + * @internal (private) + */ + UText fText = UTEXT_INITIALIZER; + +#ifndef U_HIDE_INTERNAL_API +public: +#endif /* U_HIDE_INTERNAL_API */ + /** + * The rule data for this BreakIterator instance. + * Not for general use; Public only for testing purposes. + * @internal + */ + RBBIDataWrapper *fData = nullptr; + +private: + /** + * The saved error code associated with this break iterator. + * This is the value to be returned by copyErrorTo(). + */ + UErrorCode fErrorCode = U_ZERO_ERROR; + + /** + * The current position of the iterator. Pinned, 0 < fPosition <= text.length. + * Never has the value UBRK_DONE (-1). + */ + int32_t fPosition = 0; + + /** + * TODO: + */ + int32_t fRuleStatusIndex = 0; + + /** + * Cache of previously determined boundary positions. + */ + class BreakCache; + BreakCache *fBreakCache = nullptr; + + /** + * Cache of boundary positions within a region of text that has been + * sub-divided by dictionary based breaking. + */ + class DictionaryCache; + DictionaryCache *fDictionaryCache = nullptr; + + /** + * + * If present, UStack of LanguageBreakEngine objects that might handle + * dictionary characters. Searched from top to bottom to find an object to + * handle a given character. + * @internal (private) + */ + UStack *fLanguageBreakEngines = nullptr; + + /** + * + * If present, the special LanguageBreakEngine used for handling + * characters that are in the dictionary set, but not handled by any + * LanguageBreakEngine. + * @internal (private) + */ + UnhandledEngine *fUnhandledBreakEngine = nullptr; + + /** + * Counter for the number of characters encountered with the "dictionary" + * flag set. + * @internal (private) + */ + uint32_t fDictionaryCharCount = 0; + + /** + * A character iterator that refers to the same text as the UText, above. + * Only included for compatibility with old API, which was based on CharacterIterators. + * Value may be adopted from outside, or one of fSCharIter or fDCharIter, below. + */ + CharacterIterator *fCharIter = &fSCharIter; + + /** + * When the input text is provided by a UnicodeString, this will point to + * a characterIterator that wraps that data. Needed only for the + * implementation of getText(), a backwards compatibility issue. + */ + UCharCharacterIterator fSCharIter {u"", 0}; + + /** + * True when iteration has run off the end, and iterator functions should return UBRK_DONE. + */ + bool fDone = false; + + /** + * Array of look-ahead tentative results. + */ + int32_t *fLookAheadMatches = nullptr; + + /** + * A flag to indicate if phrase based breaking is enabled. + */ + UBool fIsPhraseBreaking = false; + + //======================================================================= + // constructors + //======================================================================= + + /** + * Constructor from a flattened set of RBBI data in malloced memory. + * RulesBasedBreakIterators built from a custom set of rules + * are created via this constructor; the rules are compiled + * into memory, then the break iterator is constructed here. + * + * The break iterator adopts the memory, and will + * free it when done. + * @internal (private) + */ + RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status); + + /** + * This constructor uses the udata interface to create a BreakIterator + * whose internal tables live in a memory-mapped file. "image" is an + * ICU UDataMemory handle for the pre-compiled break iterator tables. + * @param image handle to the memory image for the break iterator data. + * Ownership of the UDataMemory handle passes to the Break Iterator, + * which will be responsible for closing it when it is no longer needed. + * @param status Information on any errors encountered. + * @param isPhraseBreaking true if phrase based breaking is required, otherwise false. + * @see udata_open + * @see #getBinaryRules + * @internal (private) + */ + RuleBasedBreakIterator(UDataMemory* image, UBool isPhraseBreaking, UErrorCode &status); + + /** @internal */ + friend class RBBIRuleBuilder; + /** @internal */ + friend class BreakIterator; + + /** + * Default constructor with an error code parameter. + * Aside from error handling, otherwise identical to the default constructor. + * Internally, handles common initialization for other constructors. + * @internal (private) + */ + RuleBasedBreakIterator(UErrorCode *status); + +public: + + /** Default constructor. Creates an empty shell of an iterator, with no + * rules or text to iterate over. Object can subsequently be assigned to, + * but is otherwise unusable. + * @stable ICU 2.2 + */ + RuleBasedBreakIterator(); + + /** + * Copy constructor. Will produce a break iterator with the same behavior, + * and which iterates over the same text, as the one passed in. + * @param that The RuleBasedBreakIterator passed to be copied + * @stable ICU 2.0 + */ + RuleBasedBreakIterator(const RuleBasedBreakIterator& that); + + /** + * Construct a RuleBasedBreakIterator from a set of rules supplied as a string. + * @param rules The break rules to be used. + * @param parseError In the event of a syntax error in the rules, provides the location + * within the rules of the problem. + * @param status Information on any errors encountered. + * @stable ICU 2.2 + */ + RuleBasedBreakIterator( const UnicodeString &rules, + UParseError &parseError, + UErrorCode &status); + + /** + * Construct a RuleBasedBreakIterator from a set of precompiled binary rules. + * Binary rules are obtained from RulesBasedBreakIterator::getBinaryRules(). + * Construction of a break iterator in this way is substantially faster than + * construction from source rules. + * + * Ownership of the storage containing the compiled rules remains with the + * caller of this function. The compiled rules must not be modified or + * deleted during the life of the break iterator. + * + * The compiled rules are not compatible across different major versions of ICU. + * The compiled rules are compatible only between machines with the same + * byte ordering (little or big endian) and the same base character set family + * (ASCII or EBCDIC). + * + * @see #getBinaryRules + * @param compiledRules A pointer to the compiled break rules to be used. + * @param ruleLength The length of the compiled break rules, in bytes. This + * corresponds to the length value produced by getBinaryRules(). + * @param status Information on any errors encountered, including invalid + * binary rules. + * @stable ICU 4.8 + */ + RuleBasedBreakIterator(const uint8_t *compiledRules, + uint32_t ruleLength, + UErrorCode &status); + + /** + * This constructor uses the udata interface to create a BreakIterator + * whose internal tables live in a memory-mapped file. "image" is an + * ICU UDataMemory handle for the pre-compiled break iterator tables. + * @param image handle to the memory image for the break iterator data. + * Ownership of the UDataMemory handle passes to the Break Iterator, + * which will be responsible for closing it when it is no longer needed. + * @param status Information on any errors encountered. + * @see udata_open + * @see #getBinaryRules + * @stable ICU 2.8 + */ + RuleBasedBreakIterator(UDataMemory* image, UErrorCode &status); + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~RuleBasedBreakIterator(); + + /** + * Assignment operator. Sets this iterator to have the same behavior, + * and iterate over the same text, as the one passed in. + * @param that The RuleBasedBreakItertor passed in + * @return the newly created RuleBasedBreakIterator + * @stable ICU 2.0 + */ + RuleBasedBreakIterator& operator=(const RuleBasedBreakIterator& that); + + /** + * Equality operator. Returns true if both BreakIterators are of the + * same class, have the same behavior, and iterate over the same text. + * @param that The BreakIterator to be compared for equality + * @return true if both BreakIterators are of the + * same class, have the same behavior, and iterate over the same text. + * @stable ICU 2.0 + */ + virtual bool operator==(const BreakIterator& that) const override; + + /** + * Not-equal operator. If operator== returns true, this returns false, + * and vice versa. + * @param that The BreakIterator to be compared for inequality + * @return true if both BreakIterators are not same. + * @stable ICU 2.0 + */ + inline bool operator!=(const BreakIterator& that) const { + return !operator==(that); + } + + /** + * Returns a newly-constructed RuleBasedBreakIterator with the same + * behavior, and iterating over the same text, as this one. + * Differs from the copy constructor in that it is polymorphic, and + * will correctly clone (copy) a derived class. + * clone() is thread safe. Multiple threads may simultaneously + * clone the same source break iterator. + * @return a newly-constructed RuleBasedBreakIterator + * @stable ICU 2.0 + */ + virtual RuleBasedBreakIterator* clone() const override; + + /** + * Compute a hash code for this BreakIterator + * @return A hash code + * @stable ICU 2.0 + */ + virtual int32_t hashCode(void) const; + + /** + * Returns the description used to create this iterator + * @return the description used to create this iterator + * @stable ICU 2.0 + */ + virtual const UnicodeString& getRules(void) const; + + //======================================================================= + // BreakIterator overrides + //======================================================================= + + /** + *

+ * Return a CharacterIterator over the text being analyzed. + * The returned character iterator is owned by the break iterator, and must + * not be deleted by the caller. Repeated calls to this function may + * return the same CharacterIterator. + *

+ *

+ * The returned character iterator must not be used concurrently with + * the break iterator. If concurrent operation is needed, clone the + * returned character iterator first and operate on the clone. + *

+ *

+ * When the break iterator is operating on text supplied via a UText, + * this function will fail, returning a CharacterIterator containing no text. + * The function getUText() provides similar functionality, + * is reliable, and is more efficient. + *

+ * + * TODO: deprecate this function? + * + * @return An iterator over the text being analyzed. + * @stable ICU 2.0 + */ + virtual CharacterIterator& getText(void) const override; + + + /** + * Get a UText for the text being analyzed. + * The returned UText is a shallow clone of the UText used internally + * by the break iterator implementation. It can safely be used to + * access the text without impacting any break iterator operations, + * but the underlying text itself must not be altered. + * + * @param fillIn A UText to be filled in. If nullptr, a new UText will be + * allocated to hold the result. + * @param status receives any error codes. + * @return The current UText for this break iterator. If an input + * UText was provided, it will always be returned. + * @stable ICU 3.4 + */ + virtual UText *getUText(UText *fillIn, UErrorCode &status) const override; + + /** + * Set the iterator to analyze a new piece of text. This function resets + * the current iteration position to the beginning of the text. + * @param newText An iterator over the text to analyze. The BreakIterator + * takes ownership of the character iterator. The caller MUST NOT delete it! + * @stable ICU 2.0 + */ + virtual void adoptText(CharacterIterator* newText) override; + + /** + * Set the iterator to analyze a new piece of text. This function resets + * the current iteration position to the beginning of the text. + * + * The BreakIterator will retain a reference to the supplied string. + * The caller must not modify or delete the text while the BreakIterator + * retains the reference. + * + * @param newText The text to analyze. + * @stable ICU 2.0 + */ + virtual void setText(const UnicodeString& newText) override; + + /** + * Reset the break iterator to operate over the text represented by + * the UText. The iterator position is reset to the start. + * + * This function makes a shallow clone of the supplied UText. This means + * that the caller is free to immediately close or otherwise reuse the + * Utext that was passed as a parameter, but that the underlying text itself + * must not be altered while being referenced by the break iterator. + * + * @param text The UText used to change the text. + * @param status Receives any error codes. + * @stable ICU 3.4 + */ + virtual void setText(UText *text, UErrorCode &status) override; + + /** + * Sets the current iteration position to the beginning of the text, position zero. + * @return The offset of the beginning of the text, zero. + * @stable ICU 2.0 + */ + virtual int32_t first(void) override; + + /** + * Sets the current iteration position to the end of the text. + * @return The text's past-the-end offset. + * @stable ICU 2.0 + */ + virtual int32_t last(void) override; + + /** + * Advances the iterator either forward or backward the specified number of steps. + * Negative values move backward, and positive values move forward. This is + * equivalent to repeatedly calling next() or previous(). + * @param n The number of steps to move. The sign indicates the direction + * (negative is backwards, and positive is forwards). + * @return The character offset of the boundary position n boundaries away from + * the current one. + * @stable ICU 2.0 + */ + virtual int32_t next(int32_t n) override; + + /** + * Advances the iterator to the next boundary position. + * @return The position of the first boundary after this one. + * @stable ICU 2.0 + */ + virtual int32_t next(void) override; + + /** + * Moves the iterator backwards, to the last boundary preceding this one. + * @return The position of the last boundary position preceding this one. + * @stable ICU 2.0 + */ + virtual int32_t previous(void) override; + + /** + * Sets the iterator to refer to the first boundary position following + * the specified position. + * @param offset The position from which to begin searching for a break position. + * @return The position of the first break after the current position. + * @stable ICU 2.0 + */ + virtual int32_t following(int32_t offset) override; + + /** + * Sets the iterator to refer to the last boundary position before the + * specified position. + * @param offset The position to begin searching for a break from. + * @return The position of the last boundary before the starting position. + * @stable ICU 2.0 + */ + virtual int32_t preceding(int32_t offset) override; + + /** + * Returns true if the specified position is a boundary position. As a side + * effect, leaves the iterator pointing to the first boundary position at + * or after "offset". + * @param offset the offset to check. + * @return True if "offset" is a boundary position. + * @stable ICU 2.0 + */ + virtual UBool isBoundary(int32_t offset) override; + + /** + * Returns the current iteration position. Note that UBRK_DONE is never + * returned from this function; if iteration has run to the end of a + * string, current() will return the length of the string while + * next() will return UBRK_DONE). + * @return The current iteration position. + * @stable ICU 2.0 + */ + virtual int32_t current(void) const override; + + + /** + * Return the status tag from the break rule that determined the boundary at + * the current iteration position. For break rules that do not specify a + * status, a default value of 0 is returned. If more than one break rule + * would cause a boundary to be located at some position in the text, + * the numerically largest of the applicable status values is returned. + *

+ * Of the standard types of ICU break iterators, only word break and + * line break provide status values. The values are defined in + * the header file ubrk.h. For Word breaks, the status allows distinguishing between words + * that contain alphabetic letters, "words" that appear to be numbers, + * punctuation and spaces, words containing ideographic characters, and + * more. For Line Break, the status distinguishes between hard (mandatory) breaks + * and soft (potential) break positions. + *

+ * getRuleStatus() can be called after obtaining a boundary + * position from next(), previous(), or + * any other break iterator functions that returns a boundary position. + *

+ * Note that getRuleStatus() returns the value corresponding to + * current() index even after next() has returned DONE. + *

+ * When creating custom break rules, one is free to define whatever + * status values may be convenient for the application. + *

+ * @return the status from the break rule that determined the boundary + * at the current iteration position. + * + * @see UWordBreak + * @stable ICU 2.2 + */ + virtual int32_t getRuleStatus() const override; + + /** + * Get the status (tag) values from the break rule(s) that determined the boundary + * at the current iteration position. + *

+ * The returned status value(s) are stored into an array provided by the caller. + * The values are stored in sorted (ascending) order. + * If the capacity of the output array is insufficient to hold the data, + * the output will be truncated to the available length, and a + * U_BUFFER_OVERFLOW_ERROR will be signaled. + * + * @param fillInVec an array to be filled in with the status values. + * @param capacity the length of the supplied vector. A length of zero causes + * the function to return the number of status values, in the + * normal way, without attempting to store any values. + * @param status receives error codes. + * @return The number of rule status values from the rules that determined + * the boundary at the current iteration position. + * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value + * is the total number of status values that were available, + * not the reduced number that were actually returned. + * @see getRuleStatus + * @stable ICU 3.0 + */ + virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status) override; + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. + * This method is to implement a simple version of RTTI, since not all + * C++ compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Returns the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + * + * Base* polymorphic_pointer = createPolymorphicObject(); + * if (polymorphic_pointer->getDynamicClassID() == + * Derived::getStaticClassID()) ... + * + * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Deprecated functionality. Use clone() instead. + * + * Create a clone (copy) of this break iterator in memory provided + * by the caller. The idea is to increase performance by avoiding + * a storage allocation. Use of this function is NOT RECOMMENDED. + * Performance gains are minimal, and correct buffer management is + * tricky. Use clone() instead. + * + * @param stackBuffer The pointer to the memory into which the cloned object + * should be placed. If nullptr, allocate heap memory + * for the cloned object. + * @param BufferSize The size of the buffer. If zero, return the required + * buffer size, but do not clone the object. If the + * size was too small (but not zero), allocate heap + * storage for the cloned object. + * + * @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be + * returned if the provided buffer was too small, and + * the clone was therefore put on the heap. + * + * @return Pointer to the clone object. This may differ from the stackBuffer + * address if the byte alignment of the stack buffer was not suitable + * or if the stackBuffer was too small to hold the clone. + * @deprecated ICU 52. Use clone() instead. + */ + virtual RuleBasedBreakIterator *createBufferClone(void *stackBuffer, + int32_t &BufferSize, + UErrorCode &status) override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Return the binary form of compiled break rules, + * which can then be used to create a new break iterator at some + * time in the future. Creating a break iterator from pre-compiled rules + * is much faster than building one from the source form of the + * break rules. + * + * The binary data can only be used with the same version of ICU + * and on the same platform type (processor endian-ness) + * + * @param length Returns the length of the binary data. (Out parameter.) + * + * @return A pointer to the binary (compiled) rule data. The storage + * belongs to the RulesBasedBreakIterator object, not the + * caller, and must not be modified or deleted. + * @stable ICU 4.8 + */ + virtual const uint8_t *getBinaryRules(uint32_t &length); + + /** + * Set the subject text string upon which the break iterator is operating + * without changing any other aspect of the matching state. + * The new and previous text strings must have the same content. + * + * This function is intended for use in environments where ICU is operating on + * strings that may move around in memory. It provides a mechanism for notifying + * ICU that the string has been relocated, and providing a new UText to access the + * string in its new position. + * + * Note that the break iterator implementation never copies the underlying text + * of a string being processed, but always operates directly on the original text + * provided by the user. Refreshing simply drops the references to the old text + * and replaces them with references to the new. + * + * Caution: this function is normally used only by very specialized, + * system-level code. One example use case is with garbage collection that moves + * the text in memory. + * + * @param input The new (moved) text string. + * @param status Receives errors detected by this function. + * @return *this + * + * @stable ICU 49 + */ + virtual RuleBasedBreakIterator &refreshInputText(UText *input, UErrorCode &status) override; + + +private: + //======================================================================= + // implementation + //======================================================================= + /** + * Iterate backwards from an arbitrary position in the input text using the + * synthesized Safe Reverse rules. + * This locates a "Safe Position" from which the forward break rules + * will operate correctly. A Safe Position is not necessarily a boundary itself. + * + * @param fromPosition the position in the input text to begin the iteration. + * @internal (private) + */ + int32_t handleSafePrevious(int32_t fromPosition); + + /** + * Find a rule-based boundary by running the state machine. + * Input + * fPosition, the position in the text to begin from. + * Output + * fPosition: the boundary following the starting position. + * fDictionaryCharCount the number of dictionary characters encountered. + * If > 0, the segment will be further subdivided + * fRuleStatusIndex Info from the state table indicating which rules caused the boundary. + * + * @internal (private) + */ + int32_t handleNext(); + + /* + * Templatized version of handleNext() and handleSafePrevious(). + * + * There will be exactly four instantiations, two each for 8 and 16 bit tables, + * two each for 8 and 16 bit trie. + * Having separate instantiations for the table types keeps conditional tests of + * the table type out of the inner loops, at the expense of replicated code. + * + * The template parameter for the Trie access function is a value, not a type. + * Doing it this way, the compiler will inline the Trie function in the + * expanded functions. (Both the 8 and 16 bit access functions have the same type + * signature) + */ + + typedef uint16_t (*PTrieFunc)(const UCPTrie *, UChar32); + + template + int32_t handleSafePrevious(int32_t fromPosition); + + template + int32_t handleNext(); + + + /** + * This function returns the appropriate LanguageBreakEngine for a + * given character c. + * @param c A character in the dictionary set + * @internal (private) + */ + const LanguageBreakEngine *getLanguageBreakEngine(UChar32 c); + + public: +#ifndef U_HIDE_INTERNAL_API + /** + * Debugging function only. + * @internal + */ + void dumpCache(); + + /** + * Debugging function only. + * @internal + */ + void dumpTables(); +#endif /* U_HIDE_INTERNAL_API */ +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbnf.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbnf.h new file mode 100644 index 0000000000000000000000000000000000000000..0336ac1f81e99a18c1a850b40e2c9dd95a523de0 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbnf.h @@ -0,0 +1,1142 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 1997-2015, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************* +*/ + +#ifndef RBNF_H +#define RBNF_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Rule Based Number Format + */ + +/** + * \def U_HAVE_RBNF + * This will be 0 if RBNF support is not included in ICU + * and 1 if it is. + * + * @stable ICU 2.4 + */ +#if UCONFIG_NO_FORMATTING +#define U_HAVE_RBNF 0 +#else +#define U_HAVE_RBNF 1 + +#include "unicode/dcfmtsym.h" +#include "unicode/fmtable.h" +#include "unicode/locid.h" +#include "unicode/numfmt.h" +#include "unicode/unistr.h" +#include "unicode/strenum.h" +#include "unicode/brkiter.h" +#include "unicode/upluralrules.h" + +U_NAMESPACE_BEGIN + +class NFRule; +class NFRuleSet; +class LocalizationInfo; +class PluralFormat; +class RuleBasedCollator; + +/** + * Tags for the predefined rulesets. + * + * @stable ICU 2.2 + */ +enum URBNFRuleSetTag { + /** + * Requests predefined ruleset for spelling out numeric values in words. + * @stable ICU 2.2 + */ + URBNF_SPELLOUT, + /** + * Requests predefined ruleset for the ordinal form of a number. + * @stable ICU 2.2 + */ + URBNF_ORDINAL, + /** + * Requests predefined ruleset for formatting a value as a duration in hours, minutes, and seconds. + * @stable ICU 2.2 + */ + URBNF_DURATION, + /** + * Requests predefined ruleset for various non-place-value numbering systems. + * WARNING: The same resource contains rule sets for a variety of different numbering systems. + * You need to call setDefaultRuleSet() on the formatter to choose the actual numbering system. + * @stable ICU 2.2 + */ + URBNF_NUMBERING_SYSTEM, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal URBNFRuleSetTag value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + URBNF_COUNT +#endif // U_HIDE_DEPRECATED_API +}; + +/** + * The RuleBasedNumberFormat class formats numbers according to a set of rules. This number formatter is + * typically used for spelling out numeric values in words (e.g., 25,3476 as + * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois + * cents soixante-seize" or + * "fünfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for + * other complicated formatting tasks, such as formatting a number of seconds as hours, + * minutes and seconds (e.g., 3,730 as "1:02:10"). + * + *

The resources contain three predefined formatters for each locale: spellout, which + * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which + * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and + * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is + * "2:03").  The client can also define more specialized RuleBasedNumberFormats + * by supplying programmer-defined rule sets.

+ * + *

The behavior of a RuleBasedNumberFormat is specified by a textual description + * that is either passed to the constructor as a String or loaded from a resource + * bundle. In its simplest form, the description consists of a semicolon-delimited list of rules. + * Each rule has a string of output text and a value or range of values it is applicable to. + * In a typical spellout rule set, the first twenty rules are the words for the numbers from + * 0 to 19:

+ * + *
zero; one; two; three; four; five; six; seven; eight; nine;
+ * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;
+ * + *

For larger numbers, we can use the preceding set of rules to format the ones place, and + * we only have to supply the words for the multiples of 10:

+ * + *
 20: twenty[->>];
+ * 30: thirty[->>];
+ * 40: forty[->>];
+ * 50: fifty[->>];
+ * 60: sixty[->>];
+ * 70: seventy[->>];
+ * 80: eighty[->>];
+ * 90: ninety[->>];
+ * + *

In these rules, the base value is spelled out explicitly and set off from the + * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable + * to all numbers from its own base value to one less than the next rule's base value. The + * ">>" token is called a substitution and tells the formatter to + * isolate the number's ones digit, format it using this same set of rules, and place the + * result at the position of the ">>" token. Text in brackets is omitted if + * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24 + * is "twenty-four," not "twenty four").

+ * + *

For even larger numbers, we can actually look up several parts of the number in the + * list:

+ * + *
100: << hundred[ >>];
+ * + *

The "<<" represents a new kind of substitution. The << isolates + * the hundreds digit (and any digits to its left), formats it using this same rule set, and + * places the result where the "<<" was. Notice also that the meaning of + * >> has changed: it now refers to both the tens and the ones digits. The meaning of + * both substitutions depends on the rule's base value. The base value determines the rule's divisor, + * which is the highest power of 10 that is less than or equal to the base value (the user + * can change this). To fill in the substitutions, the formatter divides the number being + * formatted by the divisor. The integral quotient is used to fill in the << + * substitution, and the remainder is used to fill in the >> substitution. The meaning + * of the brackets changes similarly: text in brackets is omitted if the value being + * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so + * if a substitution is filled in with text that includes another substitution, that + * substitution is also filled in.

+ * + *

This rule covers values up to 999, at which point we add another rule:

+ * + *
1000: << thousand[ >>];
+ * + *

Again, the meanings of the brackets and substitution tokens shift because the rule's + * base value is a higher power of 10, changing the rule's divisor. This rule can actually be + * used all the way up to 999,999. This allows us to finish out the rules as follows:

+ * + *
 1,000,000: << million[ >>];
+ * 1,000,000,000: << billion[ >>];
+ * 1,000,000,000,000: << trillion[ >>];
+ * 1,000,000,000,000,000: OUT OF RANGE!;
+ * + *

Commas, periods, and spaces can be used in the base values to improve legibility and + * are ignored by the rule parser. The last rule in the list is customarily treated as an + * "overflow rule," applying to everything from its base value on up, and often (as + * in this example) being used to print out an error message or default representation. + * Notice also that the size of the major groupings in large numbers is controlled by the + * spacing of the rules: because in English we group numbers by thousand, the higher rules + * are separated from each other by a factor of 1,000.

+ * + *

To see how these rules actually work in practice, consider the following example: + * Formatting 25,430 with this rule set would work like this:

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
<< thousand >>[the rule whose base value is 1,000 is applicable to 25,340]
twenty->> thousand >>[25,340 over 1,000 is 25. The rule for 20 applies.]
twenty-five thousand >>[25 mod 10 is 5. The rule for 5 is "five."
twenty-five thousand << hundred >>[25,340 mod 1,000 is 340. The rule for 100 applies.]
twenty-five thousand three hundred >>[340 over 100 is 3. The rule for 3 is "three."]
twenty-five thousand three hundred forty[340 mod 100 is 40. The rule for 40 applies. Since 40 divides + * evenly by 10, the hyphen and substitution in the brackets are omitted.]
+ * + *

The above syntax suffices only to format positive integers. To format negative numbers, + * we add a special rule:

+ * + *
-x: minus >>;
+ * + *

This is called a negative-number rule, and is identified by "-x" + * where the base value would be. This rule is used to format all negative numbers. the + * >> token here means "find the number's absolute value, format it with these + * rules, and put the result here."

+ * + *

We also add a special rule called a fraction rule for numbers with fractional + * parts:

+ * + *
x.x: << point >>;
+ * + *

This rule is used for all positive non-integers (negative non-integers pass through the + * negative-number rule first and then through this rule). Here, the << token refers to + * the number's integral part, and the >> to the number's fractional part. The + * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be + * formatted as "one hundred twenty-three point four five six").

+ * + *

To see how this rule syntax is applied to various languages, examine the resource data.

+ * + *

There is actually much more flexibility built into the rule language than the + * description above shows. A formatter may own multiple rule sets, which can be selected by + * the caller, and which can use each other to fill in their substitutions. Substitutions can + * also be filled in with digits, using a DecimalFormat object. There is syntax that can be + * used to alter a rule's divisor in various ways. And there is provision for much more + * flexible fraction handling. A complete description of the rule syntax follows:

+ * + *
+ * + *

The description of a RuleBasedNumberFormat's behavior consists of one or more rule + * sets. Each rule set consists of a name, a colon, and a list of rules. A rule + * set name must begin with a % sign. Rule sets with names that begin with a single % sign + * are public: the caller can specify that they be used to format and parse numbers. + * Rule sets with names that begin with %% are private: they exist only for the use + * of other rule sets. If a formatter only has one rule set, the name may be omitted.

+ * + *

The user can also specify a special "rule set" named %%lenient-parse. + * The body of %%lenient-parse isn't a set of number-formatting rules, but a RuleBasedCollator + * description which is used to define equivalences for lenient parsing. For more information + * on the syntax, see RuleBasedCollator. For more information on lenient parsing, + * see setLenientParse(). Note: symbols that have syntactic meaning + * in collation rules, such as '&', have no particular meaning when appearing outside + * of the lenient-parse rule set.

+ * + *

The body of a rule set consists of an ordered, semicolon-delimited list of rules. + * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two substitutions. + * These parameters are controlled by the description syntax, which consists of a rule + * descriptor, a colon, and a rule body.

+ * + *

A rule descriptor can take one of the following forms (text in italics is the + * name of a token):

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
bv:bv specifies the rule's base value. bv is a decimal + * number expressed using ASCII digits. bv may contain spaces, period, and commas, + * which are ignored. The rule's divisor is the highest power of 10 less than or equal to + * the base value.
bv/rad:bv specifies the rule's base value. The rule's divisor is the + * highest power of rad less than or equal to the base value.
bv>:bv specifies the rule's base value. To calculate the divisor, + * let the radix be 10, and the exponent be the highest exponent of the radix that yields a + * result less than or equal to the base value. Every > character after the base value + * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix + * raised to the power of the exponent; otherwise, the divisor is 1.
bv/rad>:bv specifies the rule's base value. To calculate the divisor, + * let the radix be rad, and the exponent be the highest exponent of the radix that + * yields a result less than or equal to the base value. Every > character after the radix + * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix + * raised to the power of the exponent; otherwise, the divisor is 1.
-x:The rule is a negative-number rule.
x.x:The rule is an improper fraction rule. If the full stop in + * the middle of the rule name is replaced with the decimal point + * that is used in the language or DecimalFormatSymbols, then that rule will + * have precedence when formatting and parsing this rule. For example, some + * languages use the comma, and can thus be written as x,x instead. For example, + * you can use "x.x: << point >>;x,x: << comma >>;" to + * handle the decimal point that matches the language's natural spelling of + * the punctuation of either the full stop or comma.
0.x:The rule is a proper fraction rule. If the full stop in + * the middle of the rule name is replaced with the decimal point + * that is used in the language or DecimalFormatSymbols, then that rule will + * have precedence when formatting and parsing this rule. For example, some + * languages use the comma, and can thus be written as 0,x instead. For example, + * you can use "0.x: point >>;0,x: comma >>;" to + * handle the decimal point that matches the language's natural spelling of + * the punctuation of either the full stop or comma.
x.0:The rule is a default rule. If the full stop in + * the middle of the rule name is replaced with the decimal point + * that is used in the language or DecimalFormatSymbols, then that rule will + * have precedence when formatting and parsing this rule. For example, some + * languages use the comma, and can thus be written as x,0 instead. For example, + * you can use "x.0: << point;x,0: << comma;" to + * handle the decimal point that matches the language's natural spelling of + * the punctuation of either the full stop or comma.
Inf:The rule for infinity.
NaN:The rule for an IEEE 754 NaN (not a number).
nothingIf the rule's rule descriptor is left out, the base value is one plus the + * preceding rule's base value (or zero if this is the first rule in the list) in a normal + * rule set.  In a fraction rule set, the base value is the same as the preceding rule's + * base value.
+ * + *

A rule set may be either a regular rule set or a fraction rule set, depending + * on whether it is used to format a number's integral part (or the whole number) or a + * number's fractional part. Using a rule set to format a rule's fractional part makes it a + * fraction rule set.

+ * + *

Which rule is used to format a number is defined according to one of the following + * algorithms: If the rule set is a regular rule set, do the following: + * + *

    + *
  • If the rule set includes a default rule (and the number was passed in as a double), + * use the default rule.  (If the number being formatted was passed in as a long, + * the default rule is ignored.)
  • + *
  • If the number is negative, use the negative-number rule.
  • + *
  • If the number has a fractional part and is greater than 1, use the improper fraction + * rule.
  • + *
  • If the number has a fractional part and is between 0 and 1, use the proper fraction + * rule.
  • + *
  • Binary-search the rule list for the rule with the highest base value less than or equal + * to the number. If that rule has two substitutions, its base value is not an even multiple + * of its divisor, and the number is an even multiple of the rule's divisor, use the + * rule that precedes it in the rule list. Otherwise, use the rule itself.
  • + *
+ * + *

If the rule set is a fraction rule set, do the following: + * + *

    + *
  • Ignore negative-number and fraction rules.
  • + *
  • For each rule in the list, multiply the number being formatted (which will always be + * between 0 and 1) by the rule's base value. Keep track of the distance between the result + * the nearest integer.
  • + *
  • Use the rule that produced the result closest to zero in the above calculation. In the + * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is + * to try each rule's base value as a possible denominator of a fraction. Whichever + * denominator produces the fraction closest in value to the number being formatted wins.) If + * the rule following the matching rule has the same base value, use it if the numerator of + * the fraction is anything other than 1; if the numerator is 1, use the original matching + * rule. (This is to allow singular and plural forms of the rule text without a lot of extra + * hassle.)
  • + *
+ * + *

A rule's body consists of a string of characters terminated by a semicolon. The rule + * may include zero, one, or two substitution tokens, and a range of text in + * brackets. The brackets denote optional text (and may also include one or both + * substitutions). The exact meanings of the substitution tokens, and under what conditions + * optional text is omitted, depend on the syntax of the substitution token and the context. + * The rest of the text in a rule body is literal text that is output when the rule matches + * the number being formatted.

+ * + *

A substitution token begins and ends with a token character. The token + * character and the context together specify a mathematical operation to be performed on the + * number being formatted. An optional substitution descriptor specifies how the + * value resulting from that operation is used to fill in the substitution. The position of + * the substitution token in the rule body specifies the location of the resultant text in + * the original rule text.

+ * + *

The meanings of the substitution token characters are as follows:

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
>>in normal ruleDivide the number by the rule's divisor and format the remainder
in negative-number ruleFind the absolute value of the number and format the result
in fraction or default ruleIsolate the number's fractional part and format it.
in rule in fraction rule setNot allowed.
>>>in normal ruleDivide the number by the rule's divisor and format the remainder, + * but bypass the normal rule-selection process and just use the + * rule that precedes this one in this rule list.
in all other rulesNot allowed.
<<in normal ruleDivide the number by the rule's divisor and format the quotient
in negative-number ruleNot allowed.
in fraction or default ruleIsolate the number's integral part and format it.
in rule in fraction rule setMultiply the number by the rule's base value and format the result.
==in all rule setsFormat the number unchanged
[]in normal ruleOmit the optional text if the number is an even multiple of the rule's divisor
in negative-number ruleNot allowed.
in improper-fraction ruleOmit the optional text if the number is between 0 and 1 (same as specifying both an + * x.x rule and a 0.x rule)
in default ruleOmit the optional text if the number is an integer (same as specifying both an x.x + * rule and an x.0 rule)
in proper-fraction ruleNot allowed.
in rule in fraction rule setOmit the optional text if multiplying the number by the rule's base value yields 1.
$(cardinal,plural syntax)$in all rule setsThis provides the ability to choose a word based on the number divided by the radix to the power of the + * exponent of the base value for the specified locale, which is normally equivalent to the << value. + * This uses the cardinal plural rules from PluralFormat. All strings used in the plural format are treated + * as the same base value for parsing.
$(ordinal,plural syntax)$in all rule setsThis provides the ability to choose a word based on the number divided by the radix to the power of the + * exponent of the base value for the specified locale, which is normally equivalent to the << value. + * This uses the ordinal plural rules from PluralFormat. All strings used in the plural format are treated + * as the same base value for parsing.
+ * + *

The substitution descriptor (i.e., the text between the token characters) may take one + * of three forms:

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
a rule set namePerform the mathematical operation on the number, and format the result using the + * named rule set.
a DecimalFormat patternPerform the mathematical operation on the number, and format the result using a + * DecimalFormat with the specified pattern.  The pattern must begin with 0 or #.
nothingPerform the mathematical operation on the number, and format the result using the rule + * set containing the current rule, except: + *
    + *
  • You can't have an empty substitution descriptor with a == substitution.
  • + *
  • If you omit the substitution descriptor in a >> substitution in a fraction rule, + * format the result one digit at a time using the rule set containing the current rule.
  • + *
  • If you omit the substitution descriptor in a << substitution in a rule in a + * fraction rule set, format the result using the default rule set for this formatter.
  • + *
+ *
+ * + *

Whitespace is ignored between a rule set name and a rule set body, between a rule + * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe, + * the apostrophe is ignored, but all text after it becomes significant (this is how you can + * have a rule's rule text begin with whitespace). There is no escape function: the semicolon + * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set + * names. The characters beginning a substitution token are always treated as the beginning + * of a substitution token.

+ * + *

See the resource data and the demo program for annotated examples of real rule sets + * using these features.

+ * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + * + *

Localizations

+ *

Constructors are available that allow the specification of localizations for the + * public rule sets (and also allow more control over what public rule sets are available). + * Localization data is represented as a textual description. The description represents + * an array of arrays of string. The first element is an array of the public rule set names, + * each of these must be one of the public rule set names that appear in the rules. Only + * names in this array will be treated as public rule set names by the API. Each subsequent + * element is an array of localizations of these names. The first element of one of these + * subarrays is the locale name, and the remaining elements are localizations of the + * public rule set names, in the same order as they were listed in the first array.

+ *

In the syntax, angle brackets '<', '>' are used to delimit the arrays, and comma ',' is used + * to separate elements of an array. Whitespace is ignored, unless quoted.

+ *

For example:

+ * < < %foo, %bar, %baz >,
+ *   < en, Foo, Bar, Baz >,
+ *   < fr, 'le Foo', 'le Bar', 'le Baz' >
+ *   < zh, \\u7532, \\u4e59, \\u4e19 > >
+ * 

+ * @author Richard Gillam + * @see NumberFormat + * @see DecimalFormat + * @see PluralFormat + * @see PluralRules + * @stable ICU 2.0 + */ +class U_I18N_API RuleBasedNumberFormat : public NumberFormat { +public: + + //----------------------------------------------------------------------- + // constructors + //----------------------------------------------------------------------- + + /** + * Creates a RuleBasedNumberFormat that behaves according to the description + * passed in. The formatter uses the default locale. + * @param rules A description of the formatter's desired behavior. + * See the class documentation for a complete explanation of the description + * syntax. + * @param perror The parse error if an error was encountered. + * @param status The status indicating whether the constructor succeeded. + * @stable ICU 3.2 + */ + RuleBasedNumberFormat(const UnicodeString& rules, UParseError& perror, UErrorCode& status); + + /** + * Creates a RuleBasedNumberFormat that behaves according to the description + * passed in. The formatter uses the default locale. + *

+ * The localizations data provides information about the public + * rule sets and their localized display names for different + * locales. The first element in the list is an array of the names + * of the public rule sets. The first element in this array is + * the initial default ruleset. The remaining elements in the + * list are arrays of localizations of the names of the public + * rule sets. Each of these is one longer than the initial array, + * with the first String being the ULocale ID, and the remaining + * Strings being the localizations of the rule set names, in the + * same order as the initial array. Arrays are nullptr-terminated. + * @param rules A description of the formatter's desired behavior. + * See the class documentation for a complete explanation of the description + * syntax. + * @param localizations the localization information. + * names in the description. These will be copied by the constructor. + * @param perror The parse error if an error was encountered. + * @param status The status indicating whether the constructor succeeded. + * @stable ICU 3.2 + */ + RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations, + UParseError& perror, UErrorCode& status); + + /** + * Creates a RuleBasedNumberFormat that behaves according to the rules + * passed in. The formatter uses the specified locale to determine the + * characters to use when formatting numerals, and to define equivalences + * for lenient parsing. + * @param rules The formatter rules. + * See the class documentation for a complete explanation of the rule + * syntax. + * @param locale A locale that governs which characters are used for + * formatting values in numerals and which characters are equivalent in + * lenient parsing. + * @param perror The parse error if an error was encountered. + * @param status The status indicating whether the constructor succeeded. + * @stable ICU 2.0 + */ + RuleBasedNumberFormat(const UnicodeString& rules, const Locale& locale, + UParseError& perror, UErrorCode& status); + + /** + * Creates a RuleBasedNumberFormat that behaves according to the description + * passed in. The formatter uses the default locale. + *

+ * The localizations data provides information about the public + * rule sets and their localized display names for different + * locales. The first element in the list is an array of the names + * of the public rule sets. The first element in this array is + * the initial default ruleset. The remaining elements in the + * list are arrays of localizations of the names of the public + * rule sets. Each of these is one longer than the initial array, + * with the first String being the ULocale ID, and the remaining + * Strings being the localizations of the rule set names, in the + * same order as the initial array. Arrays are nullptr-terminated. + * @param rules A description of the formatter's desired behavior. + * See the class documentation for a complete explanation of the description + * syntax. + * @param localizations a list of localizations for the rule set + * names in the description. These will be copied by the constructor. + * @param locale A locale that governs which characters are used for + * formatting values in numerals and which characters are equivalent in + * lenient parsing. + * @param perror The parse error if an error was encountered. + * @param status The status indicating whether the constructor succeeded. + * @stable ICU 3.2 + */ + RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations, + const Locale& locale, UParseError& perror, UErrorCode& status); + + /** + * Creates a RuleBasedNumberFormat from a predefined ruleset. The selector + * code chose among three possible predefined formats: spellout, ordinal, + * and duration. + * @param tag A selector code specifying which kind of formatter to create for that + * locale. There are four legal values: URBNF_SPELLOUT, which creates a formatter that + * spells out a value in words in the desired language, URBNF_ORDINAL, which attaches + * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"), + * URBNF_DURATION, which formats a duration in seconds as hours, minutes, and seconds always rounding down, + * and URBNF_NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering + * systems such as the Hebrew numbering system, or for Roman Numerals, etc. + * NOTE: If you use URBNF_NUMBERING_SYSTEM, you must also call setDefaultRuleSet() to + * specify the exact numbering system you want to use. If you want the default numbering system + * for the locale, call NumberFormat::createInstance() instead of creating a RuleBasedNumberFormat directly. + * @param locale The locale for the formatter. + * @param status The status indicating whether the constructor succeeded. + * @stable ICU 2.0 + */ + RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& locale, UErrorCode& status); + + //----------------------------------------------------------------------- + // boilerplate + //----------------------------------------------------------------------- + + /** + * Copy constructor + * @param rhs the object to be copied from. + * @stable ICU 2.6 + */ + RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs); + + /** + * Assignment operator + * @param rhs the object to be copied from. + * @stable ICU 2.6 + */ + RuleBasedNumberFormat& operator=(const RuleBasedNumberFormat& rhs); + + /** + * Release memory allocated for a RuleBasedNumberFormat when you are finished with it. + * @stable ICU 2.6 + */ + virtual ~RuleBasedNumberFormat(); + + /** + * Clone this object polymorphically. The caller is responsible + * for deleting the result when done. + * @return A copy of the object. + * @stable ICU 2.6 + */ + virtual RuleBasedNumberFormat* clone() const override; + + /** + * Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.6 + */ + virtual bool operator==(const Format& other) const override; + +//----------------------------------------------------------------------- +// public API functions +//----------------------------------------------------------------------- + + /** + * return the rules that were provided to the RuleBasedNumberFormat. + * @return the result String that was passed in + * @stable ICU 2.0 + */ + virtual UnicodeString getRules() const; + + /** + * Return the number of public rule set names. + * @return the number of public rule set names. + * @stable ICU 2.0 + */ + virtual int32_t getNumberOfRuleSetNames() const; + + /** + * Return the name of the index'th public ruleSet. If index is not valid, + * the function returns null. + * @param index the index of the ruleset + * @return the name of the index'th public ruleSet. + * @stable ICU 2.0 + */ + virtual UnicodeString getRuleSetName(int32_t index) const; + + /** + * Return the number of locales for which we have localized rule set display names. + * @return the number of locales for which we have localized rule set display names. + * @stable ICU 3.2 + */ + virtual int32_t getNumberOfRuleSetDisplayNameLocales(void) const; + + /** + * Return the index'th display name locale. + * @param index the index of the locale + * @param status set to a failure code when this function fails + * @return the locale + * @see #getNumberOfRuleSetDisplayNameLocales + * @stable ICU 3.2 + */ + virtual Locale getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const; + + /** + * Return the rule set display names for the provided locale. These are in the same order + * as those returned by getRuleSetName. The locale is matched against the locales for + * which there is display name data, using normal fallback rules. If no locale matches, + * the default display names are returned. (These are the internal rule set names minus + * the leading '%'.) + * @param index the index of the rule set + * @param locale the locale (returned by getRuleSetDisplayNameLocales) for which the localized + * display name is desired + * @return the display name for the given index, which might be bogus if there is an error + * @see #getRuleSetName + * @stable ICU 3.2 + */ + virtual UnicodeString getRuleSetDisplayName(int32_t index, + const Locale& locale = Locale::getDefault()); + + /** + * Return the rule set display name for the provided rule set and locale. + * The locale is matched against the locales for which there is display name data, using + * normal fallback rules. If no locale matches, the default display name is returned. + * @return the display name for the rule set + * @stable ICU 3.2 + * @see #getRuleSetDisplayName + */ + virtual UnicodeString getRuleSetDisplayName(const UnicodeString& ruleSetName, + const Locale& locale = Locale::getDefault()); + + + using NumberFormat::format; + + /** + * Formats the specified 32-bit number using the default ruleset. + * @param number The number to format. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @return A textual representation of the number. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(int32_t number, + UnicodeString& toAppendTo, + FieldPosition& pos) const override; + + /** + * Formats the specified 64-bit number using the default ruleset. + * @param number The number to format. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @return A textual representation of the number. + * @stable ICU 2.1 + */ + virtual UnicodeString& format(int64_t number, + UnicodeString& toAppendTo, + FieldPosition& pos) const override; + /** + * Formats the specified number using the default ruleset. + * @param number The number to format. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @return A textual representation of the number. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(double number, + UnicodeString& toAppendTo, + FieldPosition& pos) const override; + + /** + * Formats the specified number using the named ruleset. + * @param number The number to format. + * @param ruleSetName The name of the rule set to format the number with. + * This must be the name of a valid public rule set for this formatter. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @param status the status + * @return A textual representation of the number. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(int32_t number, + const UnicodeString& ruleSetName, + UnicodeString& toAppendTo, + FieldPosition& pos, + UErrorCode& status) const; + /** + * Formats the specified 64-bit number using the named ruleset. + * @param number The number to format. + * @param ruleSetName The name of the rule set to format the number with. + * This must be the name of a valid public rule set for this formatter. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @param status the status + * @return A textual representation of the number. + * @stable ICU 2.1 + */ + virtual UnicodeString& format(int64_t number, + const UnicodeString& ruleSetName, + UnicodeString& toAppendTo, + FieldPosition& pos, + UErrorCode& status) const; + /** + * Formats the specified number using the named ruleset. + * @param number The number to format. + * @param ruleSetName The name of the rule set to format the number with. + * This must be the name of a valid public rule set for this formatter. + * @param toAppendTo the string that will hold the (appended) result + * @param pos the fieldposition + * @param status the status + * @return A textual representation of the number. + * @stable ICU 2.0 + */ + virtual UnicodeString& format(double number, + const UnicodeString& ruleSetName, + UnicodeString& toAppendTo, + FieldPosition& pos, + UErrorCode& status) const; + +protected: + /** + * Format a decimal number. + * The number is a DigitList wrapper onto a floating point decimal number. + * The default implementation in NumberFormat converts the decimal number + * to a double and formats that. Subclasses of NumberFormat that want + * to specifically handle big decimal numbers must override this method. + * class DecimalFormat does so. + * + * @param number The number, a DigitList format Decimal Floating Point. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @internal + */ + virtual UnicodeString& format(const number::impl::DecimalQuantity &number, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; +public: + + using NumberFormat::parse; + + /** + * Parses the specified string, beginning at the specified position, according + * to this formatter's rules. This will match the string against all of the + * formatter's public rule sets and return the value corresponding to the longest + * parseable substring. This function's behavior is affected by the lenient + * parse mode. + * @param text The string to parse + * @param result the result of the parse, either a double or a long. + * @param parsePosition On entry, contains the position of the first character + * in "text" to examine. On exit, has been updated to contain the position + * of the first character in "text" that wasn't consumed by the parse. + * @see #setLenient + * @stable ICU 2.0 + */ + virtual void parse(const UnicodeString& text, + Formattable& result, + ParsePosition& parsePosition) const override; + +#if !UCONFIG_NO_COLLATION + + /** + * Turns lenient parse mode on and off. + * + * When in lenient parse mode, the formatter uses a Collator for parsing the text. + * Only primary differences are treated as significant. This means that case + * differences, accent differences, alternate spellings of the same letter + * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in + * matching the text. In many cases, numerals will be accepted in place of words + * or phrases as well. + * + * For example, all of the following will correctly parse as 255 in English in + * lenient-parse mode: + *
"two hundred fifty-five" + *
"two hundred fifty five" + *
"TWO HUNDRED FIFTY-FIVE" + *
"twohundredfiftyfive" + *
"2 hundred fifty-5" + * + * The Collator used is determined by the locale that was + * passed to this object on construction. The description passed to this object + * on construction may supply additional collation rules that are appended to the + * end of the default collator for the locale, enabling additional equivalences + * (such as adding more ignorable characters or permitting spelled-out version of + * symbols; see the demo program for examples). + * + * It's important to emphasize that even strict parsing is relatively lenient: it + * will accept some text that it won't produce as output. In English, for example, + * it will correctly parse "two hundred zero" and "fifteen hundred". + * + * @param enabled If true, turns lenient-parse mode on; if false, turns it off. + * @see RuleBasedCollator + * @stable ICU 2.0 + */ + virtual void setLenient(UBool enabled) override; + + /** + * Returns true if lenient-parse mode is turned on. Lenient parsing is off + * by default. + * @return true if lenient-parse mode is turned on. + * @see #setLenient + * @stable ICU 2.0 + */ + virtual inline UBool isLenient(void) const override; + +#endif + + /** + * Override the default rule set to use. If ruleSetName is null, reset + * to the initial default rule set. If the rule set is not a public rule set name, + * U_ILLEGAL_ARGUMENT_ERROR is returned in status. + * @param ruleSetName the name of the rule set, or null to reset the initial default. + * @param status set to failure code when a problem occurs. + * @stable ICU 2.6 + */ + virtual void setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status); + + /** + * Return the name of the current default rule set. If the current rule set is + * not public, returns a bogus (and empty) UnicodeString. + * @return the name of the current default rule set + * @stable ICU 3.0 + */ + virtual UnicodeString getDefaultRuleSetName() const; + + /** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. Note: For getContext, see + * NumberFormat. + * @param value The UDisplayContext value to set. + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @stable ICU 53 + */ + virtual void setContext(UDisplayContext value, UErrorCode& status) override; + + /** + * Get the rounding mode. + * @return A rounding mode + * @stable ICU 60 + */ + virtual ERoundingMode getRoundingMode(void) const override; + + /** + * Set the rounding mode. + * @param roundingMode A rounding mode + * @stable ICU 60 + */ + virtual void setRoundingMode(ERoundingMode roundingMode) override; + +public: + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.8 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Sets the decimal format symbols, which is generally not changed + * by the programmer or user. The formatter takes ownership of + * symbolsToAdopt; the client must not delete it. + * + * @param symbolsToAdopt DecimalFormatSymbols to be adopted. + * @stable ICU 49 + */ + virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt); + + /** + * Sets the decimal format symbols, which is generally not changed + * by the programmer or user. A clone of the symbols is created and + * the symbols is _not_ adopted; the client is still responsible for + * deleting it. + * + * @param symbols DecimalFormatSymbols. + * @stable ICU 49 + */ + virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols); + +private: + RuleBasedNumberFormat() = delete; // default constructor not implemented + + // this will ref the localizations if they are not nullptr + // caller must deref to get adoption + RuleBasedNumberFormat(const UnicodeString& description, LocalizationInfo* localizations, + const Locale& locale, UParseError& perror, UErrorCode& status); + + void init(const UnicodeString& rules, LocalizationInfo* localizations, UParseError& perror, UErrorCode& status); + void initCapitalizationContextInfo(const Locale& thelocale); + void dispose(); + void stripWhitespace(UnicodeString& src); + void initDefaultRuleSet(); + NFRuleSet* findRuleSet(const UnicodeString& name, UErrorCode& status) const; + + /* friend access */ + friend class NFSubstitution; + friend class NFRule; + friend class NFRuleSet; + friend class FractionalPartSubstitution; + + inline NFRuleSet * getDefaultRuleSet() const; + const RuleBasedCollator * getCollator() const; + DecimalFormatSymbols * initializeDecimalFormatSymbols(UErrorCode &status); + const DecimalFormatSymbols * getDecimalFormatSymbols() const; + NFRule * initializeDefaultInfinityRule(UErrorCode &status); + const NFRule * getDefaultInfinityRule() const; + NFRule * initializeDefaultNaNRule(UErrorCode &status); + const NFRule * getDefaultNaNRule() const; + PluralFormat *createPluralFormat(UPluralType pluralType, const UnicodeString &pattern, UErrorCode& status) const; + UnicodeString& adjustForCapitalizationContext(int32_t startPos, UnicodeString& currentResult, UErrorCode& status) const; + UnicodeString& format(int64_t number, NFRuleSet *ruleSet, UnicodeString& toAppendTo, UErrorCode& status) const; + void format(double number, NFRuleSet& rs, UnicodeString& toAppendTo, UErrorCode& status) const; + +private: + NFRuleSet **fRuleSets; + UnicodeString* ruleSetDescriptions; + int32_t numRuleSets; + NFRuleSet *defaultRuleSet; + Locale locale; + RuleBasedCollator* collator; + DecimalFormatSymbols* decimalFormatSymbols; + NFRule *defaultInfinityRule; + NFRule *defaultNaNRule; + ERoundingMode fRoundingMode; + UBool lenient; + UnicodeString* lenientParseRules; + LocalizationInfo* localizations; + UnicodeString originalDescription; + UBool capitalizationInfoSet; + UBool capitalizationForUIListMenu; + UBool capitalizationForStandAlone; + BreakIterator* capitalizationBrkIter; +}; + +// --------------- + +#if !UCONFIG_NO_COLLATION + +inline UBool +RuleBasedNumberFormat::isLenient(void) const { + return lenient; +} + +#endif + +inline NFRuleSet* +RuleBasedNumberFormat::getDefaultRuleSet() const { + return defaultRuleSet; +} + +U_NAMESPACE_END + +/* U_HAVE_RBNF */ +#endif + +#endif /* U_SHOW_CPLUSPLUS_API */ + +/* RBNF_H */ +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbtz.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbtz.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc3483ebf219167a973c1f8b25466e642682d6c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rbtz.h @@ -0,0 +1,373 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2013, International Business Machines Corporation and * +* others. All Rights Reserved. * +******************************************************************************* +*/ +#ifndef RBTZ_H +#define RBTZ_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Rule based customizable time zone + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/basictz.h" +#include "unicode/unistr.h" + +U_NAMESPACE_BEGIN + +// forward declaration +class UVector; +struct Transition; + +/** + * a BasicTimeZone subclass implemented in terms of InitialTimeZoneRule and TimeZoneRule instances + * @see BasicTimeZone + * @see InitialTimeZoneRule + * @see TimeZoneRule + */ +class U_I18N_API RuleBasedTimeZone : public BasicTimeZone { +public: + /** + * Constructs a RuleBasedTimeZone object with the ID and the + * InitialTimeZoneRule. The input InitialTimeZoneRule + * is adopted by this RuleBasedTimeZone, thus the caller must not + * delete it. + * @param id The time zone ID. + * @param initialRule The initial time zone rule. + * @stable ICU 3.8 + */ + RuleBasedTimeZone(const UnicodeString& id, InitialTimeZoneRule* initialRule); + + /** + * Copy constructor. + * @param source The RuleBasedTimeZone object to be copied. + * @stable ICU 3.8 + */ + RuleBasedTimeZone(const RuleBasedTimeZone& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~RuleBasedTimeZone(); + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + RuleBasedTimeZone& operator=(const RuleBasedTimeZone& right); + + /** + * Return true if the given TimeZone objects are + * semantically equal. Objects of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZone objects are + *semantically equal. + * @stable ICU 3.8 + */ + virtual bool operator==(const TimeZone& that) const override; + + /** + * Return true if the given TimeZone objects are + * semantically unequal. Objects of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZone objects are + * semantically unequal. + * @stable ICU 3.8 + */ + virtual bool operator!=(const TimeZone& that) const; + + /** + * Adds the `TimeZoneRule` which represents time transitions. + * The `TimeZoneRule` must have start times, that is, the result + * of `isTransitionRule()` must be true. Otherwise, U_ILLEGAL_ARGUMENT_ERROR + * is set to the error code. + * The input `TimeZoneRule` is adopted by this `RuleBasedTimeZone`; + * the caller must not delete it. Should an error condition prevent + * the successful adoption of the rule, this function will delete it. + * + * After all rules are added, the caller must call `complete()` method to + * make this `RuleBasedTimeZone` ready to handle common time + * zone functions. + * @param rule The `TimeZoneRule`. + * @param status Output param to filled in with a success or an error. + * @stable ICU 3.8 + */ + void addTransitionRule(TimeZoneRule* rule, UErrorCode& status); + + /** + * Makes the TimeZoneRule ready to handle actual timezone + * calculation APIs. This method collects time zone rules specified + * by the caller via the constructor and addTransitionRule() and + * builds internal structure for making the object ready to support + * time zone APIs such as getOffset(), getNextTransition() and others. + * @param status Output param to filled in with a success or an error. + * @stable ICU 3.8 + */ + void complete(UErrorCode& status); + + /** + * Clones TimeZone objects polymorphically. Clients are responsible for deleting + * the TimeZone object cloned. + * + * @return A new copy of this TimeZone object. + * @stable ICU 3.8 + */ + virtual RuleBasedTimeZone* clone() const override; + + /** + * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time in this time zone, taking daylight savings time into + * account) as of a particular reference date. The reference date is used to determine + * whether daylight savings time is in effect and needs to be figured into the offset + * that is returned (in other words, what is the adjusted GMT offset in this time zone + * at this particular date and time?). For the time zones produced by createTimeZone(), + * the reference data is specified according to the Gregorian calendar, and the date + * and time fields are local standard time. + * + *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, + * which returns both the raw and the DST offset for a given time. This method + * is retained only for backward compatibility. + * + * @param era The reference date's era + * @param year The reference date's year + * @param month The reference date's month (0-based; 0 is January) + * @param day The reference date's day-in-month (1-based) + * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) + * @param millis The reference date's milliseconds in day, local standard time + * @param status Output param to filled in with a success or an error. + * @return The offset in milliseconds to add to GMT to get local time. + * @stable ICU 3.8 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const override; + + /** + * Gets the time zone offset, for current date, modified in case of + * daylight savings. This is the offset to add *to* UTC to get local time. + * + *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, + * which returns both the raw and the DST offset for a given time. This method + * is retained only for backward compatibility. + * + * @param era The reference date's era + * @param year The reference date's year + * @param month The reference date's month (0-based; 0 is January) + * @param day The reference date's day-in-month (1-based) + * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) + * @param millis The reference date's milliseconds in day, local standard time + * @param monthLength The length of the given month in days. + * @param status Output param to filled in with a success or an error. + * @return The offset in milliseconds to add to GMT to get local time. + * @stable ICU 3.8 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t millis, + int32_t monthLength, UErrorCode& status) const override; + + /** + * Returns the time zone raw and GMT offset for the given moment + * in time. Upon return, local-millis = GMT-millis + rawOffset + + * dstOffset. All computations are performed in the proleptic + * Gregorian calendar. The default implementation in the TimeZone + * class delegates to the 8-argument getOffset(). + * + * @param date moment in time for which to return offsets, in + * units of milliseconds from January 1, 1970 0:00 GMT, either GMT + * time or local wall time, depending on `local'. + * @param local if true, `date' is local wall time; otherwise it + * is in GMT time. + * @param rawOffset output parameter to receive the raw offset, that + * is, the offset not including DST adjustments + * @param dstOffset output parameter to receive the DST offset, + * that is, the offset to be added to `rawOffset' to obtain the + * total offset between local and GMT time. If DST is not in + * effect, this value is zero; otherwise it is a positive value, + * typically one hour. + * @param ec input-output error code + * @stable ICU 3.8 + */ + virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, + int32_t& dstOffset, UErrorCode& ec) const override; + + /** + * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @param offsetMillis The new raw GMT offset for this time zone. + * @stable ICU 3.8 + */ + virtual void setRawOffset(int32_t offsetMillis) override; + + /** + * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @return The TimeZone's raw GMT offset. + * @stable ICU 3.8 + */ + virtual int32_t getRawOffset(void) const override; + + /** + * Queries if this time zone uses daylight savings time. + * @return true if this time zone uses daylight savings time, + * false, otherwise. + * @stable ICU 3.8 + */ + virtual UBool useDaylightTime(void) const override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Queries if the given date is in daylight savings time in + * this time zone. + * This method is wasteful since it creates a new GregorianCalendar and + * deletes it each time it is called. This is a deprecated method + * and provided only for Java compatibility. + * + * @param date the given UDate. + * @param status Output param filled in with success/error code. + * @return true if the given date is in daylight savings time, + * false, otherwise. + * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. + */ + virtual UBool inDaylightTime(UDate date, UErrorCode& status) const override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Returns true if this zone has the same rule and offset as another zone. + * That is, if this zone differs only in ID, if at all. + * @param other the TimeZone object to be compared with + * @return true if the given zone is the same as this one, + * with the possible exception of the ID + * @stable ICU 3.8 + */ + virtual UBool hasSameRules(const TimeZone& other) const override; + + /** + * Gets the first time zone transition after the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the first transition after the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override; + + /** + * Gets the most recent time zone transition before the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the most recent transition before the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override; + + /** + * Returns the number of TimeZoneRules which represents time transitions, + * for this time zone, that is, all TimeZoneRules for this time zone except + * InitialTimeZoneRule. The return value range is 0 or any positive value. + * @param status Receives error status code. + * @return The number of TimeZoneRules representing time transitions. + * @stable ICU 3.8 + */ + virtual int32_t countTransitionRules(UErrorCode& status) const override; + + /** + * Gets the InitialTimeZoneRule and the set of TimeZoneRule + * which represent time transitions for this time zone. On successful return, + * the argument initial points to non-nullptr InitialTimeZoneRule and + * the array trsrules is filled with 0 or multiple TimeZoneRule + * instances up to the size specified by trscount. The results are referencing the + * rule instance held by this time zone instance. Therefore, after this time zone + * is destructed, they are no longer available. + * @param initial Receives the initial timezone rule + * @param trsrules Receives the timezone transition rules + * @param trscount On input, specify the size of the array 'transitions' receiving + * the timezone transition rules. On output, actual number of + * rules filled in the array will be set. + * @param status Receives error status code. + * @stable ICU 3.8 + */ + virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, + const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const override; + + /** + * Get time zone offsets from local wall time. + * @stable ICU 69 + */ + virtual void getOffsetFromLocal( + UDate date, UTimeZoneLocalOption nonExistingTimeOpt, + UTimeZoneLocalOption duplicatedTimeOpt, + int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const override; + +private: + void deleteRules(void); + void deleteTransitions(void); + UVector* copyRules(UVector* source); + TimeZoneRule* findRuleInFinal(UDate date, UBool local, + int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; + UBool findNext(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const; + UBool findPrev(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const; + int32_t getLocalDelta(int32_t rawBefore, int32_t dstBefore, int32_t rawAfter, int32_t dstAfter, + int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; + UDate getTransitionTime(Transition* transition, UBool local, + int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; + void getOffsetInternal(UDate date, UBool local, int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt, + int32_t& rawOffset, int32_t& dstOffset, UErrorCode& ec) const; + void completeConst(UErrorCode &status) const; + + InitialTimeZoneRule *fInitialRule; + UVector *fHistoricRules; + UVector *fFinalRules; + UVector *fHistoricTransitions; + UBool fUpToDate; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // RBTZ_H + +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/regex.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/regex.h new file mode 100644 index 0000000000000000000000000000000000000000..cc2f9249295ee06d89f6fc9c65149947683068da --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/regex.h @@ -0,0 +1,1882 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 2002-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* file name: regex.h +* encoding: UTF-8 +* indentation:4 +* +* created on: 2002oct22 +* created by: Andy Heninger +* +* ICU Regular Expressions, API for C++ +*/ + +#ifndef REGEX_H +#define REGEX_H + +//#define REGEX_DEBUG + +/** + * \file + * \brief C++ API: Regular Expressions + * + * The ICU API for processing regular expressions consists of two classes, + * `RegexPattern` and `RegexMatcher`. + * `RegexPattern` objects represent a pre-processed, or compiled + * regular expression. They are created from a regular expression pattern string, + * and can be used to create `RegexMatcher` objects for the pattern. + * + * Class `RegexMatcher` bundles together a regular expression + * pattern and a target string to which the search pattern will be applied. + * `RegexMatcher` includes API for doing plain find or search + * operations, for search and replace operations, and for obtaining detailed + * information about bounds of a match. + * + * Note that by constructing `RegexMatcher` objects directly from regular + * expression pattern strings application code can be simplified and the explicit + * need for `RegexPattern` objects can usually be eliminated. + * + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_REGULAR_EXPRESSIONS + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/utext.h" +#include "unicode/parseerr.h" + +#include "unicode/uregex.h" + +// Forward Declarations + +struct UHashtable; + +U_NAMESPACE_BEGIN + +struct Regex8BitSet; +class RegexCImpl; +class RegexMatcher; +class RegexPattern; +struct REStackFrame; +class BreakIterator; +class UnicodeSet; +class UVector; +class UVector32; +class UVector64; + + +/** + * Class `RegexPattern` represents a compiled regular expression. It includes + * factory methods for creating a RegexPattern object from the source (string) form + * of a regular expression, methods for creating RegexMatchers that allow the pattern + * to be applied to input text, and a few convenience methods for simple common + * uses of regular expressions. + * + * Class RegexPattern is not intended to be subclassed. + * + * @stable ICU 2.4 + */ +class U_I18N_API RegexPattern final : public UObject { +public: + + /** + * default constructor. Create a RegexPattern object that refers to no actual + * pattern. Not normally needed; RegexPattern objects are usually + * created using the factory method `compile()`. + * + * @stable ICU 2.4 + */ + RegexPattern(); + + /** + * Copy Constructor. Create a new RegexPattern object that is equivalent + * to the source object. + * @param source the pattern object to be copied. + * @stable ICU 2.4 + */ + RegexPattern(const RegexPattern &source); + + /** + * Destructor. Note that a RegexPattern object must persist so long as any + * RegexMatcher objects that were created from the RegexPattern are active. + * @stable ICU 2.4 + */ + virtual ~RegexPattern(); + + /** + * Comparison operator. Two RegexPattern objects are considered equal if they + * were constructed from identical source patterns using the same #URegexpFlag + * settings. + * @param that a RegexPattern object to compare with "this". + * @return true if the objects are equivalent. + * @stable ICU 2.4 + */ + bool operator==(const RegexPattern& that) const; + + /** + * Comparison operator. Two RegexPattern objects are considered equal if they + * were constructed from identical source patterns using the same #URegexpFlag + * settings. + * @param that a RegexPattern object to compare with "this". + * @return true if the objects are different. + * @stable ICU 2.4 + */ + inline bool operator!=(const RegexPattern& that) const {return ! operator ==(that);} + + /** + * Assignment operator. After assignment, this RegexPattern will behave identically + * to the source object. + * @stable ICU 2.4 + */ + RegexPattern &operator =(const RegexPattern &source); + + /** + * Create an exact copy of this RegexPattern object. Since RegexPattern is not + * intended to be subclassed, clone() and the copy construction are + * equivalent operations. + * @return the copy of this RegexPattern + * @stable ICU 2.4 + */ + virtual RegexPattern *clone() const; + + + /** + * Compiles the regular expression in string form into a RegexPattern + * object. These compile methods, rather than the constructors, are the usual + * way that RegexPattern objects are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * All #URegexpFlag pattern match mode flags are set to their default values. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string rather than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. + * @param pe Receives the position (line and column nubers) of any error + * within the regular expression.) + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 2.4 + */ + static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, + UParseError &pe, + UErrorCode &status); + + /** + * Compiles the regular expression in string form into a RegexPattern + * object. These compile methods, rather than the constructors, are the usual + * way that RegexPattern objects are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * All #URegexpFlag pattern match mode flags are set to their default values. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string rather than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. Note, the text referred + * to by this UText must not be deleted during the lifetime of the + * RegexPattern object or any RegexMatcher object created from it. + * @param pe Receives the position (line and column nubers) of any error + * within the regular expression.) + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 4.6 + */ + static RegexPattern * U_EXPORT2 compile( UText *regex, + UParseError &pe, + UErrorCode &status); + + /** + * Compiles the regular expression in string form into a RegexPattern + * object using the specified #URegexpFlag match mode flags. These compile methods, + * rather than the constructors, are the usual way that RegexPattern objects + * are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string instead of than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. + * @param flags The #URegexpFlag match mode flags to be used, e.g. #UREGEX_CASE_INSENSITIVE. + * @param pe Receives the position (line and column numbers) of any error + * within the regular expression.) + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 2.4 + */ + static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, + uint32_t flags, + UParseError &pe, + UErrorCode &status); + + /** + * Compiles the regular expression in string form into a RegexPattern + * object using the specified #URegexpFlag match mode flags. These compile methods, + * rather than the constructors, are the usual way that RegexPattern objects + * are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string instead of than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. Note, the text referred + * to by this UText must not be deleted during the lifetime of the + * RegexPattern object or any RegexMatcher object created from it. + * @param flags The #URegexpFlag match mode flags to be used, e.g. #UREGEX_CASE_INSENSITIVE. + * @param pe Receives the position (line and column numbers) of any error + * within the regular expression.) + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 4.6 + */ + static RegexPattern * U_EXPORT2 compile( UText *regex, + uint32_t flags, + UParseError &pe, + UErrorCode &status); + + /** + * Compiles the regular expression in string form into a RegexPattern + * object using the specified #URegexpFlag match mode flags. These compile methods, + * rather than the constructors, are the usual way that RegexPattern objects + * are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string instead of than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. + * @param flags The #URegexpFlag match mode flags to be used, e.g. #UREGEX_CASE_INSENSITIVE. + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 2.6 + */ + static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, + uint32_t flags, + UErrorCode &status); + + /** + * Compiles the regular expression in string form into a RegexPattern + * object using the specified #URegexpFlag match mode flags. These compile methods, + * rather than the constructors, are the usual way that RegexPattern objects + * are created. + * + * Note that RegexPattern objects must not be deleted while RegexMatcher + * objects created from the pattern are active. RegexMatchers keep a pointer + * back to their pattern, so premature deletion of the pattern is a + * catastrophic error. + * + * Note that it is often more convenient to construct a RegexMatcher directly + * from a pattern string instead of than separately compiling the pattern and + * then creating a RegexMatcher object from the pattern. + * + * @param regex The regular expression to be compiled. Note, the text referred + * to by this UText must not be deleted during the lifetime of the + * RegexPattern object or any RegexMatcher object created from it. + * @param flags The #URegexpFlag match mode flags to be used, e.g. #UREGEX_CASE_INSENSITIVE. + * @param status A reference to a UErrorCode to receive any errors. + * @return A regexPattern object for the compiled pattern. + * + * @stable ICU 4.6 + */ + static RegexPattern * U_EXPORT2 compile( UText *regex, + uint32_t flags, + UErrorCode &status); + + /** + * Get the #URegexpFlag match mode flags that were used when compiling this pattern. + * @return the #URegexpFlag match mode flags + * @stable ICU 2.4 + */ + virtual uint32_t flags() const; + + /** + * Creates a RegexMatcher that will match the given input against this pattern. The + * RegexMatcher can then be used to perform match, find or replace operations + * on the input. Note that a RegexPattern object must not be deleted while + * RegexMatchers created from it still exist and might possibly be used again. + * + * The matcher will retain a reference to the supplied input string, and all regexp + * pattern matching operations happen directly on this original string. It is + * critical that the string not be altered or deleted before use by the regular + * expression operations is complete. + * + * @param input The input string to which the regular expression will be applied. + * @param status A reference to a UErrorCode to receive any errors. + * @return A RegexMatcher object for this pattern and input. + * + * @stable ICU 2.4 + */ + virtual RegexMatcher *matcher(const UnicodeString &input, + UErrorCode &status) const; + +private: + /** + * Cause a compilation error if an application accidentally attempts to + * create a matcher with a (char16_t *) string as input rather than + * a UnicodeString. Avoids a dangling reference to a temporary string. + * + * To efficiently work with char16_t *strings, wrap the data in a UnicodeString + * using one of the aliasing constructors, such as + * `UnicodeString(UBool isTerminated, const char16_t *text, int32_t textLength);` + * or in a UText, using + * `utext_openUChars(UText *ut, const char16_t *text, int64_t textLength, UErrorCode *status);` + * + */ + RegexMatcher *matcher(const char16_t *input, + UErrorCode &status) const = delete; +public: + + + /** + * Creates a RegexMatcher that will match against this pattern. The + * RegexMatcher can be used to perform match, find or replace operations. + * Note that a RegexPattern object must not be deleted while + * RegexMatchers created from it still exist and might possibly be used again. + * + * @param status A reference to a UErrorCode to receive any errors. + * @return A RegexMatcher object for this pattern and input. + * + * @stable ICU 2.6 + */ + virtual RegexMatcher *matcher(UErrorCode &status) const; + + + /** + * Test whether a string matches a regular expression. This convenience function + * both compiles the regular expression and applies it in a single operation. + * Note that if the same pattern needs to be applied repeatedly, this method will be + * less efficient than creating and reusing a RegexMatcher object. + * + * @param regex The regular expression + * @param input The string data to be matched + * @param pe Receives the position of any syntax errors within the regular expression + * @param status A reference to a UErrorCode to receive any errors. + * @return True if the regular expression exactly matches the full input string. + * + * @stable ICU 2.4 + */ + static UBool U_EXPORT2 matches(const UnicodeString ®ex, + const UnicodeString &input, + UParseError &pe, + UErrorCode &status); + + /** + * Test whether a string matches a regular expression. This convenience function + * both compiles the regular expression and applies it in a single operation. + * Note that if the same pattern needs to be applied repeatedly, this method will be + * less efficient than creating and reusing a RegexMatcher object. + * + * @param regex The regular expression + * @param input The string data to be matched + * @param pe Receives the position of any syntax errors within the regular expression + * @param status A reference to a UErrorCode to receive any errors. + * @return True if the regular expression exactly matches the full input string. + * + * @stable ICU 4.6 + */ + static UBool U_EXPORT2 matches(UText *regex, + UText *input, + UParseError &pe, + UErrorCode &status); + + /** + * Returns the regular expression from which this pattern was compiled. This method will work + * even if the pattern was compiled from a UText. + * + * Note: If the pattern was originally compiled from a UText, and that UText was modified, + * the returned string may no longer reflect the RegexPattern object. + * @stable ICU 2.4 + */ + virtual UnicodeString pattern() const; + + + /** + * Returns the regular expression from which this pattern was compiled. This method will work + * even if the pattern was compiled from a UnicodeString. + * + * Note: This is the original input, not a clone. If the pattern was originally compiled from a + * UText, and that UText was modified, the returned UText may no longer reflect the RegexPattern + * object. + * + * @stable ICU 4.6 + */ + virtual UText *patternText(UErrorCode &status) const; + + + /** + * Get the group number corresponding to a named capture group. + * The returned number can be used with any function that access + * capture groups by number. + * + * The function returns an error status if the specified name does not + * appear in the pattern. + * + * @param groupName The capture group name. + * @param status A UErrorCode to receive any errors. + * + * @stable ICU 55 + */ + virtual int32_t groupNumberFromName(const UnicodeString &groupName, UErrorCode &status) const; + + + /** + * Get the group number corresponding to a named capture group. + * The returned number can be used with any function that access + * capture groups by number. + * + * The function returns an error status if the specified name does not + * appear in the pattern. + * + * @param groupName The capture group name, + * platform invariant characters only. + * @param nameLength The length of the name, or -1 if the name is + * nul-terminated. + * @param status A UErrorCode to receive any errors. + * + * @stable ICU 55 + */ + virtual int32_t groupNumberFromName(const char *groupName, int32_t nameLength, UErrorCode &status) const; + + + /** + * Split a string into fields. Somewhat like split() from Perl or Java. + * Pattern matches identify delimiters that separate the input + * into fields. The input data between the delimiters becomes the + * fields themselves. + * + * If the delimiter pattern includes capture groups, the captured text will + * also appear in the destination array of output strings, interspersed + * with the fields. This is similar to Perl, but differs from Java, + * which ignores the presence of capture groups in the pattern. + * + * Trailing empty fields will always be returned, assuming sufficient + * destination capacity. This differs from the default behavior for Java + * and Perl where trailing empty fields are not returned. + * + * The number of strings produced by the split operation is returned. + * This count includes the strings from capture groups in the delimiter pattern. + * This behavior differs from Java, which ignores capture groups. + * + * For the best performance on split() operations, + * RegexMatcher::split is preferable to this function + * + * @param input The string to be split into fields. The field delimiters + * match the pattern (in the "this" object) + * @param dest An array of UnicodeStrings to receive the results of the split. + * This is an array of actual UnicodeString objects, not an + * array of pointers to strings. Local (stack based) arrays can + * work well here. + * @param destCapacity The number of elements in the destination array. + * If the number of fields found is less than destCapacity, the + * extra strings in the destination array are not altered. + * If the number of destination strings is less than the number + * of fields, the trailing part of the input string, including any + * field delimiters, is placed in the last destination string. + * @param status A reference to a UErrorCode to receive any errors. + * @return The number of fields into which the input string was split. + * @stable ICU 2.4 + */ + virtual int32_t split(const UnicodeString &input, + UnicodeString dest[], + int32_t destCapacity, + UErrorCode &status) const; + + + /** + * Split a string into fields. Somewhat like %split() from Perl or Java. + * Pattern matches identify delimiters that separate the input + * into fields. The input data between the delimiters becomes the + * fields themselves. + * + * If the delimiter pattern includes capture groups, the captured text will + * also appear in the destination array of output strings, interspersed + * with the fields. This is similar to Perl, but differs from Java, + * which ignores the presence of capture groups in the pattern. + * + * Trailing empty fields will always be returned, assuming sufficient + * destination capacity. This differs from the default behavior for Java + * and Perl where trailing empty fields are not returned. + * + * The number of strings produced by the split operation is returned. + * This count includes the strings from capture groups in the delimiter pattern. + * This behavior differs from Java, which ignores capture groups. + * + * For the best performance on split() operations, + * `RegexMatcher::split()` is preferable to this function + * + * @param input The string to be split into fields. The field delimiters + * match the pattern (in the "this" object) + * @param dest An array of mutable UText structs to receive the results of the split. + * If a field is nullptr, a new UText is allocated to contain the results for + * that field. This new UText is not guaranteed to be mutable. + * @param destCapacity The number of elements in the destination array. + * If the number of fields found is less than destCapacity, the + * extra strings in the destination array are not altered. + * If the number of destination strings is less than the number + * of fields, the trailing part of the input string, including any + * field delimiters, is placed in the last destination string. + * @param status A reference to a UErrorCode to receive any errors. + * @return The number of destination strings used. + * + * @stable ICU 4.6 + */ + virtual int32_t split(UText *input, + UText *dest[], + int32_t destCapacity, + UErrorCode &status) const; + + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.4 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.4 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + // + // Implementation Data + // + UText *fPattern; // The original pattern string. + UnicodeString *fPatternString; // The original pattern UncodeString if relevant + uint32_t fFlags; // The flags used when compiling the pattern. + // + UVector64 *fCompiledPat; // The compiled pattern p-code. + UnicodeString fLiteralText; // Any literal string data from the pattern, + // after un-escaping, for use during the match. + + UVector *fSets; // Any UnicodeSets referenced from the pattern. + Regex8BitSet *fSets8; // (and fast sets for latin-1 range.) + + + UErrorCode fDeferredStatus; // status if some prior error has left this + // RegexPattern in an unusable state. + + int32_t fMinMatchLen; // Minimum Match Length. All matches will have length + // >= this value. For some patterns, this calculated + // value may be less than the true shortest + // possible match. + + int32_t fFrameSize; // Size of a state stack frame in the + // execution engine. + + int32_t fDataSize; // The size of the data needed by the pattern that + // does not go on the state stack, but has just + // a single copy per matcher. + + UVector32 *fGroupMap; // Map from capture group number to position of + // the group's variables in the matcher stack frame. + + int32_t fStartType; // Info on how a match must start. + int32_t fInitialStringIdx; // + int32_t fInitialStringLen; + UnicodeSet *fInitialChars; + UChar32 fInitialChar; + Regex8BitSet *fInitialChars8; + UBool fNeedsAltInput; + + UHashtable *fNamedCaptureMap; // Map from capture group names to numbers. + + friend class RegexCompile; + friend class RegexMatcher; + friend class RegexCImpl; + + // + // Implementation Methods + // + void init(); // Common initialization, for use by constructors. + bool initNamedCaptureMap(); // Lazy init for fNamedCaptureMap. + void zap(); // Common cleanup + + void dumpOp(int32_t index) const; + + public: +#ifndef U_HIDE_INTERNAL_API + /** + * Dump a compiled pattern. Internal debug function. + * @internal + */ + void dumpPattern() const; +#endif /* U_HIDE_INTERNAL_API */ +}; + + + +/** + * class RegexMatcher bundles together a regular expression pattern and + * input text to which the expression can be applied. It includes methods + * for testing for matches, and for find and replace operations. + * + *

Class RegexMatcher is not intended to be subclassed.

+ * + * @stable ICU 2.4 + */ +class U_I18N_API RegexMatcher final : public UObject { +public: + + /** + * Construct a RegexMatcher for a regular expression. + * This is a convenience method that avoids the need to explicitly create + * a RegexPattern object. Note that if several RegexMatchers need to be + * created for the same expression, it will be more efficient to + * separately create and cache a RegexPattern object, and use + * its matcher() method to create the RegexMatcher objects. + * + * @param regexp The Regular Expression to be compiled. + * @param flags #URegexpFlag options, such as #UREGEX_CASE_INSENSITIVE. + * @param status Any errors are reported by setting this UErrorCode variable. + * @stable ICU 2.6 + */ + RegexMatcher(const UnicodeString ®exp, uint32_t flags, UErrorCode &status); + + /** + * Construct a RegexMatcher for a regular expression. + * This is a convenience method that avoids the need to explicitly create + * a RegexPattern object. Note that if several RegexMatchers need to be + * created for the same expression, it will be more efficient to + * separately create and cache a RegexPattern object, and use + * its matcher() method to create the RegexMatcher objects. + * + * @param regexp The regular expression to be compiled. + * @param flags #URegexpFlag options, such as #UREGEX_CASE_INSENSITIVE. + * @param status Any errors are reported by setting this UErrorCode variable. + * + * @stable ICU 4.6 + */ + RegexMatcher(UText *regexp, uint32_t flags, UErrorCode &status); + + /** + * Construct a RegexMatcher for a regular expression. + * This is a convenience method that avoids the need to explicitly create + * a RegexPattern object. Note that if several RegexMatchers need to be + * created for the same expression, it will be more efficient to + * separately create and cache a RegexPattern object, and use + * its matcher() method to create the RegexMatcher objects. + * + * The matcher will retain a reference to the supplied input string, and all regexp + * pattern matching operations happen directly on the original string. It is + * critical that the string not be altered or deleted before use by the regular + * expression operations is complete. + * + * @param regexp The Regular Expression to be compiled. + * @param input The string to match. The matcher retains a reference to the + * caller's string; mo copy is made. + * @param flags #URegexpFlag options, such as #UREGEX_CASE_INSENSITIVE. + * @param status Any errors are reported by setting this UErrorCode variable. + * @stable ICU 2.6 + */ + RegexMatcher(const UnicodeString ®exp, const UnicodeString &input, + uint32_t flags, UErrorCode &status); + + /** + * Construct a RegexMatcher for a regular expression. + * This is a convenience method that avoids the need to explicitly create + * a RegexPattern object. Note that if several RegexMatchers need to be + * created for the same expression, it will be more efficient to + * separately create and cache a RegexPattern object, and use + * its matcher() method to create the RegexMatcher objects. + * + * The matcher will make a shallow clone of the supplied input text, and all regexp + * pattern matching operations happen on this clone. While read-only operations on + * the supplied text are permitted, it is critical that the underlying string not be + * altered or deleted before use by the regular expression operations is complete. + * + * @param regexp The Regular Expression to be compiled. + * @param input The string to match. The matcher retains a shallow clone of the text. + * @param flags #URegexpFlag options, such as #UREGEX_CASE_INSENSITIVE. + * @param status Any errors are reported by setting this UErrorCode variable. + * + * @stable ICU 4.6 + */ + RegexMatcher(UText *regexp, UText *input, + uint32_t flags, UErrorCode &status); + +private: + /** + * Cause a compilation error if an application accidentally attempts to + * create a matcher with a (char16_t *) string as input rather than + * a UnicodeString. Avoids a dangling reference to a temporary string. + * + * To efficiently work with char16_t *strings, wrap the data in a UnicodeString + * using one of the aliasing constructors, such as + * `UnicodeString(UBool isTerminated, const char16_t *text, int32_t textLength);` + * or in a UText, using + * `utext_openUChars(UText *ut, const char16_t *text, int64_t textLength, UErrorCode *status);` + */ + RegexMatcher(const UnicodeString ®exp, const char16_t *input, + uint32_t flags, UErrorCode &status) = delete; +public: + + + /** + * Destructor. + * + * @stable ICU 2.4 + */ + virtual ~RegexMatcher(); + + + /** + * Attempts to match the entire input region against the pattern. + * @param status A reference to a UErrorCode to receive any errors. + * @return true if there is a match + * @stable ICU 2.4 + */ + virtual UBool matches(UErrorCode &status); + + + /** + * Resets the matcher, then attempts to match the input beginning + * at the specified startIndex, and extending to the end of the input. + * The input region is reset to include the entire input string. + * A successful match must extend to the end of the input. + * @param startIndex The input string (native) index at which to begin matching. + * @param status A reference to a UErrorCode to receive any errors. + * @return true if there is a match + * @stable ICU 2.8 + */ + virtual UBool matches(int64_t startIndex, UErrorCode &status); + + + /** + * Attempts to match the input string, starting from the beginning of the region, + * against the pattern. Like the matches() method, this function + * always starts at the beginning of the input region; + * unlike that function, it does not require that the entire region be matched. + * + * If the match succeeds then more information can be obtained via the start(), + * end(), and group() functions. + * + * @param status A reference to a UErrorCode to receive any errors. + * @return true if there is a match at the start of the input string. + * @stable ICU 2.4 + */ + virtual UBool lookingAt(UErrorCode &status); + + + /** + * Attempts to match the input string, starting from the specified index, against the pattern. + * The match may be of any length, and is not required to extend to the end + * of the input string. Contrast with match(). + * + * If the match succeeds then more information can be obtained via the start(), + * end(), and group() functions. + * + * @param startIndex The input string (native) index at which to begin matching. + * @param status A reference to a UErrorCode to receive any errors. + * @return true if there is a match. + * @stable ICU 2.8 + */ + virtual UBool lookingAt(int64_t startIndex, UErrorCode &status); + + + /** + * Find the next pattern match in the input string. + * The find begins searching the input at the location following the end of + * the previous match, or at the start of the string if there is no previous match. + * If a match is found, `start()`, `end()` and `group()` + * will provide more information regarding the match. + * Note that if the input string is changed by the application, + * use find(startPos, status) instead of find(), because the saved starting + * position may not be valid with the altered input string. + * @return true if a match is found. + * @stable ICU 2.4 + */ + virtual UBool find(); + + + /** + * Find the next pattern match in the input string. + * The find begins searching the input at the location following the end of + * the previous match, or at the start of the string if there is no previous match. + * If a match is found, `start()`, `end()` and `group()` + * will provide more information regarding the match. + * + * Note that if the input string is changed by the application, + * use find(startPos, status) instead of find(), because the saved starting + * position may not be valid with the altered input string. + * @param status A reference to a UErrorCode to receive any errors. + * @return true if a match is found. + * @stable ICU 55 + */ + virtual UBool find(UErrorCode &status); + + /** + * Resets this RegexMatcher and then attempts to find the next substring of the + * input string that matches the pattern, starting at the specified index. + * + * @param start The (native) index in the input string to begin the search. + * @param status A reference to a UErrorCode to receive any errors. + * @return true if a match is found. + * @stable ICU 2.4 + */ + virtual UBool find(int64_t start, UErrorCode &status); + + + /** + * Returns a string containing the text matched by the previous match. + * If the pattern can match an empty string, an empty string may be returned. + * @param status A reference to a UErrorCode to receive any errors. + * Possible errors are U_REGEX_INVALID_STATE if no match + * has been attempted or the last match failed. + * @return a string containing the matched input text. + * @stable ICU 2.4 + */ + virtual UnicodeString group(UErrorCode &status) const; + + + /** + * Returns a string containing the text captured by the given group + * during the previous match operation. Group(0) is the entire match. + * + * A zero length string is returned both for capture groups that did not + * participate in the match and for actual zero length matches. + * To distinguish between these two cases use the function start(), + * which returns -1 for non-participating groups. + * + * @param groupNum the capture group number + * @param status A reference to a UErrorCode to receive any errors. + * Possible errors are U_REGEX_INVALID_STATE if no match + * has been attempted or the last match failed and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. + * @return the captured text + * @stable ICU 2.4 + */ + virtual UnicodeString group(int32_t groupNum, UErrorCode &status) const; + + /** + * Returns the number of capturing groups in this matcher's pattern. + * @return the number of capture groups + * @stable ICU 2.4 + */ + virtual int32_t groupCount() const; + + + /** + * Returns a shallow clone of the entire live input string with the UText current native index + * set to the beginning of the requested group. + * + * @param dest The UText into which the input should be cloned, or nullptr to create a new UText + * @param group_len A reference to receive the length of the desired capture group + * @param status A reference to a UErrorCode to receive any errors. + * Possible errors are U_REGEX_INVALID_STATE if no match + * has been attempted or the last match failed and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. + * @return dest if non-nullptr, a shallow copy of the input text otherwise + * + * @stable ICU 4.6 + */ + virtual UText *group(UText *dest, int64_t &group_len, UErrorCode &status) const; + + /** + * Returns a shallow clone of the entire live input string with the UText current native index + * set to the beginning of the requested group. + * + * A group length of zero is returned both for capture groups that did not + * participate in the match and for actual zero length matches. + * To distinguish between these two cases use the function start(), + * which returns -1 for non-participating groups. + * + * @param groupNum The capture group number. + * @param dest The UText into which the input should be cloned, or nullptr to create a new UText. + * @param group_len A reference to receive the length of the desired capture group + * @param status A reference to a UErrorCode to receive any errors. + * Possible errors are U_REGEX_INVALID_STATE if no match + * has been attempted or the last match failed and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. + * @return dest if non-nullptr, a shallow copy of the input text otherwise + * + * @stable ICU 4.6 + */ + virtual UText *group(int32_t groupNum, UText *dest, int64_t &group_len, UErrorCode &status) const; + + /** + * Returns the index in the input string of the start of the text matched + * during the previous match operation. + * @param status a reference to a UErrorCode to receive any errors. + * @return The (native) position in the input string of the start of the last match. + * @stable ICU 2.4 + */ + virtual int32_t start(UErrorCode &status) const; + + /** + * Returns the index in the input string of the start of the text matched + * during the previous match operation. + * @param status a reference to a UErrorCode to receive any errors. + * @return The (native) position in the input string of the start of the last match. + * @stable ICU 4.6 + */ + virtual int64_t start64(UErrorCode &status) const; + + + /** + * Returns the index in the input string of the start of the text matched by the + * specified capture group during the previous match operation. Return -1 if + * the capture group exists in the pattern, but was not part of the last match. + * + * @param group the capture group number + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed, and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number + * @return the (native) start position of substring matched by the specified group. + * @stable ICU 2.4 + */ + virtual int32_t start(int32_t group, UErrorCode &status) const; + + /** + * Returns the index in the input string of the start of the text matched by the + * specified capture group during the previous match operation. Return -1 if + * the capture group exists in the pattern, but was not part of the last match. + * + * @param group the capture group number. + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed, and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. + * @return the (native) start position of substring matched by the specified group. + * @stable ICU 4.6 + */ + virtual int64_t start64(int32_t group, UErrorCode &status) const; + + /** + * Returns the index in the input string of the first character following the + * text matched during the previous match operation. + * + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed. + * @return the index of the last character matched, plus one. + * The index value returned is a native index, corresponding to + * code units for the underlying encoding type, for example, + * a byte index for UTF-8. + * @stable ICU 2.4 + */ + virtual int32_t end(UErrorCode &status) const; + + /** + * Returns the index in the input string of the first character following the + * text matched during the previous match operation. + * + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed. + * @return the index of the last character matched, plus one. + * The index value returned is a native index, corresponding to + * code units for the underlying encoding type, for example, + * a byte index for UTF-8. + * @stable ICU 4.6 + */ + virtual int64_t end64(UErrorCode &status) const; + + + /** + * Returns the index in the input string of the character following the + * text matched by the specified capture group during the previous match operation. + * + * @param group the capture group number + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number + * @return the index of the first character following the text + * captured by the specified group during the previous match operation. + * Return -1 if the capture group exists in the pattern but was not part of the match. + * The index value returned is a native index, corresponding to + * code units for the underlying encoding type, for example, + * a byte index for UTF8. + * @stable ICU 2.4 + */ + virtual int32_t end(int32_t group, UErrorCode &status) const; + + /** + * Returns the index in the input string of the character following the + * text matched by the specified capture group during the previous match operation. + * + * @param group the capture group number + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed and + * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number + * @return the index of the first character following the text + * captured by the specified group during the previous match operation. + * Return -1 if the capture group exists in the pattern but was not part of the match. + * The index value returned is a native index, corresponding to + * code units for the underlying encoding type, for example, + * a byte index for UTF8. + * @stable ICU 4.6 + */ + virtual int64_t end64(int32_t group, UErrorCode &status) const; + + /** + * Resets this matcher. The effect is to remove any memory of previous matches, + * and to cause subsequent find() operations to begin at the beginning of + * the input string. + * + * @return this RegexMatcher. + * @stable ICU 2.4 + */ + virtual RegexMatcher &reset(); + + + /** + * Resets this matcher, and set the current input position. + * The effect is to remove any memory of previous matches, + * and to cause subsequent find() operations to begin at + * the specified (native) position in the input string. + * + * The matcher's region is reset to its default, which is the entire + * input string. + * + * An alternative to this function is to set a match region + * beginning at the desired index. + * + * @return this RegexMatcher. + * @stable ICU 2.8 + */ + virtual RegexMatcher &reset(int64_t index, UErrorCode &status); + + + /** + * Resets this matcher with a new input string. This allows instances of RegexMatcher + * to be reused, which is more efficient than creating a new RegexMatcher for + * each input string to be processed. + * @param input The new string on which subsequent pattern matches will operate. + * The matcher retains a reference to the callers string, and operates + * directly on that. Ownership of the string remains with the caller. + * Because no copy of the string is made, it is essential that the + * caller not delete the string until after regexp operations on it + * are done. + * Note that while a reset on the matcher with an input string that is then + * modified across/during matcher operations may be supported currently for UnicodeString, + * this was not originally intended behavior, and support for this is not guaranteed + * in upcoming versions of ICU. + * @return this RegexMatcher. + * @stable ICU 2.4 + */ + virtual RegexMatcher &reset(const UnicodeString &input); + + + /** + * Resets this matcher with a new input string. This allows instances of RegexMatcher + * to be reused, which is more efficient than creating a new RegexMatcher for + * each input string to be processed. + * @param input The new string on which subsequent pattern matches will operate. + * The matcher makes a shallow clone of the given text; ownership of the + * original string remains with the caller. Because no deep copy of the + * text is made, it is essential that the caller not modify the string + * until after regexp operations on it are done. + * @return this RegexMatcher. + * + * @stable ICU 4.6 + */ + virtual RegexMatcher &reset(UText *input); + + + /** + * Set the subject text string upon which the regular expression is looking for matches + * without changing any other aspect of the matching state. + * The new and previous text strings must have the same content. + * + * This function is intended for use in environments where ICU is operating on + * strings that may move around in memory. It provides a mechanism for notifying + * ICU that the string has been relocated, and providing a new UText to access the + * string in its new position. + * + * Note that the regular expression implementation never copies the underlying text + * of a string being matched, but always operates directly on the original text + * provided by the user. Refreshing simply drops the references to the old text + * and replaces them with references to the new. + * + * Caution: this function is normally used only by very specialized, + * system-level code. One example use case is with garbage collection that moves + * the text in memory. + * + * @param input The new (moved) text string. + * @param status Receives errors detected by this function. + * + * @stable ICU 4.8 + */ + virtual RegexMatcher &refreshInputText(UText *input, UErrorCode &status); + +private: + /** + * Cause a compilation error if an application accidentally attempts to + * reset a matcher with a (char16_t *) string as input rather than + * a UnicodeString. Avoids a dangling reference to a temporary string. + * + * To efficiently work with char16_t *strings, wrap the data in a UnicodeString + * using one of the aliasing constructors, such as + * `UnicodeString(UBool isTerminated, const char16_t *text, int32_t textLength);` + * or in a UText, using + * `utext_openUChars(UText *ut, const char16_t *text, int64_t textLength, UErrorCode *status);` + * + */ + RegexMatcher &reset(const char16_t *input) = delete; +public: + + /** + * Returns the input string being matched. Ownership of the string belongs to + * the matcher; it should not be altered or deleted. This method will work even if the input + * was originally supplied as a UText. + * @return the input string + * @stable ICU 2.4 + */ + virtual const UnicodeString &input() const; + + /** + * Returns the input string being matched. This is the live input text; it should not be + * altered or deleted. This method will work even if the input was originally supplied as + * a UnicodeString. + * @return the input text + * + * @stable ICU 4.6 + */ + virtual UText *inputText() const; + + /** + * Returns the input string being matched, either by copying it into the provided + * UText parameter or by returning a shallow clone of the live input. Note that copying + * the entire input may cause significant performance and memory issues. + * @param dest The UText into which the input should be copied, or nullptr to create a new UText + * @param status error code + * @return dest if non-nullptr, a shallow copy of the input text otherwise + * + * @stable ICU 4.6 + */ + virtual UText *getInput(UText *dest, UErrorCode &status) const; + + + /** Sets the limits of this matcher's region. + * The region is the part of the input string that will be searched to find a match. + * Invoking this method resets the matcher, and then sets the region to start + * at the index specified by the start parameter and end at the index specified + * by the end parameter. + * + * Depending on the transparency and anchoring being used (see useTransparentBounds + * and useAnchoringBounds), certain constructs such as anchors may behave differently + * at or around the boundaries of the region + * + * The function will fail if start is greater than limit, or if either index + * is less than zero or greater than the length of the string being matched. + * + * @param start The (native) index to begin searches at. + * @param limit The index to end searches at (exclusive). + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.0 + */ + virtual RegexMatcher ®ion(int64_t start, int64_t limit, UErrorCode &status); + + /** + * Identical to region(start, limit, status) but also allows a start position without + * resetting the region state. + * @param regionStart The region start + * @param regionLimit the limit of the region + * @param startIndex The (native) index within the region bounds at which to begin searches. + * @param status A reference to a UErrorCode to receive any errors. + * If startIndex is not within the specified region bounds, + * U_INDEX_OUTOFBOUNDS_ERROR is returned. + * @stable ICU 4.6 + */ + virtual RegexMatcher ®ion(int64_t regionStart, int64_t regionLimit, int64_t startIndex, UErrorCode &status); + + /** + * Reports the start index of this matcher's region. The searches this matcher + * conducts are limited to finding matches within regionStart (inclusive) and + * regionEnd (exclusive). + * + * @return The starting (native) index of this matcher's region. + * @stable ICU 4.0 + */ + virtual int32_t regionStart() const; + + /** + * Reports the start index of this matcher's region. The searches this matcher + * conducts are limited to finding matches within regionStart (inclusive) and + * regionEnd (exclusive). + * + * @return The starting (native) index of this matcher's region. + * @stable ICU 4.6 + */ + virtual int64_t regionStart64() const; + + + /** + * Reports the end (limit) index (exclusive) of this matcher's region. The searches + * this matcher conducts are limited to finding matches within regionStart + * (inclusive) and regionEnd (exclusive). + * + * @return The ending point (native) of this matcher's region. + * @stable ICU 4.0 + */ + virtual int32_t regionEnd() const; + + /** + * Reports the end (limit) index (exclusive) of this matcher's region. The searches + * this matcher conducts are limited to finding matches within regionStart + * (inclusive) and regionEnd (exclusive). + * + * @return The ending point (native) of this matcher's region. + * @stable ICU 4.6 + */ + virtual int64_t regionEnd64() const; + + /** + * Queries the transparency of region bounds for this matcher. + * See useTransparentBounds for a description of transparent and opaque bounds. + * By default, a matcher uses opaque region boundaries. + * + * @return true if this matcher is using opaque bounds, false if it is not. + * @stable ICU 4.0 + */ + virtual UBool hasTransparentBounds() const; + + /** + * Sets the transparency of region bounds for this matcher. + * Invoking this function with an argument of true will set this matcher to use transparent bounds. + * If the boolean argument is false, then opaque bounds will be used. + * + * Using transparent bounds, the boundaries of this matcher's region are transparent + * to lookahead, lookbehind, and boundary matching constructs. Those constructs can + * see text beyond the boundaries of the region while checking for a match. + * + * With opaque bounds, no text outside of the matcher's region is visible to lookahead, + * lookbehind, and boundary matching constructs. + * + * By default, a matcher uses opaque bounds. + * + * @param b true for transparent bounds; false for opaque bounds + * @return This Matcher; + * @stable ICU 4.0 + **/ + virtual RegexMatcher &useTransparentBounds(UBool b); + + + /** + * Return true if this matcher is using anchoring bounds. + * By default, matchers use anchoring region bounds. + * + * @return true if this matcher is using anchoring bounds. + * @stable ICU 4.0 + */ + virtual UBool hasAnchoringBounds() const; + + + /** + * Set whether this matcher is using Anchoring Bounds for its region. + * With anchoring bounds, pattern anchors such as ^ and $ will match at the start + * and end of the region. Without Anchoring Bounds, anchors will only match at + * the positions they would in the complete text. + * + * Anchoring Bounds are the default for regions. + * + * @param b true if to enable anchoring bounds; false to disable them. + * @return This Matcher + * @stable ICU 4.0 + */ + virtual RegexMatcher &useAnchoringBounds(UBool b); + + + /** + * Return true if the most recent matching operation attempted to access + * additional input beyond the available input text. + * In this case, additional input text could change the results of the match. + * + * hitEnd() is defined for both successful and unsuccessful matches. + * In either case hitEnd() will return true if if the end of the text was + * reached at any point during the matching process. + * + * @return true if the most recent match hit the end of input + * @stable ICU 4.0 + */ + virtual UBool hitEnd() const; + + /** + * Return true the most recent match succeeded and additional input could cause + * it to fail. If this method returns false and a match was found, then more input + * might change the match but the match won't be lost. If a match was not found, + * then requireEnd has no meaning. + * + * @return true if more input could cause the most recent match to no longer match. + * @stable ICU 4.0 + */ + virtual UBool requireEnd() const; + + + /** + * Returns the pattern that is interpreted by this matcher. + * @return the RegexPattern for this RegexMatcher + * @stable ICU 2.4 + */ + virtual const RegexPattern &pattern() const; + + + /** + * Replaces every substring of the input that matches the pattern + * with the given replacement string. This is a convenience function that + * provides a complete find-and-replace-all operation. + * + * This method first resets this matcher. It then scans the input string + * looking for matches of the pattern. Input that is not part of any + * match is left unchanged; each match is replaced in the result by the + * replacement string. The replacement string may contain references to + * capture groups. + * + * @param replacement a string containing the replacement text. + * @param status a reference to a UErrorCode to receive any errors. + * @return a string containing the results of the find and replace. + * @stable ICU 2.4 + */ + virtual UnicodeString replaceAll(const UnicodeString &replacement, UErrorCode &status); + + + /** + * Replaces every substring of the input that matches the pattern + * with the given replacement string. This is a convenience function that + * provides a complete find-and-replace-all operation. + * + * This method first resets this matcher. It then scans the input string + * looking for matches of the pattern. Input that is not part of any + * match is left unchanged; each match is replaced in the result by the + * replacement string. The replacement string may contain references to + * capture groups. + * + * @param replacement a string containing the replacement text. + * @param dest a mutable UText in which the results are placed. + * If nullptr, a new UText will be created (which may not be mutable). + * @param status a reference to a UErrorCode to receive any errors. + * @return a string containing the results of the find and replace. + * If a pre-allocated UText was provided, it will always be used and returned. + * + * @stable ICU 4.6 + */ + virtual UText *replaceAll(UText *replacement, UText *dest, UErrorCode &status); + + + /** + * Replaces the first substring of the input that matches + * the pattern with the replacement string. This is a convenience + * function that provides a complete find-and-replace operation. + * + * This function first resets this RegexMatcher. It then scans the input string + * looking for a match of the pattern. Input that is not part + * of the match is appended directly to the result string; the match is replaced + * in the result by the replacement string. The replacement string may contain + * references to captured groups. + * + * The state of the matcher (the position at which a subsequent find() + * would begin) after completing a replaceFirst() is not specified. The + * RegexMatcher should be reset before doing additional find() operations. + * + * @param replacement a string containing the replacement text. + * @param status a reference to a UErrorCode to receive any errors. + * @return a string containing the results of the find and replace. + * @stable ICU 2.4 + */ + virtual UnicodeString replaceFirst(const UnicodeString &replacement, UErrorCode &status); + + + /** + * Replaces the first substring of the input that matches + * the pattern with the replacement string. This is a convenience + * function that provides a complete find-and-replace operation. + * + * This function first resets this RegexMatcher. It then scans the input string + * looking for a match of the pattern. Input that is not part + * of the match is appended directly to the result string; the match is replaced + * in the result by the replacement string. The replacement string may contain + * references to captured groups. + * + * The state of the matcher (the position at which a subsequent find() + * would begin) after completing a replaceFirst() is not specified. The + * RegexMatcher should be reset before doing additional find() operations. + * + * @param replacement a string containing the replacement text. + * @param dest a mutable UText in which the results are placed. + * If nullptr, a new UText will be created (which may not be mutable). + * @param status a reference to a UErrorCode to receive any errors. + * @return a string containing the results of the find and replace. + * If a pre-allocated UText was provided, it will always be used and returned. + * + * @stable ICU 4.6 + */ + virtual UText *replaceFirst(UText *replacement, UText *dest, UErrorCode &status); + + + /** + * Implements a replace operation intended to be used as part of an + * incremental find-and-replace. + * + * The input string, starting from the end of the previous replacement and ending at + * the start of the current match, is appended to the destination string. Then the + * replacement string is appended to the output string, + * including handling any substitutions of captured text. + * + * For simple, prepackaged, non-incremental find-and-replace + * operations, see replaceFirst() or replaceAll(). + * + * @param dest A UnicodeString to which the results of the find-and-replace are appended. + * @param replacement A UnicodeString that provides the text to be substituted for + * the input text that matched the regexp pattern. The replacement + * text may contain references to captured text from the + * input. + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed, and U_INDEX_OUTOFBOUNDS_ERROR + * if the replacement text specifies a capture group that + * does not exist in the pattern. + * + * @return this RegexMatcher + * @stable ICU 2.4 + * + */ + virtual RegexMatcher &appendReplacement(UnicodeString &dest, + const UnicodeString &replacement, UErrorCode &status); + + + /** + * Implements a replace operation intended to be used as part of an + * incremental find-and-replace. + * + * The input string, starting from the end of the previous replacement and ending at + * the start of the current match, is appended to the destination string. Then the + * replacement string is appended to the output string, + * including handling any substitutions of captured text. + * + * For simple, prepackaged, non-incremental find-and-replace + * operations, see replaceFirst() or replaceAll(). + * + * @param dest A mutable UText to which the results of the find-and-replace are appended. + * Must not be nullptr. + * @param replacement A UText that provides the text to be substituted for + * the input text that matched the regexp pattern. The replacement + * text may contain references to captured text from the input. + * @param status A reference to a UErrorCode to receive any errors. Possible + * errors are U_REGEX_INVALID_STATE if no match has been + * attempted or the last match failed, and U_INDEX_OUTOFBOUNDS_ERROR + * if the replacement text specifies a capture group that + * does not exist in the pattern. + * + * @return this RegexMatcher + * + * @stable ICU 4.6 + */ + virtual RegexMatcher &appendReplacement(UText *dest, + UText *replacement, UErrorCode &status); + + + /** + * As the final step in a find-and-replace operation, append the remainder + * of the input string, starting at the position following the last appendReplacement(), + * to the destination string. `appendTail()` is intended to be invoked after one + * or more invocations of the `RegexMatcher::appendReplacement()`. + * + * @param dest A UnicodeString to which the results of the find-and-replace are appended. + * @return the destination string. + * @stable ICU 2.4 + */ + virtual UnicodeString &appendTail(UnicodeString &dest); + + + /** + * As the final step in a find-and-replace operation, append the remainder + * of the input string, starting at the position following the last appendReplacement(), + * to the destination string. `appendTail()` is intended to be invoked after one + * or more invocations of the `RegexMatcher::appendReplacement()`. + * + * @param dest A mutable UText to which the results of the find-and-replace are appended. + * Must not be nullptr. + * @param status error cod + * @return the destination string. + * + * @stable ICU 4.6 + */ + virtual UText *appendTail(UText *dest, UErrorCode &status); + + + /** + * Split a string into fields. Somewhat like %split() from Perl. + * The pattern matches identify delimiters that separate the input + * into fields. The input data between the matches becomes the + * fields themselves. + * + * @param input The string to be split into fields. The field delimiters + * match the pattern (in the "this" object). This matcher + * will be reset to this input string. + * @param dest An array of UnicodeStrings to receive the results of the split. + * This is an array of actual UnicodeString objects, not an + * array of pointers to strings. Local (stack based) arrays can + * work well here. + * @param destCapacity The number of elements in the destination array. + * If the number of fields found is less than destCapacity, the + * extra strings in the destination array are not altered. + * If the number of destination strings is less than the number + * of fields, the trailing part of the input string, including any + * field delimiters, is placed in the last destination string. + * @param status A reference to a UErrorCode to receive any errors. + * @return The number of fields into which the input string was split. + * @stable ICU 2.6 + */ + virtual int32_t split(const UnicodeString &input, + UnicodeString dest[], + int32_t destCapacity, + UErrorCode &status); + + + /** + * Split a string into fields. Somewhat like %split() from Perl. + * The pattern matches identify delimiters that separate the input + * into fields. The input data between the matches becomes the + * fields themselves. + * + * @param input The string to be split into fields. The field delimiters + * match the pattern (in the "this" object). This matcher + * will be reset to this input string. + * @param dest An array of mutable UText structs to receive the results of the split. + * If a field is nullptr, a new UText is allocated to contain the results for + * that field. This new UText is not guaranteed to be mutable. + * @param destCapacity The number of elements in the destination array. + * If the number of fields found is less than destCapacity, the + * extra strings in the destination array are not altered. + * If the number of destination strings is less than the number + * of fields, the trailing part of the input string, including any + * field delimiters, is placed in the last destination string. + * @param status A reference to a UErrorCode to receive any errors. + * @return The number of fields into which the input string was split. + * + * @stable ICU 4.6 + */ + virtual int32_t split(UText *input, + UText *dest[], + int32_t destCapacity, + UErrorCode &status); + + /** + * Set a processing time limit for match operations with this Matcher. + * + * Some patterns, when matching certain strings, can run in exponential time. + * For practical purposes, the match operation may appear to be in an + * infinite loop. + * When a limit is set a match operation will fail with an error if the + * limit is exceeded. + * + * The units of the limit are steps of the match engine. + * Correspondence with actual processor time will depend on the speed + * of the processor and the details of the specific pattern, but will + * typically be on the order of milliseconds. + * + * By default, the matching time is not limited. + * + * + * @param limit The limit value, or 0 for no limit. + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.0 + */ + virtual void setTimeLimit(int32_t limit, UErrorCode &status); + + /** + * Get the time limit, if any, for match operations made with this Matcher. + * + * @return the maximum allowed time for a match, in units of processing steps. + * @stable ICU 4.0 + */ + virtual int32_t getTimeLimit() const; + + /** + * Set the amount of heap storage available for use by the match backtracking stack. + * The matcher is also reset, discarding any results from previous matches. + * + * ICU uses a backtracking regular expression engine, with the backtrack stack + * maintained on the heap. This function sets the limit to the amount of memory + * that can be used for this purpose. A backtracking stack overflow will + * result in an error from the match operation that caused it. + * + * A limit is desirable because a malicious or poorly designed pattern can use + * excessive memory, potentially crashing the process. A limit is enabled + * by default. + * + * @param limit The maximum size, in bytes, of the matching backtrack stack. + * A value of zero means no limit. + * The limit must be greater or equal to zero. + * + * @param status A reference to a UErrorCode to receive any errors. + * + * @stable ICU 4.0 + */ + virtual void setStackLimit(int32_t limit, UErrorCode &status); + + /** + * Get the size of the heap storage available for use by the back tracking stack. + * + * @return the maximum backtracking stack size, in bytes, or zero if the + * stack size is unlimited. + * @stable ICU 4.0 + */ + virtual int32_t getStackLimit() const; + + + /** + * Set a callback function for use with this Matcher. + * During matching operations the function will be called periodically, + * giving the application the opportunity to terminate a long-running + * match. + * + * @param callback A pointer to the user-supplied callback function. + * @param context User context pointer. The value supplied at the + * time the callback function is set will be saved + * and passed to the callback each time that it is called. + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.0 + */ + virtual void setMatchCallback(URegexMatchCallback *callback, + const void *context, + UErrorCode &status); + + + /** + * Get the callback function for this URegularExpression. + * + * @param callback Out parameter, receives a pointer to the user-supplied + * callback function. + * @param context Out parameter, receives the user context pointer that + * was set when uregex_setMatchCallback() was called. + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.0 + */ + virtual void getMatchCallback(URegexMatchCallback *&callback, + const void *&context, + UErrorCode &status); + + + /** + * Set a progress callback function for use with find operations on this Matcher. + * During find operations, the callback will be invoked after each return from a + * match attempt, giving the application the opportunity to terminate a long-running + * find operation. + * + * @param callback A pointer to the user-supplied callback function. + * @param context User context pointer. The value supplied at the + * time the callback function is set will be saved + * and passed to the callback each time that it is called. + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.6 + */ + virtual void setFindProgressCallback(URegexFindProgressCallback *callback, + const void *context, + UErrorCode &status); + + + /** + * Get the find progress callback function for this URegularExpression. + * + * @param callback Out parameter, receives a pointer to the user-supplied + * callback function. + * @param context Out parameter, receives the user context pointer that + * was set when uregex_setFindProgressCallback() was called. + * @param status A reference to a UErrorCode to receive any errors. + * @stable ICU 4.6 + */ + virtual void getFindProgressCallback(URegexFindProgressCallback *&callback, + const void *&context, + UErrorCode &status); + +#ifndef U_HIDE_INTERNAL_API + /** + * setTrace Debug function, enable/disable tracing of the matching engine. + * For internal ICU development use only. DO NO USE!!!! + * @internal + */ + void setTrace(UBool state); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + +private: + // Constructors and other object boilerplate are private. + // Instances of RegexMatcher can not be assigned, copied, cloned, etc. + RegexMatcher() = delete; // default constructor not implemented + RegexMatcher(const RegexPattern *pat); + RegexMatcher(const RegexMatcher &other) = delete; + RegexMatcher &operator =(const RegexMatcher &rhs) = delete; + void init(UErrorCode &status); // Common initialization + void init2(UText *t, UErrorCode &e); // Common initialization, part 2. + + friend class RegexPattern; + friend class RegexCImpl; +public: +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + void resetPreserveRegion(); // Reset matcher state, but preserve any region. +#endif /* U_HIDE_INTERNAL_API */ +private: + + // + // MatchAt This is the internal interface to the match engine itself. + // Match status comes back in matcher member variables. + // + void MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status); + inline void backTrack(int64_t &inputIdx, int32_t &patIdx); + UBool isWordBoundary(int64_t pos); // perform Perl-like \b test + UBool isUWordBoundary(int64_t pos, UErrorCode &status); // perform RBBI based \b test + // Find a grapheme cluster boundary using a break iterator. For handling \X in regexes. + int64_t followingGCBoundary(int64_t pos, UErrorCode &status); + REStackFrame *resetStack(); + inline REStackFrame *StateSave(REStackFrame *fp, int64_t savePatIdx, UErrorCode &status); + void IncrementTime(UErrorCode &status); + + // Call user find callback function, if set. Return true if operation should be interrupted. + inline UBool findProgressInterrupt(int64_t matchIndex, UErrorCode &status); + + int64_t appendGroup(int32_t groupNum, UText *dest, UErrorCode &status) const; + + UBool findUsingChunk(UErrorCode &status); + void MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &status); + UBool isChunkWordBoundary(int32_t pos); + + const RegexPattern *fPattern; + RegexPattern *fPatternOwned; // Non-nullptr if this matcher owns the pattern, and + // should delete it when through. + + const UnicodeString *fInput; // The string being matched. Only used for input() + UText *fInputText; // The text being matched. Is never nullptr. + UText *fAltInputText; // A shallow copy of the text being matched. + // Only created if the pattern contains backreferences. + int64_t fInputLength; // Full length of the input text. + int32_t fFrameSize; // The size of a frame in the backtrack stack. + + int64_t fRegionStart; // Start of the input region, default = 0. + int64_t fRegionLimit; // End of input region, default to input.length. + + int64_t fAnchorStart; // Region bounds for anchoring operations (^ or $). + int64_t fAnchorLimit; // See useAnchoringBounds + + int64_t fLookStart; // Region bounds for look-ahead/behind and + int64_t fLookLimit; // and other boundary tests. See + // useTransparentBounds + + int64_t fActiveStart; // Currently active bounds for matching. + int64_t fActiveLimit; // Usually is the same as region, but + // is changed to fLookStart/Limit when + // entering look around regions. + + UBool fTransparentBounds; // True if using transparent bounds. + UBool fAnchoringBounds; // True if using anchoring bounds. + + UBool fMatch; // True if the last attempted match was successful. + int64_t fMatchStart; // Position of the start of the most recent match + int64_t fMatchEnd; // First position after the end of the most recent match + // Zero if no previous match, even when a region + // is active. + int64_t fLastMatchEnd; // First position after the end of the previous match, + // or -1 if there was no previous match. + int64_t fAppendPosition; // First position after the end of the previous + // appendReplacement(). As described by the + // JavaDoc for Java Matcher, where it is called + // "append position" + UBool fHitEnd; // True if the last match touched the end of input. + UBool fRequireEnd; // True if the last match required end-of-input + // (matched $ or Z) + + UVector64 *fStack; + REStackFrame *fFrame; // After finding a match, the last active stack frame, + // which will contain the capture group results. + // NOT valid while match engine is running. + + int64_t *fData; // Data area for use by the compiled pattern. + int64_t fSmallData[8]; // Use this for data if it's enough. + + int32_t fTimeLimit; // Max time (in arbitrary steps) to let the + // match engine run. Zero for unlimited. + + int32_t fTime; // Match time, accumulates while matching. + int32_t fTickCounter; // Low bits counter for time. Counts down StateSaves. + // Kept separately from fTime to keep as much + // code as possible out of the inline + // StateSave function. + + int32_t fStackLimit; // Maximum memory size to use for the backtrack + // stack, in bytes. Zero for unlimited. + + URegexMatchCallback *fCallbackFn; // Pointer to match progress callback funct. + // nullptr if there is no callback. + const void *fCallbackContext; // User Context ptr for callback function. + + URegexFindProgressCallback *fFindProgressCallbackFn; // Pointer to match progress callback funct. + // nullptr if there is no callback. + const void *fFindProgressCallbackContext; // User Context ptr for callback function. + + + UBool fInputUniStrMaybeMutable; // Set when fInputText wraps a UnicodeString that may be mutable - compatibility. + + UBool fTraceDebug; // Set true for debug tracing of match engine. + + UErrorCode fDeferredStatus; // Save error state that cannot be immediately + // reported, or that permanently disables this matcher. + + BreakIterator *fWordBreakItr; + BreakIterator *fGCBreakItr; +}; + +U_NAMESPACE_END +#endif // UCONFIG_NO_REGULAR_EXPRESSIONS + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/region.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/region.h new file mode 100644 index 0000000000000000000000000000000000000000..1e19d66f4a5b1e11598e6f94f7c7e8f821e1d7ef --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/region.h @@ -0,0 +1,229 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2014-2016, International Business Machines Corporation and others. + * All Rights Reserved. + ******************************************************************************* + */ + +#ifndef REGION_H +#define REGION_H + +/** + * \file + * \brief C++ API: Region classes (territory containment) + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uregion.h" +#include "unicode/uobject.h" +#include "unicode/uniset.h" +#include "unicode/unistr.h" +#include "unicode/strenum.h" + +U_NAMESPACE_BEGIN + +/** + * Region is the class representing a Unicode Region Code, also known as a + * Unicode Region Subtag, which is defined based upon the BCP 47 standard. We often think of + * "regions" as "countries" when defining the characteristics of a locale. Region codes There are different + * types of region codes that are important to distinguish. + *

+ * Macroregion - A code for a "macro geographical (continental) region, geographical sub-region, or + * selected economic and other grouping" as defined in + * UN M.49 (http://unstats.un.org/unsd/methods/m49/m49regin.htm). + * These are typically 3-digit codes, but contain some 2-letter codes, such as the LDML code QO + * added for Outlying Oceania. Not all UNM.49 codes are defined in LDML, but most of them are. + * Macroregions are represented in ICU by one of three region types: WORLD ( region code 001 ), + * CONTINENTS ( regions contained directly by WORLD ), and SUBCONTINENTS ( things contained directly + * by a continent ). + *

+ * TERRITORY - A Region that is not a Macroregion. These are typically codes for countries, but also + * include areas that are not separate countries, such as the code "AQ" for Antarctica or the code + * "HK" for Hong Kong (SAR China). Overseas dependencies of countries may or may not have separate + * codes. The codes are typically 2-letter codes aligned with the ISO 3166 standard, but BCP47 allows + * for the use of 3-digit codes in the future. + *

+ * UNKNOWN - The code ZZ is defined by Unicode LDML for use to indicate that the Region is unknown, + * or that the value supplied as a region was invalid. + *

+ * DEPRECATED - Region codes that have been defined in the past but are no longer in modern usage, + * usually due to a country splitting into multiple territories or changing its name. + *

+ * GROUPING - A widely understood grouping of territories that has a well defined membership such + * that a region code has been assigned for it. Some of these are UNM.49 codes that do't fall into + * the world/continent/sub-continent hierarchy, while others are just well known groupings that have + * their own region code. Region "EU" (European Union) is one such region code that is a grouping. + * Groupings will never be returned by the getContainingRegion() API, since a different type of region + * ( WORLD, CONTINENT, or SUBCONTINENT ) will always be the containing region instead. + * + * The Region class is not intended for public subclassing. + * + * @author John Emmons + * @stable ICU 51 + */ + +class U_I18N_API Region : public UObject { +public: + /** + * Destructor. + * @stable ICU 51 + */ + virtual ~Region(); + + /** + * Returns true if the two regions are equal. + * @stable ICU 51 + */ + bool operator==(const Region &that) const; + + /** + * Returns true if the two regions are NOT equal; that is, if operator ==() returns false. + * @stable ICU 51 + */ + bool operator!=(const Region &that) const; + + /** + * Returns a pointer to a Region using the given region code. The region code can be either 2-letter ISO code, + * 3-letter ISO code, UNM.49 numeric code, or other valid Unicode Region Code as defined by the LDML specification. + * The identifier will be canonicalized internally using the supplemental metadata as defined in the CLDR. + * If the region code is nullptr or not recognized, the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ) + * @stable ICU 51 + */ + static const Region* U_EXPORT2 getInstance(const char *region_code, UErrorCode &status); + + /** + * Returns a pointer to a Region using the given numeric region code. If the numeric region code is not recognized, + * the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ). + * @stable ICU 51 + */ + static const Region* U_EXPORT2 getInstance (int32_t code, UErrorCode &status); + + /** + * Returns an enumeration over the IDs of all known regions that match the given type. + * @stable ICU 55 + */ + static StringEnumeration* U_EXPORT2 getAvailable(URegionType type, UErrorCode &status); + + /** + * Returns a pointer to the region that contains this region. Returns nullptr if this region is code "001" (World) + * or "ZZ" (Unknown region). For example, calling this method with region "IT" (Italy) returns the + * region "039" (Southern Europe). + * @stable ICU 51 + */ + const Region* getContainingRegion() const; + + /** + * Return a pointer to the region that geographically contains this region and matches the given type, + * moving multiple steps up the containment chain if necessary. Returns nullptr if no containing region can be found + * that matches the given type. Note: The URegionTypes = "URGN_GROUPING", "URGN_DEPRECATED", or "URGN_UNKNOWN" + * are not appropriate for use in this API. nullptr will be returned in this case. For example, calling this method + * with region "IT" (Italy) for type "URGN_CONTINENT" returns the region "150" ( Europe ). + * @stable ICU 51 + */ + const Region* getContainingRegion(URegionType type) const; + + /** + * Return an enumeration over the IDs of all the regions that are immediate children of this region in the + * region hierarchy. These returned regions could be either macro regions, territories, or a mixture of the two, + * depending on the containment data as defined in CLDR. This API may return nullptr if this region doesn't have + * any sub-regions. For example, calling this method with region "150" (Europe) returns an enumeration containing + * the various sub regions of Europe - "039" (Southern Europe) - "151" (Eastern Europe) - "154" (Northern Europe) + * and "155" (Western Europe). + * @stable ICU 55 + */ + StringEnumeration* getContainedRegions(UErrorCode &status) const; + + /** + * Returns an enumeration over the IDs of all the regions that are children of this region anywhere in the region + * hierarchy and match the given type. This API may return an empty enumeration if this region doesn't have any + * sub-regions that match the given type. For example, calling this method with region "150" (Europe) and type + * "URGN_TERRITORY" returns a set containing all the territories in Europe ( "FR" (France) - "IT" (Italy) - "DE" (Germany) etc. ) + * @stable ICU 55 + */ + StringEnumeration* getContainedRegions( URegionType type, UErrorCode &status ) const; + + /** + * Returns true if this region contains the supplied other region anywhere in the region hierarchy. + * @stable ICU 51 + */ + UBool contains(const Region &other) const; + + /** + * For deprecated regions, return an enumeration over the IDs of the regions that are the preferred replacement + * regions for this region. Returns null for a non-deprecated region. For example, calling this method with region + * "SU" (Soviet Union) would return a list of the regions containing "RU" (Russia), "AM" (Armenia), "AZ" (Azerbaijan), etc... + * @stable ICU 55 + */ + StringEnumeration* getPreferredValues(UErrorCode &status) const; + + /** + * Return this region's canonical region code. + * @stable ICU 51 + */ + const char* getRegionCode() const; + + /** + * Return this region's numeric code. + * Returns a negative value if the given region does not have a numeric code assigned to it. + * @stable ICU 51 + */ + int32_t getNumericCode() const; + + /** + * Returns the region type of this region. + * @stable ICU 51 + */ + URegionType getType() const; + +#ifndef U_HIDE_INTERNAL_API + /** + * Cleans up statically allocated memory. + * @internal + */ + static void cleanupRegionData(); +#endif /* U_HIDE_INTERNAL_API */ + +private: + char id[4]; + UnicodeString idStr; + int32_t code; + URegionType fType; + Region *containingRegion; + UVector *containedRegions; + UVector *preferredValues; + + /** + * Default Constructor. Internal - use factory methods only. + */ + Region(); + + + /* + * Initializes the region data from the ICU resource bundles. The region data + * contains the basic relationships such as which regions are known, what the numeric + * codes are, any known aliases, and the territory containment data. + * + * If the region data has already loaded, then this method simply returns without doing + * anything meaningful. + */ + + static void U_CALLCONV loadRegionData(UErrorCode &status); + +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // REGION_H + +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/reldatefmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/reldatefmt.h new file mode 100644 index 0000000000000000000000000000000000000000..4123468c6521c96e545eebb54218d7f6ecacd149 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/reldatefmt.h @@ -0,0 +1,751 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************** +* Copyright (C) 2014-2016, International Business Machines Corporation and +* others. +* All Rights Reserved. +***************************************************************************** +* +* File RELDATEFMT.H +***************************************************************************** +*/ + +#ifndef __RELDATEFMT_H +#define __RELDATEFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/udisplaycontext.h" +#include "unicode/ureldatefmt.h" +#include "unicode/locid.h" +#include "unicode/formattedvalue.h" + +/** + * \file + * \brief C++ API: Formats relative dates such as "1 day ago" or "tomorrow" + */ + +#if !UCONFIG_NO_FORMATTING + +/** + * Represents the unit for formatting a relative date. e.g "in 5 days" + * or "in 3 months" + * @stable ICU 53 + */ +typedef enum UDateRelativeUnit { + + /** + * Seconds + * @stable ICU 53 + */ + UDAT_RELATIVE_SECONDS, + + /** + * Minutes + * @stable ICU 53 + */ + UDAT_RELATIVE_MINUTES, + + /** + * Hours + * @stable ICU 53 + */ + UDAT_RELATIVE_HOURS, + + /** + * Days + * @stable ICU 53 + */ + UDAT_RELATIVE_DAYS, + + /** + * Weeks + * @stable ICU 53 + */ + UDAT_RELATIVE_WEEKS, + + /** + * Months + * @stable ICU 53 + */ + UDAT_RELATIVE_MONTHS, + + /** + * Years + * @stable ICU 53 + */ + UDAT_RELATIVE_YEARS, + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateRelativeUnit value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDAT_RELATIVE_UNIT_COUNT +#endif // U_HIDE_DEPRECATED_API +} UDateRelativeUnit; + +/** + * Represents an absolute unit. + * @stable ICU 53 + */ +typedef enum UDateAbsoluteUnit { + + // Days of week have to remain together and in order from Sunday to + // Saturday. + /** + * Sunday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_SUNDAY, + + /** + * Monday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_MONDAY, + + /** + * Tuesday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_TUESDAY, + + /** + * Wednesday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_WEDNESDAY, + + /** + * Thursday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_THURSDAY, + + /** + * Friday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_FRIDAY, + + /** + * Saturday + * @stable ICU 53 + */ + UDAT_ABSOLUTE_SATURDAY, + + /** + * Day + * @stable ICU 53 + */ + UDAT_ABSOLUTE_DAY, + + /** + * Week + * @stable ICU 53 + */ + UDAT_ABSOLUTE_WEEK, + + /** + * Month + * @stable ICU 53 + */ + UDAT_ABSOLUTE_MONTH, + + /** + * Year + * @stable ICU 53 + */ + UDAT_ABSOLUTE_YEAR, + + /** + * Now + * @stable ICU 53 + */ + UDAT_ABSOLUTE_NOW, + + /** + * Quarter + * @stable ICU 63 + */ + UDAT_ABSOLUTE_QUARTER, + + /** + * Hour + * @stable ICU 65 + */ + UDAT_ABSOLUTE_HOUR, + + /** + * Minute + * @stable ICU 65 + */ + UDAT_ABSOLUTE_MINUTE, + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateAbsoluteUnit value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDAT_ABSOLUTE_UNIT_COUNT = UDAT_ABSOLUTE_NOW + 4 +#endif // U_HIDE_DEPRECATED_API +} UDateAbsoluteUnit; + +/** + * Represents a direction for an absolute unit e.g "Next Tuesday" + * or "Last Tuesday" + * @stable ICU 53 + */ +typedef enum UDateDirection { + + /** + * Two before. Not fully supported in every locale. + * @stable ICU 53 + */ + UDAT_DIRECTION_LAST_2, + + /** + * Last + * @stable ICU 53 + */ + UDAT_DIRECTION_LAST, + + /** + * This + * @stable ICU 53 + */ + UDAT_DIRECTION_THIS, + + /** + * Next + * @stable ICU 53 + */ + UDAT_DIRECTION_NEXT, + + /** + * Two after. Not fully supported in every locale. + * @stable ICU 53 + */ + UDAT_DIRECTION_NEXT_2, + + /** + * Plain, which means the absence of a qualifier. + * @stable ICU 53 + */ + UDAT_DIRECTION_PLAIN, + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateDirection value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDAT_DIRECTION_COUNT +#endif // U_HIDE_DEPRECATED_API +} UDateDirection; + +#if !UCONFIG_NO_BREAK_ITERATION + +U_NAMESPACE_BEGIN + +class BreakIterator; +class RelativeDateTimeCacheData; +class SharedNumberFormat; +class SharedPluralRules; +class SharedBreakIterator; +class NumberFormat; +class UnicodeString; +class FormattedRelativeDateTime; +class FormattedRelativeDateTimeData; + +/** + * An immutable class containing the result of a relative datetime formatting operation. + * + * Instances of this class are immutable and thread-safe. + * + * Not intended for public subclassing. + * + * @stable ICU 64 + */ +class U_I18N_API FormattedRelativeDateTime : public UMemory, public FormattedValue { + public: + /** + * Default constructor; makes an empty FormattedRelativeDateTime. + * @stable ICU 64 + */ + FormattedRelativeDateTime() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} + + /** + * Move constructor: Leaves the source FormattedRelativeDateTime in an undefined state. + * @stable ICU 64 + */ + FormattedRelativeDateTime(FormattedRelativeDateTime&& src) noexcept; + + /** + * Destruct an instance of FormattedRelativeDateTime. + * @stable ICU 64 + */ + virtual ~FormattedRelativeDateTime() override; + + /** Copying not supported; use move constructor instead. */ + FormattedRelativeDateTime(const FormattedRelativeDateTime&) = delete; + + /** Copying not supported; use move assignment instead. */ + FormattedRelativeDateTime& operator=(const FormattedRelativeDateTime&) = delete; + + /** + * Move assignment: Leaves the source FormattedRelativeDateTime in an undefined state. + * @stable ICU 64 + */ + FormattedRelativeDateTime& operator=(FormattedRelativeDateTime&& src) noexcept; + + /** @copydoc FormattedValue::toString() */ + UnicodeString toString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::toTempString() */ + UnicodeString toTempString(UErrorCode& status) const override; + + /** @copydoc FormattedValue::appendTo() */ + Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override; + + /** @copydoc FormattedValue::nextPosition() */ + UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; + + private: + FormattedRelativeDateTimeData *fData; + UErrorCode fErrorCode; + explicit FormattedRelativeDateTime(FormattedRelativeDateTimeData *results) + : fData(results), fErrorCode(U_ZERO_ERROR) {} + explicit FormattedRelativeDateTime(UErrorCode errorCode) + : fData(nullptr), fErrorCode(errorCode) {} + friend class RelativeDateTimeFormatter; +}; + +/** + * Formats simple relative dates. There are two types of relative dates that + * it handles: + *

    + *
  • relative dates with a quantity e.g "in 5 days"
  • + *
  • relative dates without a quantity e.g "next Tuesday"
  • + *
+ *

+ * This API is very basic and is intended to be a building block for more + * fancy APIs. The caller tells it exactly what to display in a locale + * independent way. While this class automatically provides the correct plural + * forms, the grammatical form is otherwise as neutral as possible. It is the + * caller's responsibility to handle cut-off logic such as deciding between + * displaying "in 7 days" or "in 1 week." This API supports relative dates + * involving one single unit. This API does not support relative dates + * involving compound units, + * e.g "in 5 days and 4 hours" nor does it support parsing. + *

+ * This class is mostly thread safe and immutable with the following caveats: + * 1. The assignment operator violates Immutability. It must not be used + * concurrently with other operations. + * 2. Caller must not hold onto adopted pointers. + *

+ * This class is not intended for public subclassing. + *

+ * Here are some examples of use: + *

+ *
+ * UErrorCode status = U_ZERO_ERROR;
+ * UnicodeString appendTo;
+ * RelativeDateTimeFormatter fmt(status);
+ * // Appends "in 1 day"
+ * fmt.format(
+ *     1, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
+ * // Appends "in 3 days"
+ * fmt.format(
+ *     3, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
+ * // Appends "3.2 years ago"
+ * fmt.format(
+ *     3.2, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, appendTo, status);
+ * // Appends "last Sunday"
+ * fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
+ * // Appends "this Sunday"
+ * fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
+ * // Appends "next Sunday"
+ * fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
+ * // Appends "Sunday"
+ * fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
+ *
+ * // Appends "yesterday"
+ * fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, appendTo, status);
+ * // Appends "today"
+ * fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, appendTo, status);
+ * // Appends "tomorrow"
+ * fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, appendTo, status);
+ * // Appends "now"
+ * fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, appendTo, status);
+ *
+ * 
+ *
+ *

+ * In the future, we may add more forms, such as abbreviated/short forms + * (3 secs ago), and relative day periods ("yesterday afternoon"), etc. + * + * The RelativeDateTimeFormatter class is not intended for public subclassing. + * + * @stable ICU 53 + */ +class U_I18N_API RelativeDateTimeFormatter : public UObject { +public: + + /** + * Create RelativeDateTimeFormatter with default locale. + * @stable ICU 53 + */ + RelativeDateTimeFormatter(UErrorCode& status); + + /** + * Create RelativeDateTimeFormatter with given locale. + * @stable ICU 53 + */ + RelativeDateTimeFormatter(const Locale& locale, UErrorCode& status); + + /** + * Create RelativeDateTimeFormatter with given locale and NumberFormat. + * + * @param locale the locale + * @param nfToAdopt Constructed object takes ownership of this pointer. + * It is an error for caller to delete this pointer or change its + * contents after calling this constructor. + * @param status Any error is returned here. + * @stable ICU 53 + */ + RelativeDateTimeFormatter( + const Locale& locale, NumberFormat *nfToAdopt, UErrorCode& status); + + /** + * Create RelativeDateTimeFormatter with given locale, NumberFormat, + * and capitalization context. + * + * @param locale the locale + * @param nfToAdopt Constructed object takes ownership of this pointer. + * It is an error for caller to delete this pointer or change its + * contents after calling this constructor. Caller may pass nullptr for + * this argument if they want default number format behavior. + * @param style the format style. The UDAT_RELATIVE bit field has no effect. + * @param capitalizationContext A value from UDisplayContext that pertains to + * capitalization. + * @param status Any error is returned here. + * @stable ICU 54 + */ + RelativeDateTimeFormatter( + const Locale& locale, + NumberFormat *nfToAdopt, + UDateRelativeDateTimeFormatterStyle style, + UDisplayContext capitalizationContext, + UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 53 + */ + RelativeDateTimeFormatter(const RelativeDateTimeFormatter& other); + + /** + * Assignment operator. + * @stable ICU 53 + */ + RelativeDateTimeFormatter& operator=( + const RelativeDateTimeFormatter& other); + + /** + * Destructor. + * @stable ICU 53 + */ + virtual ~RelativeDateTimeFormatter(); + + /** + * Formats a relative date with a quantity such as "in 5 days" or + * "3 months ago" + * + * This method returns a String. To get more information about the + * formatting result, use formatToValue(). + * + * @param quantity The numerical amount e.g 5. This value is formatted + * according to this object's NumberFormat object. + * @param direction NEXT means a future relative date; LAST means a past + * relative date. If direction is anything else, this method sets + * status to U_ILLEGAL_ARGUMENT_ERROR. + * @param unit the unit e.g day? month? year? + * @param appendTo The string to which the formatted result will be + * appended + * @param status ICU error code returned here. + * @return appendTo + * @stable ICU 53 + */ + UnicodeString& format( + double quantity, + UDateDirection direction, + UDateRelativeUnit unit, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Formats a relative date with a quantity such as "in 5 days" or + * "3 months ago" + * + * This method returns a FormattedRelativeDateTime, which exposes more + * information than the String returned by format(). + * + * @param quantity The numerical amount e.g 5. This value is formatted + * according to this object's NumberFormat object. + * @param direction NEXT means a future relative date; LAST means a past + * relative date. If direction is anything else, this method sets + * status to U_ILLEGAL_ARGUMENT_ERROR. + * @param unit the unit e.g day? month? year? + * @param status ICU error code returned here. + * @return The formatted relative datetime + * @stable ICU 64 + */ + FormattedRelativeDateTime formatToValue( + double quantity, + UDateDirection direction, + UDateRelativeUnit unit, + UErrorCode& status) const; + + /** + * Formats a relative date without a quantity. + * + * This method returns a String. To get more information about the + * formatting result, use formatToValue(). + * + * @param direction NEXT, LAST, THIS, etc. + * @param unit e.g SATURDAY, DAY, MONTH + * @param appendTo The string to which the formatted result will be + * appended. If the value of direction is documented as not being fully + * supported in all locales then this method leaves appendTo unchanged if + * no format string is available. + * @param status ICU error code returned here. + * @return appendTo + * @stable ICU 53 + */ + UnicodeString& format( + UDateDirection direction, + UDateAbsoluteUnit unit, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Formats a relative date without a quantity. + * + * This method returns a FormattedRelativeDateTime, which exposes more + * information than the String returned by format(). + * + * If the string is not available in the requested locale, the return + * value will be empty (calling toString will give an empty string). + * + * @param direction NEXT, LAST, THIS, etc. + * @param unit e.g SATURDAY, DAY, MONTH + * @param status ICU error code returned here. + * @return The formatted relative datetime + * @stable ICU 64 + */ + FormattedRelativeDateTime formatToValue( + UDateDirection direction, + UDateAbsoluteUnit unit, + UErrorCode& status) const; + + /** + * Format a combination of URelativeDateTimeUnit and numeric offset + * using a numeric style, e.g. "1 week ago", "in 1 week", + * "5 weeks ago", "in 5 weeks". + * + * This method returns a String. To get more information about the + * formatting result, use formatNumericToValue(). + * + * @param offset The signed offset for the specified unit. This + * will be formatted according to this object's + * NumberFormat object. + * @param unit The unit to use when formatting the relative + * date, e.g. UDAT_REL_UNIT_WEEK, + * UDAT_REL_UNIT_FRIDAY. + * @param appendTo The string to which the formatted result will be + * appended. + * @param status ICU error code returned here. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString& formatNumeric( + double offset, + URelativeDateTimeUnit unit, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Format a combination of URelativeDateTimeUnit and numeric offset + * using a numeric style, e.g. "1 week ago", "in 1 week", + * "5 weeks ago", "in 5 weeks". + * + * This method returns a FormattedRelativeDateTime, which exposes more + * information than the String returned by formatNumeric(). + * + * @param offset The signed offset for the specified unit. This + * will be formatted according to this object's + * NumberFormat object. + * @param unit The unit to use when formatting the relative + * date, e.g. UDAT_REL_UNIT_WEEK, + * UDAT_REL_UNIT_FRIDAY. + * @param status ICU error code returned here. + * @return The formatted relative datetime + * @stable ICU 64 + */ + FormattedRelativeDateTime formatNumericToValue( + double offset, + URelativeDateTimeUnit unit, + UErrorCode& status) const; + + /** + * Format a combination of URelativeDateTimeUnit and numeric offset + * using a text style if possible, e.g. "last week", "this week", + * "next week", "yesterday", "tomorrow". Falls back to numeric + * style if no appropriate text term is available for the specified + * offset in the object's locale. + * + * This method returns a String. To get more information about the + * formatting result, use formatToValue(). + * + * @param offset The signed offset for the specified unit. + * @param unit The unit to use when formatting the relative + * date, e.g. UDAT_REL_UNIT_WEEK, + * UDAT_REL_UNIT_FRIDAY. + * @param appendTo The string to which the formatted result will be + * appended. + * @param status ICU error code returned here. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString& format( + double offset, + URelativeDateTimeUnit unit, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Format a combination of URelativeDateTimeUnit and numeric offset + * using a text style if possible, e.g. "last week", "this week", + * "next week", "yesterday", "tomorrow". Falls back to numeric + * style if no appropriate text term is available for the specified + * offset in the object's locale. + * + * This method returns a FormattedRelativeDateTime, which exposes more + * information than the String returned by format(). + * + * @param offset The signed offset for the specified unit. + * @param unit The unit to use when formatting the relative + * date, e.g. UDAT_REL_UNIT_WEEK, + * UDAT_REL_UNIT_FRIDAY. + * @param status ICU error code returned here. + * @return The formatted relative datetime + * @stable ICU 64 + */ + FormattedRelativeDateTime formatToValue( + double offset, + URelativeDateTimeUnit unit, + UErrorCode& status) const; + + /** + * Combines a relative date string and a time string in this object's + * locale. This is done with the same date-time separator used for the + * default calendar in this locale. + * + * @param relativeDateString the relative date, e.g 'yesterday' + * @param timeString the time e.g '3:45' + * @param appendTo concatenated date and time appended here + * @param status ICU error code returned here. + * @return appendTo + * @stable ICU 53 + */ + UnicodeString& combineDateAndTime( + const UnicodeString& relativeDateString, + const UnicodeString& timeString, + UnicodeString& appendTo, + UErrorCode& status) const; + + /** + * Returns the NumberFormat this object is using. + * + * @stable ICU 53 + */ + const NumberFormat& getNumberFormat() const; + + /** + * Returns the capitalization context. + * + * @stable ICU 54 + */ + UDisplayContext getCapitalizationContext() const; + + /** + * Returns the format style. + * + * @stable ICU 54 + */ + UDateRelativeDateTimeFormatterStyle getFormatStyle() const; + +private: + const RelativeDateTimeCacheData* fCache; + const SharedNumberFormat *fNumberFormat; + const SharedPluralRules *fPluralRules; + UDateRelativeDateTimeFormatterStyle fStyle; + UDisplayContext fContext; + const SharedBreakIterator *fOptBreakIterator; + Locale fLocale; + void init( + NumberFormat *nfToAdopt, + BreakIterator *brkIter, + UErrorCode &status); + UnicodeString& adjustForContext(UnicodeString &) const; + UBool checkNoAdjustForContext(UErrorCode& status) const; + + template + UnicodeString& doFormat( + F callback, + UnicodeString& appendTo, + UErrorCode& status, + Args... args) const; + + template + FormattedRelativeDateTime doFormatToValue( + F callback, + UErrorCode& status, + Args... args) const; + + void formatImpl( + double quantity, + UDateDirection direction, + UDateRelativeUnit unit, + FormattedRelativeDateTimeData& output, + UErrorCode& status) const; + void formatAbsoluteImpl( + UDateDirection direction, + UDateAbsoluteUnit unit, + FormattedRelativeDateTimeData& output, + UErrorCode& status) const; + void formatNumericImpl( + double offset, + URelativeDateTimeUnit unit, + FormattedRelativeDateTimeData& output, + UErrorCode& status) const; + void formatRelativeImpl( + double offset, + URelativeDateTimeUnit unit, + FormattedRelativeDateTimeData& output, + UErrorCode& status) const; +}; + +U_NAMESPACE_END + +#endif /* !UCONFIG_NO_BREAK_ITERATION */ +#endif /* !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif /* __RELDATEFMT_H */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rep.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rep.h new file mode 100644 index 0000000000000000000000000000000000000000..7115c97b8299ff0d2b809f00c32c452d3438fc5d --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/rep.h @@ -0,0 +1,266 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +************************************************************************** +* Copyright (C) 1999-2012, International Business Machines Corporation and +* others. All Rights Reserved. +************************************************************************** +* Date Name Description +* 11/17/99 aliu Creation. Ported from java. Modified to +* match current UnicodeString API. Forced +* to use name "handleReplaceBetween" because +* of existing methods in UnicodeString. +************************************************************************** +*/ + +#ifndef REP_H +#define REP_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Replaceable String + */ + +U_NAMESPACE_BEGIN + +class UnicodeString; + +/** + * Replaceable is an abstract base class representing a + * string of characters that supports the replacement of a range of + * itself with a new string of characters. It is used by APIs that + * change a piece of text while retaining metadata. Metadata is data + * other than the Unicode characters returned by char32At(). One + * example of metadata is style attributes; another is an edit + * history, marking each character with an author and revision number. + * + *

An implicit aspect of the Replaceable API is that + * during a replace operation, new characters take on the metadata of + * the old characters. For example, if the string "the bold + * font" has range (4, 8) replaced with "strong", then it becomes "the + * strong font". + * + *

Replaceable specifies ranges using a start + * offset and a limit offset. The range of characters thus specified + * includes the characters at offset start..limit-1. That is, the + * start offset is inclusive, and the limit offset is exclusive. + * + *

Replaceable also includes API to access characters + * in the string: length(), charAt(), + * char32At(), and extractBetween(). + * + *

For a subclass to support metadata, typical behavior of + * replace() is the following: + *

    + *
  • Set the metadata of the new text to the metadata of the first + * character replaced
  • + *
  • If no characters are replaced, use the metadata of the + * previous character
  • + *
  • If there is no previous character (i.e. start == 0), use the + * following character
  • + *
  • If there is no following character (i.e. the replaceable was + * empty), use default metadata.
    + *
  • If the code point U+FFFF is seen, it should be interpreted as + * a special marker having no metadata
  • + *
  • + *
+ * If this is not the behavior, the subclass should document any differences. + * @author Alan Liu + * @stable ICU 2.0 + */ +class U_COMMON_API Replaceable : public UObject { + +public: + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~Replaceable(); + + /** + * Returns the number of 16-bit code units in the text. + * @return number of 16-bit code units in text + * @stable ICU 1.8 + */ + inline int32_t length() const; + + /** + * Returns the 16-bit code unit at the given offset into the text. + * @param offset an integer between 0 and length()-1 + * inclusive + * @return 16-bit code unit of text at given offset + * @stable ICU 1.8 + */ + inline char16_t charAt(int32_t offset) const; + + /** + * Returns the 32-bit code point at the given 16-bit offset into + * the text. This assumes the text is stored as 16-bit code units + * with surrogate pairs intermixed. If the offset of a leading or + * trailing code unit of a surrogate pair is given, return the + * code point of the surrogate pair. + * + * @param offset an integer between 0 and length()-1 + * inclusive + * @return 32-bit code point of text at given offset + * @stable ICU 1.8 + */ + inline UChar32 char32At(int32_t offset) const; + + /** + * Copies characters in the range [start, limit) + * into the UnicodeString target. + * @param start offset of first character which will be copied + * @param limit offset immediately following the last character to + * be copied + * @param target UnicodeString into which to copy characters. + * @return A reference to target + * @stable ICU 2.1 + */ + virtual void extractBetween(int32_t start, + int32_t limit, + UnicodeString& target) const = 0; + + /** + * Replaces a substring of this object with the given text. If the + * characters being replaced have metadata, the new characters + * that replace them should be given the same metadata. + * + *

Subclasses must ensure that if the text between start and + * limit is equal to the replacement text, that replace has no + * effect. That is, any metadata + * should be unaffected. In addition, subclasses are encouraged to + * check for initial and trailing identical characters, and make a + * smaller replacement if possible. This will preserve as much + * metadata as possible. + * @param start the beginning index, inclusive; 0 <= start + * <= limit. + * @param limit the ending index, exclusive; start <= limit + * <= length(). + * @param text the text to replace characters start + * to limit - 1 + * @stable ICU 2.0 + */ + virtual void handleReplaceBetween(int32_t start, + int32_t limit, + const UnicodeString& text) = 0; + // Note: All other methods in this class take the names of + // existing UnicodeString methods. This method is the exception. + // It is named differently because all replace methods of + // UnicodeString return a UnicodeString&. The 'between' is + // required in order to conform to the UnicodeString naming + // convention; API taking start/length are named , and + // those taking start/limit are named . The + // 'handle' is added because 'replaceBetween' and + // 'doReplaceBetween' are already taken. + + /** + * Copies a substring of this object, retaining metadata. + * This method is used to duplicate or reorder substrings. + * The destination index must not overlap the source range. + * + * @param start the beginning index, inclusive; 0 <= start <= + * limit. + * @param limit the ending index, exclusive; start <= limit <= + * length(). + * @param dest the destination index. The characters from + * start..limit-1 will be copied to dest. + * Implementations of this method may assume that dest <= start || + * dest >= limit. + * @stable ICU 2.0 + */ + virtual void copy(int32_t start, int32_t limit, int32_t dest) = 0; + + /** + * Returns true if this object contains metadata. If a + * Replaceable object has metadata, calls to the Replaceable API + * must be made so as to preserve metadata. If it does not, calls + * to the Replaceable API may be optimized to improve performance. + * The default implementation returns true. + * @return true if this object contains metadata + * @stable ICU 2.2 + */ + virtual UBool hasMetaData() const; + + /** + * Clone this object, an instance of a subclass of Replaceable. + * Clones can be used concurrently in multiple threads. + * If a subclass does not implement clone(), or if an error occurs, + * then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.6 + */ + virtual Replaceable *clone() const; + +protected: + + /** + * Default constructor. + * @stable ICU 2.4 + */ + inline Replaceable(); + + /* + * Assignment operator not declared. The compiler will provide one + * which does nothing since this class does not contain any data members. + * API/code coverage may show the assignment operator as present and + * untested - ignore. + * Subclasses need this assignment operator if they use compiler-provided + * assignment operators of their own. An alternative to not declaring one + * here would be to declare and empty-implement a protected or public one. + Replaceable &Replaceable::operator=(const Replaceable &); + */ + + /** + * Virtual version of length(). + * @stable ICU 2.4 + */ + virtual int32_t getLength() const = 0; + + /** + * Virtual version of charAt(). + * @stable ICU 2.4 + */ + virtual char16_t getCharAt(int32_t offset) const = 0; + + /** + * Virtual version of char32At(). + * @stable ICU 2.4 + */ + virtual UChar32 getChar32At(int32_t offset) const = 0; +}; + +inline Replaceable::Replaceable() {} + +inline int32_t +Replaceable::length() const { + return getLength(); +} + +inline char16_t +Replaceable::charAt(int32_t offset) const { + return getCharAt(offset); +} + +inline UChar32 +Replaceable::char32At(int32_t offset) const { + return getChar32At(offset); +} + +// There is no rep.cpp, see unistr.cpp for Replaceable function implementations. + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/resbund.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/resbund.h new file mode 100644 index 0000000000000000000000000000000000000000..30fc2ac0ab235e3e859c9784658100270b350fee --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/resbund.h @@ -0,0 +1,498 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1996-2013, International Business Machines Corporation +* and others. All Rights Reserved. +* +****************************************************************************** +* +* File resbund.h +* +* CREATED BY +* Richard Gillam +* +* Modification History: +* +* Date Name Description +* 2/5/97 aliu Added scanForLocaleInFile. Added +* constructor which attempts to read resource bundle +* from a specific file, without searching other files. +* 2/11/97 aliu Added UErrorCode return values to constructors. Fixed +* infinite loops in scanForFile and scanForLocale. +* Modified getRawResourceData to not delete storage +* in localeData and resourceData which it doesn't own. +* Added Mac compatibility #ifdefs for tellp() and +* ios::nocreate. +* 2/18/97 helena Updated with 100% documentation coverage. +* 3/13/97 aliu Rewrote to load in entire resource bundle and store +* it as a Hashtable of ResourceBundleData objects. +* Added state table to govern parsing of files. +* Modified to load locale index out of new file +* distinct from default.txt. +* 3/25/97 aliu Modified to support 2-d arrays, needed for timezone +* data. Added support for custom file suffixes. Again, +* needed to support timezone data. +* 4/7/97 aliu Cleaned up. +* 03/02/99 stephen Removed dependency on FILE*. +* 03/29/99 helena Merged Bertrand and Stephen's changes. +* 06/11/99 stephen Removed parsing of .txt files. +* Reworked to use new binary format. +* Cleaned up. +* 06/14/99 stephen Removed methods taking a filename suffix. +* 11/09/99 weiv Added getLocale(), fRealLocale, removed fRealLocaleID +****************************************************************************** +*/ + +#ifndef RESBUND_H +#define RESBUND_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/ures.h" +#include "unicode/unistr.h" +#include "unicode/locid.h" + +/** + * \file + * \brief C++ API: Resource Bundle + */ + +U_NAMESPACE_BEGIN + +/** + * A class representing a collection of resource information pertaining to a given + * locale. A resource bundle provides a way of accessing locale- specific information in + * a data file. You create a resource bundle that manages the resources for a given + * locale and then ask it for individual resources. + *

+ * Resource bundles in ICU4C are currently defined using text files which conform to the following + * BNF definition. + * More on resource bundle concepts and syntax can be found in the + * Users Guide. + *

+ * + * The ResourceBundle class is not suitable for subclassing. + * + * @stable ICU 2.0 + */ +class U_COMMON_API ResourceBundle : public UObject { +public: + /** + * Constructor + * + * @param packageName The packageName and locale together point to an ICU udata object, + * as defined by udata_open( packageName, "res", locale, err) + * or equivalent. Typically, packageName will refer to a (.dat) file, or to + * a package registered with udata_setAppData(). Using a full file or directory + * pathname for packageName is deprecated. + * @param locale This is the locale this resource bundle is for. To get resources + * for the French locale, for example, you would create a + * ResourceBundle passing Locale::FRENCH for the "locale" parameter, + * and all subsequent calls to that resource bundle will return + * resources that pertain to the French locale. If the caller doesn't + * pass a locale parameter, the default locale for the system (as + * returned by Locale::getDefault()) will be used. + * @param err The Error Code. + * The UErrorCode& err parameter is used to return status information to the user. To + * check whether the construction succeeded or not, you should check the value of + * U_SUCCESS(err). If you wish more detailed information, you can check for + * informational error results which still indicate success. U_USING_FALLBACK_WARNING + * indicates that a fall back locale was used. For example, 'de_CH' was requested, + * but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that + * the default locale data was used; neither the requested locale nor any of its + * fall back locales could be found. + * @stable ICU 2.0 + */ + ResourceBundle(const UnicodeString& packageName, + const Locale& locale, + UErrorCode& err); + + /** + * Construct a resource bundle for the default bundle in the specified package. + * + * @param packageName The packageName and locale together point to an ICU udata object, + * as defined by udata_open( packageName, "res", locale, err) + * or equivalent. Typically, packageName will refer to a (.dat) file, or to + * a package registered with udata_setAppData(). Using a full file or directory + * pathname for packageName is deprecated. + * @param err A UErrorCode value + * @stable ICU 2.0 + */ + ResourceBundle(const UnicodeString& packageName, + UErrorCode& err); + + /** + * Construct a resource bundle for the ICU default bundle. + * + * @param err A UErrorCode value + * @stable ICU 2.0 + */ + ResourceBundle(UErrorCode &err); + + /** + * Standard constructor, constructs a resource bundle for the locale-specific + * bundle in the specified package. + * + * @param packageName The packageName and locale together point to an ICU udata object, + * as defined by udata_open( packageName, "res", locale, err) + * or equivalent. Typically, packageName will refer to a (.dat) file, or to + * a package registered with udata_setAppData(). Using a full file or directory + * pathname for packageName is deprecated. + * nullptr is used to refer to ICU data. + * @param locale The locale for which to open a resource bundle. + * @param err A UErrorCode value + * @stable ICU 2.0 + */ + ResourceBundle(const char* packageName, + const Locale& locale, + UErrorCode& err); + + /** + * Copy constructor. + * + * @param original The resource bundle to copy. + * @stable ICU 2.0 + */ + ResourceBundle(const ResourceBundle &original); + + /** + * Constructor from a C UResourceBundle. The resource bundle is + * copied and not adopted. ures_close will still need to be used on the + * original resource bundle. + * + * @param res A pointer to the C resource bundle. + * @param status A UErrorCode value. + * @stable ICU 2.0 + */ + ResourceBundle(UResourceBundle *res, + UErrorCode &status); + + /** + * Assignment operator. + * + * @param other The resource bundle to copy. + * @stable ICU 2.0 + */ + ResourceBundle& + operator=(const ResourceBundle& other); + + /** Destructor. + * @stable ICU 2.0 + */ + virtual ~ResourceBundle(); + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + ResourceBundle *clone() const; + + /** + * Returns the size of a resource. Size for scalar types is always 1, and for vector/table types is + * the number of child resources. + * @warning Integer array is treated as a scalar type. There are no + * APIs to access individual members of an integer array. It + * is always returned as a whole. + * + * @return number of resources in a given resource. + * @stable ICU 2.0 + */ + int32_t + getSize(void) const; + + /** + * returns a string from a string resource type + * + * @param status fills in the outgoing error code + * could be U_MISSING_RESOURCE_ERROR if the key is not found + * could be a warning + * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING + * @return a pointer to a zero-terminated char16_t array which lives in a memory mapped/DLL file. + * @stable ICU 2.0 + */ + UnicodeString + getString(UErrorCode& status) const; + + /** + * returns a binary data from a resource. Can be used at most primitive resource types (binaries, + * strings, ints) + * + * @param len fills in the length of resulting byte chunk + * @param status fills in the outgoing error code + * could be U_MISSING_RESOURCE_ERROR if the key is not found + * could be a warning + * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING + * @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file. + * @stable ICU 2.0 + */ + const uint8_t* + getBinary(int32_t& len, UErrorCode& status) const; + + + /** + * returns an integer vector from a resource. + * + * @param len fills in the length of resulting integer vector + * @param status fills in the outgoing error code + * could be U_MISSING_RESOURCE_ERROR if the key is not found + * could be a warning + * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING + * @return a pointer to a vector of integers that lives in a memory mapped/DLL file. + * @stable ICU 2.0 + */ + const int32_t* + getIntVector(int32_t& len, UErrorCode& status) const; + + /** + * returns an unsigned integer from a resource. + * This integer is originally 28 bits. + * + * @param status fills in the outgoing error code + * could be U_MISSING_RESOURCE_ERROR if the key is not found + * could be a warning + * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING + * @return an unsigned integer value + * @stable ICU 2.0 + */ + uint32_t + getUInt(UErrorCode& status) const; + + /** + * returns a signed integer from a resource. + * This integer is originally 28 bit and the sign gets propagated. + * + * @param status fills in the outgoing error code + * could be U_MISSING_RESOURCE_ERROR if the key is not found + * could be a warning + * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING + * @return a signed integer value + * @stable ICU 2.0 + */ + int32_t + getInt(UErrorCode& status) const; + + /** + * Checks whether the resource has another element to iterate over. + * + * @return true if there are more elements, false if there is no more elements + * @stable ICU 2.0 + */ + UBool + hasNext(void) const; + + /** + * Resets the internal context of a resource so that iteration starts from the first element. + * + * @stable ICU 2.0 + */ + void + resetIterator(void); + + /** + * Returns the key associated with this resource. Not all the resources have a key - only + * those that are members of a table. + * + * @return a key associated to this resource, or nullptr if it doesn't have a key + * @stable ICU 2.0 + */ + const char* + getKey(void) const; + + /** + * Gets the locale ID of the resource bundle as a string. + * Same as getLocale().getName() . + * + * @return the locale ID of the resource bundle as a string + * @stable ICU 2.0 + */ + const char* + getName(void) const; + + + /** + * Returns the type of a resource. Available types are defined in enum UResType + * + * @return type of the given resource. + * @stable ICU 2.0 + */ + UResType + getType(void) const; + + /** + * Returns the next resource in a given resource or nullptr if there are no more resources + * + * @param status fills in the outgoing error code + * @return ResourceBundle object. + * @stable ICU 2.0 + */ + ResourceBundle + getNext(UErrorCode& status); + + /** + * Returns the next string in a resource or nullptr if there are no more resources + * to iterate over. + * + * @param status fills in the outgoing error code + * @return an UnicodeString object. + * @stable ICU 2.0 + */ + UnicodeString + getNextString(UErrorCode& status); + + /** + * Returns the next string in a resource or nullptr if there are no more resources + * to iterate over. + * + * @param key fill in for key associated with this string + * @param status fills in the outgoing error code + * @return an UnicodeString object. + * @stable ICU 2.0 + */ + UnicodeString + getNextString(const char ** key, + UErrorCode& status); + + /** + * Returns the resource in a resource at the specified index. + * + * @param index an index to the wanted resource. + * @param status fills in the outgoing error code + * @return ResourceBundle object. If there is an error, resource is invalid. + * @stable ICU 2.0 + */ + ResourceBundle + get(int32_t index, + UErrorCode& status) const; + + /** + * Returns the string in a given resource at the specified index. + * + * @param index an index to the wanted string. + * @param status fills in the outgoing error code + * @return an UnicodeString object. If there is an error, string is bogus + * @stable ICU 2.0 + */ + UnicodeString + getStringEx(int32_t index, + UErrorCode& status) const; + + /** + * Returns a resource in a resource that has a given key. This procedure works only with table + * resources. + * + * @param key a key associated with the wanted resource + * @param status fills in the outgoing error code. + * @return ResourceBundle object. If there is an error, resource is invalid. + * @stable ICU 2.0 + */ + ResourceBundle + get(const char* key, + UErrorCode& status) const; + + /** + * Returns a string in a resource that has a given key. This procedure works only with table + * resources. + * + * @param key a key associated with the wanted string + * @param status fills in the outgoing error code + * @return an UnicodeString object. If there is an error, string is bogus + * @stable ICU 2.0 + */ + UnicodeString + getStringEx(const char* key, + UErrorCode& status) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Return the version number associated with this ResourceBundle as a string. Please + * use getVersion, as this method is going to be deprecated. + * + * @return A version number string as specified in the resource bundle or its parent. + * The caller does not own this string. + * @see getVersion + * @deprecated ICU 2.8 Use getVersion instead. + */ + const char* + getVersionNumber(void) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Return the version number associated with this ResourceBundle as a UVersionInfo array. + * + * @param versionInfo A UVersionInfo array that is filled with the version number + * as specified in the resource bundle or its parent. + * @stable ICU 2.0 + */ + void + getVersion(UVersionInfo versionInfo) const; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Return the Locale associated with this ResourceBundle. + * + * @return a Locale object + * @deprecated ICU 2.8 Use getLocale(ULocDataLocaleType type, UErrorCode &status) overload instead. + */ + const Locale& + getLocale(void) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Return the Locale associated with this ResourceBundle. + * @param type You can choose between requested, valid and actual + * locale. For description see the definition of + * ULocDataLocaleType in uloc.h + * @param status just for catching illegal arguments + * + * @return a Locale object + * @stable ICU 2.8 + */ + const Locale + getLocale(ULocDataLocaleType type, UErrorCode &status) const; +#ifndef U_HIDE_INTERNAL_API + /** + * This API implements multilevel fallback + * @internal + */ + ResourceBundle + getWithFallback(const char* key, UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + ResourceBundle() = delete; // default constructor not implemented + + UResourceBundle *fResource; + void constructForLocale(const UnicodeString& path, const Locale& locale, UErrorCode& error); + Locale *fLocale; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/schriter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/schriter.h new file mode 100644 index 0000000000000000000000000000000000000000..a2ab17982d10106cb5d131f037f8f2e0f059fb3b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/schriter.h @@ -0,0 +1,187 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1998-2005, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* +* File schriter.h +* +* Modification History: +* +* Date Name Description +* 05/05/99 stephen Cleaned up. +****************************************************************************** +*/ + +#ifndef SCHRITER_H +#define SCHRITER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/chariter.h" +#include "unicode/uchriter.h" + +/** + * \file + * \brief C++ API: String Character Iterator + */ + +U_NAMESPACE_BEGIN +/** + * A concrete subclass of CharacterIterator that iterates over the + * characters (code units or code points) in a UnicodeString. + * It's possible not only to create an + * iterator that iterates over an entire UnicodeString, but also to + * create one that iterates over only a subrange of a UnicodeString + * (iterators over different subranges of the same UnicodeString don't + * compare equal). + * @see CharacterIterator + * @see ForwardCharacterIterator + * @stable ICU 2.0 + */ +class U_COMMON_API StringCharacterIterator : public UCharCharacterIterator { +public: + /** + * Create an iterator over the UnicodeString referred to by "textStr". + * The UnicodeString object is copied. + * The iteration range is the whole string, and the starting position is 0. + * @param textStr The unicode string used to create an iterator + * @stable ICU 2.0 + */ + StringCharacterIterator(const UnicodeString& textStr); + + /** + * Create an iterator over the UnicodeString referred to by "textStr". + * The iteration range is the whole string, and the starting + * position is specified by "textPos". If "textPos" is outside the valid + * iteration range, the behavior of this object is undefined. + * @param textStr The unicode string used to create an iterator + * @param textPos The starting position of the iteration + * @stable ICU 2.0 + */ + StringCharacterIterator(const UnicodeString& textStr, + int32_t textPos); + + /** + * Create an iterator over the UnicodeString referred to by "textStr". + * The UnicodeString object is copied. + * The iteration range begins with the code unit specified by + * "textBegin" and ends with the code unit BEFORE the code unit specified + * by "textEnd". The starting position is specified by "textPos". If + * "textBegin" and "textEnd" don't form a valid range on "text" (i.e., + * textBegin >= textEnd or either is negative or greater than text.size()), + * or "textPos" is outside the range defined by "textBegin" and "textEnd", + * the behavior of this iterator is undefined. + * @param textStr The unicode string used to create the StringCharacterIterator + * @param textBegin The begin position of the iteration range + * @param textEnd The end position of the iteration range + * @param textPos The starting position of the iteration + * @stable ICU 2.0 + */ + StringCharacterIterator(const UnicodeString& textStr, + int32_t textBegin, + int32_t textEnd, + int32_t textPos); + + /** + * Copy constructor. The new iterator iterates over the same range + * of the same string as "that", and its initial position is the + * same as "that"'s current position. + * The UnicodeString object in "that" is copied. + * @param that The StringCharacterIterator to be copied + * @stable ICU 2.0 + */ + StringCharacterIterator(const StringCharacterIterator& that); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~StringCharacterIterator(); + + /** + * Assignment operator. *this is altered to iterate over the same + * range of the same string as "that", and refers to the same + * character within that string as "that" does. + * @param that The object to be copied. + * @return the newly created object. + * @stable ICU 2.0 + */ + StringCharacterIterator& + operator=(const StringCharacterIterator& that); + + /** + * Returns true if the iterators iterate over the same range of the + * same string and are pointing at the same character. + * @param that The ForwardCharacterIterator to be compared for equality + * @return true if the iterators iterate over the same range of the + * same string and are pointing at the same character. + * @stable ICU 2.0 + */ + virtual bool operator==(const ForwardCharacterIterator& that) const override; + + /** + * Returns a new StringCharacterIterator referring to the same + * character in the same range of the same string as this one. The + * caller must delete the new iterator. + * @return the newly cloned object. + * @stable ICU 2.0 + */ + virtual StringCharacterIterator* clone() const override; + + /** + * Sets the iterator to iterate over the provided string. + * @param newText The string to be iterated over + * @stable ICU 2.0 + */ + void setText(const UnicodeString& newText); + + /** + * Copies the UnicodeString under iteration into the UnicodeString + * referred to by "result". Even if this iterator iterates across + * only a part of this string, the whole string is copied. + * @param result Receives a copy of the text under iteration. + * @stable ICU 2.0 + */ + virtual void getText(UnicodeString& result) override; + + /** + * Return a class ID for this object (not really public) + * @return a class ID for this object. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Return a class ID for this class (not really public) + * @return a class ID for this class + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +protected: + /** + * Default constructor, iteration over empty string. + * @stable ICU 2.0 + */ + StringCharacterIterator(); + + /** + * Copy of the iterated string object. + * @stable ICU 2.0 + */ + UnicodeString text; + +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/scientificnumberformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/scientificnumberformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..a1dd5436382c9cba789711bbf447b132dcc2a582 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/scientificnumberformatter.h @@ -0,0 +1,222 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2014-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +*/ +#ifndef SCINUMBERFORMATTER_H +#define SCINUMBERFORMATTER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + + +#include "unicode/unistr.h" + +/** + * \file + * \brief C++ API: Formats in scientific notation. + */ + +U_NAMESPACE_BEGIN + +class FieldPositionIterator; +class DecimalFormatSymbols; +class DecimalFormat; +class Formattable; + +/** + * A formatter that formats numbers in user-friendly scientific notation. + * + * Sample code: + *

+ * UErrorCode status = U_ZERO_ERROR;
+ * LocalPointer fmt(
+ *         ScientificNumberFormatter::createMarkupInstance(
+ *                 "en", "", "", status));
+ * if (U_FAILURE(status)) {
+ *     return;
+ * }
+ * UnicodeString appendTo;
+ * // appendTo = "1.23456x10-78"
+ * fmt->format(1.23456e-78, appendTo, status);
+ * 
+ * + * @stable ICU 55 + */ +class U_I18N_API ScientificNumberFormatter : public UObject { +public: + + /** + * Creates a ScientificNumberFormatter instance that uses + * superscript characters for exponents. + * @param fmtToAdopt The DecimalFormat which must be configured for + * scientific notation. + * @param status error returned here. + * @return The new ScientificNumberFormatter instance. + * + * @stable ICU 55 + */ + static ScientificNumberFormatter *createSuperscriptInstance( + DecimalFormat *fmtToAdopt, UErrorCode &status); + + /** + * Creates a ScientificNumberFormatter instance that uses + * superscript characters for exponents for this locale. + * @param locale The locale + * @param status error returned here. + * @return The ScientificNumberFormatter instance. + * + * @stable ICU 55 + */ + static ScientificNumberFormatter *createSuperscriptInstance( + const Locale &locale, UErrorCode &status); + + + /** + * Creates a ScientificNumberFormatter instance that uses + * markup for exponents. + * @param fmtToAdopt The DecimalFormat which must be configured for + * scientific notation. + * @param beginMarkup the markup to start superscript. + * @param endMarkup the markup to end superscript. + * @param status error returned here. + * @return The new ScientificNumberFormatter instance. + * + * @stable ICU 55 + */ + static ScientificNumberFormatter *createMarkupInstance( + DecimalFormat *fmtToAdopt, + const UnicodeString &beginMarkup, + const UnicodeString &endMarkup, + UErrorCode &status); + + /** + * Creates a ScientificNumberFormatter instance that uses + * markup for exponents for this locale. + * @param locale The locale + * @param beginMarkup the markup to start superscript. + * @param endMarkup the markup to end superscript. + * @param status error returned here. + * @return The ScientificNumberFormatter instance. + * + * @stable ICU 55 + */ + static ScientificNumberFormatter *createMarkupInstance( + const Locale &locale, + const UnicodeString &beginMarkup, + const UnicodeString &endMarkup, + UErrorCode &status); + + + /** + * Returns a copy of this object. Caller must free returned copy. + * @stable ICU 55 + */ + ScientificNumberFormatter *clone() const { + return new ScientificNumberFormatter(*this); + } + + /** + * Destructor. + * @stable ICU 55 + */ + virtual ~ScientificNumberFormatter(); + + /** + * Formats a number into user friendly scientific notation. + * + * @param number the number to format. + * @param appendTo formatted string appended here. + * @param status any error returned here. + * @return appendTo + * + * @stable ICU 55 + */ + UnicodeString &format( + const Formattable &number, + UnicodeString &appendTo, + UErrorCode &status) const; + private: + class U_I18N_API Style : public UObject { + public: + virtual Style *clone() const = 0; + protected: + virtual UnicodeString &format( + const UnicodeString &original, + FieldPositionIterator &fpi, + const UnicodeString &preExponent, + UnicodeString &appendTo, + UErrorCode &status) const = 0; + private: + friend class ScientificNumberFormatter; + }; + + class U_I18N_API SuperscriptStyle : public Style { + public: + virtual SuperscriptStyle *clone() const override; + protected: + virtual UnicodeString &format( + const UnicodeString &original, + FieldPositionIterator &fpi, + const UnicodeString &preExponent, + UnicodeString &appendTo, + UErrorCode &status) const override; + }; + + class U_I18N_API MarkupStyle : public Style { + public: + MarkupStyle( + const UnicodeString &beginMarkup, + const UnicodeString &endMarkup) + : Style(), + fBeginMarkup(beginMarkup), + fEndMarkup(endMarkup) { } + virtual MarkupStyle *clone() const override; + protected: + virtual UnicodeString &format( + const UnicodeString &original, + FieldPositionIterator &fpi, + const UnicodeString &preExponent, + UnicodeString &appendTo, + UErrorCode &status) const override; + private: + UnicodeString fBeginMarkup; + UnicodeString fEndMarkup; + }; + + ScientificNumberFormatter( + DecimalFormat *fmtToAdopt, + Style *styleToAdopt, + UErrorCode &status); + + ScientificNumberFormatter(const ScientificNumberFormatter &other); + ScientificNumberFormatter &operator=(const ScientificNumberFormatter &) = delete; + + static void getPreExponent( + const DecimalFormatSymbols &dfs, UnicodeString &preExponent); + + static ScientificNumberFormatter *createInstance( + DecimalFormat *fmtToAdopt, + Style *styleToAdopt, + UErrorCode &status); + + UnicodeString fPreExponent; + DecimalFormat *fDecimalFormat; + Style *fStyle; + +}; + +U_NAMESPACE_END + + +#endif /* !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/search.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/search.h new file mode 100644 index 0000000000000000000000000000000000000000..a8004efc43116e95751ee6bdd7a5a0aba3b006a7 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/search.h @@ -0,0 +1,580 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 2001-2011 IBM and others. All rights reserved. +********************************************************************** +* Date Name Description +* 03/22/2000 helena Creation. +********************************************************************** +*/ + +#ifndef SEARCH_H +#define SEARCH_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: SearchIterator object. + */ + +#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/chariter.h" +#include "unicode/brkiter.h" +#include "unicode/usearch.h" + +/** +* @stable ICU 2.0 +*/ +struct USearch; +/** +* @stable ICU 2.0 +*/ +typedef struct USearch USearch; + +U_NAMESPACE_BEGIN + +/** + * + * SearchIterator is an abstract base class that provides + * methods to search for a pattern within a text string. Instances of + * SearchIterator maintain a current position and scans over the + * target text, returning the indices the pattern is matched and the length + * of each match. + *

+ * SearchIterator defines a protocol for text searching. + * Subclasses provide concrete implementations of various search algorithms. + * For example, StringSearch implements language-sensitive pattern + * matching based on the comparison rules defined in a + * RuleBasedCollator object. + *

+ * Other options for searching includes using a BreakIterator to restrict + * the points at which matches are detected. + *

+ * SearchIterator provides an API that is similar to that of + * other text iteration classes such as BreakIterator. Using + * this class, it is easy to scan through text looking for all occurrences of + * a given pattern. The following example uses a StringSearch + * object to find all instances of "fox" in the target string. Any other + * subclass of SearchIterator can be used in an identical + * manner. + *


+ * UnicodeString target("The quick brown fox jumped over the lazy fox");
+ * UnicodeString pattern("fox");
+ *
+ * SearchIterator *iter  = new StringSearch(pattern, target);
+ * UErrorCode      error = U_ZERO_ERROR;
+ * for (int pos = iter->first(error); pos != USEARCH_DONE; 
+ *                               pos = iter->next(error)) {
+ *     printf("Found match at %d pos, length is %d\n", pos, iter.getMatchedLength());
+ * }
+ * 
+ * + * @see StringSearch + * @see RuleBasedCollator + */ +class U_I18N_API SearchIterator : public UObject { + +public: + + // public constructors and destructors ------------------------------- + + /** + * Copy constructor that creates a SearchIterator instance with the same + * behavior, and iterating over the same text. + * @param other the SearchIterator instance to be copied. + * @stable ICU 2.0 + */ + SearchIterator(const SearchIterator &other); + + /** + * Destructor. Cleans up the search iterator data struct. + * @stable ICU 2.0 + */ + virtual ~SearchIterator(); + + // public get and set methods ---------------------------------------- + + /** + * Sets the index to point to the given position, and clears any state + * that's affected. + *

+ * This method takes the argument index and sets the position in the text + * string accordingly without checking if the index is pointing to a + * valid starting point to begin searching. + * @param position within the text to be set. If position is less + * than or greater than the text range for searching, + * an U_INDEX_OUTOFBOUNDS_ERROR will be returned + * @param status for errors if it occurs + * @stable ICU 2.0 + */ + virtual void setOffset(int32_t position, UErrorCode &status) = 0; + + /** + * Return the current index in the text being searched. + * If the iteration has gone past the end of the text + * (or past the beginning for a backwards search), USEARCH_DONE + * is returned. + * @return current index in the text being searched. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(void) const = 0; + + /** + * Sets the text searching attributes located in the enum + * USearchAttribute with values from the enum USearchAttributeValue. + * USEARCH_DEFAULT can be used for all attributes for resetting. + * @param attribute text attribute (enum USearchAttribute) to be set + * @param value text attribute value + * @param status for errors if it occurs + * @stable ICU 2.0 + */ + void setAttribute(USearchAttribute attribute, + USearchAttributeValue value, + UErrorCode &status); + + /** + * Gets the text searching attributes + * @param attribute text attribute (enum USearchAttribute) to be retrieve + * @return text attribute value + * @stable ICU 2.0 + */ + USearchAttributeValue getAttribute(USearchAttribute attribute) const; + + /** + * Returns the index to the match in the text string that was searched. + * This call returns a valid result only after a successful call to + * first, next, previous, or last. + * Just after construction, or after a searching method returns + * USEARCH_DONE, this method will return USEARCH_DONE. + *

+ * Use getMatchedLength to get the matched string length. + * @return index of a substring within the text string that is being + * searched. + * @see #first + * @see #next + * @see #previous + * @see #last + * @stable ICU 2.0 + */ + int32_t getMatchedStart(void) const; + + /** + * Returns the length of text in the string which matches the search + * pattern. This call returns a valid result only after a successful call + * to first, next, previous, or last. + * Just after construction, or after a searching method returns + * USEARCH_DONE, this method will return 0. + * @return The length of the match in the target text, or 0 if there + * is no match currently. + * @see #first + * @see #next + * @see #previous + * @see #last + * @stable ICU 2.0 + */ + int32_t getMatchedLength(void) const; + + /** + * Returns the text that was matched by the most recent call to + * first, next, previous, or last. + * If the iterator is not pointing at a valid match (e.g. just after + * construction or after USEARCH_DONE has been returned, + * returns an empty string. + * @param result stores the matched string or an empty string if a match + * is not found. + * @see #first + * @see #next + * @see #previous + * @see #last + * @stable ICU 2.0 + */ + void getMatchedText(UnicodeString &result) const; + + /** + * Set the BreakIterator that will be used to restrict the points + * at which matches are detected. The user is responsible for deleting + * the breakiterator. + * @param breakiter A BreakIterator that will be used to restrict the + * points at which matches are detected. If a match is + * found, but the match's start or end index is not a + * boundary as determined by the BreakIterator, + * the match will be rejected and another will be searched + * for. If this parameter is nullptr, no break + * detection is attempted. + * @param status for errors if it occurs + * @see BreakIterator + * @stable ICU 2.0 + */ + void setBreakIterator(BreakIterator *breakiter, UErrorCode &status); + + /** + * Returns the BreakIterator that is used to restrict the points at + * which matches are detected. This will be the same object that was + * passed to the constructor or to setBreakIterator. + * Note that nullptr is a legal value; it means that break + * detection should not be attempted. + * @return BreakIterator used to restrict matchings. + * @see #setBreakIterator + * @stable ICU 2.0 + */ + const BreakIterator * getBreakIterator(void) const; + + /** + * Set the string text to be searched. Text iteration will hence begin at + * the start of the text string. This method is useful if you want to + * re-use an iterator to search for the same pattern within a different + * body of text. The user is responsible for deleting the text. + * @param text string to be searched. + * @param status for errors. If the text length is 0, + * an U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + virtual void setText(const UnicodeString &text, UErrorCode &status); + + /** + * Set the string text to be searched. Text iteration will hence begin at + * the start of the text string. This method is useful if you want to + * re-use an iterator to search for the same pattern within a different + * body of text. + *

+ * Note: No parsing of the text within the CharacterIterator + * will be done during searching for this version. The block of text + * in CharacterIterator will be used as it is. + * The user is responsible for deleting the text. + * @param text string iterator to be searched. + * @param status for errors if any. If the text length is 0 then an + * U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + virtual void setText(CharacterIterator &text, UErrorCode &status); + + /** + * Return the string text to be searched. + * @return text string to be searched. + * @stable ICU 2.0 + */ + const UnicodeString & getText(void) const; + + // operator overloading ---------------------------------------------- + + /** + * Equality operator. + * @param that SearchIterator instance to be compared. + * @return true if both BreakIterators are of the same class, have the + * same behavior, terates over the same text and have the same + * attributes. false otherwise. + * @stable ICU 2.0 + */ + virtual bool operator==(const SearchIterator &that) const; + + /** + * Not-equal operator. + * @param that SearchIterator instance to be compared. + * @return false if operator== returns true, and vice versa. + * @stable ICU 2.0 + */ + bool operator!=(const SearchIterator &that) const; + + // public methods ---------------------------------------------------- + + /** + * Returns a copy of SearchIterator with the same behavior, and + * iterating over the same text, as this one. Note that all data will be + * replicated, except for the text string to be searched. + * @return cloned object + * @stable ICU 2.0 + */ + virtual SearchIterator* safeClone(void) const = 0; + + /** + * Returns the first index at which the string text matches the search + * pattern. The iterator is adjusted so that its current index (as + * returned by getOffset) is the match position if one + * was found. + * If a match is not found, USEARCH_DONE will be returned and + * the iterator will be adjusted to the index USEARCH_DONE + * @param status for errors if it occurs + * @return The character index of the first match, or + * USEARCH_DONE if there are no matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t first(UErrorCode &status); + + /** + * Returns the first index equal or greater than position at which the + * string text matches the search pattern. The iterator is adjusted so + * that its current index (as returned by getOffset) is the + * match position if one was found. + * If a match is not found, USEARCH_DONE will be returned and the + * iterator will be adjusted to the index USEARCH_DONE. + * @param position where search if to start from. If position is less + * than or greater than the text range for searching, + * an U_INDEX_OUTOFBOUNDS_ERROR will be returned + * @param status for errors if it occurs + * @return The character index of the first match following + * position, or USEARCH_DONE if there are no + * matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t following(int32_t position, UErrorCode &status); + + /** + * Returns the last index in the target text at which it matches the + * search pattern. The iterator is adjusted so that its current index + * (as returned by getOffset) is the match position if one was + * found. + * If a match is not found, USEARCH_DONE will be returned and + * the iterator will be adjusted to the index USEARCH_DONE. + * @param status for errors if it occurs + * @return The index of the first match, or USEARCH_DONE if + * there are no matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t last(UErrorCode &status); + + /** + * Returns the first index less than position at which the string + * text matches the search pattern. The iterator is adjusted so that its + * current index (as returned by getOffset) is the match + * position if one was found. If a match is not found, + * USEARCH_DONE will be returned and the iterator will be + * adjusted to the index USEARCH_DONE + *

+ * When USEARCH_OVERLAP option is off, the last index of the + * result match is always less than position. + * When USERARCH_OVERLAP is on, the result match may span across + * position. + * + * @param position where search is to start from. If position is less + * than or greater than the text range for searching, + * an U_INDEX_OUTOFBOUNDS_ERROR will be returned + * @param status for errors if it occurs + * @return The character index of the first match preceding + * position, or USEARCH_DONE if there are + * no matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t preceding(int32_t position, UErrorCode &status); + + /** + * Returns the index of the next point at which the text matches the + * search pattern, starting from the current position + * The iterator is adjusted so that its current index (as returned by + * getOffset) is the match position if one was found. + * If a match is not found, USEARCH_DONE will be returned and + * the iterator will be adjusted to a position after the end of the text + * string. + * @param status for errors if it occurs + * @return The index of the next match after the current position, + * or USEARCH_DONE if there are no more matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t next(UErrorCode &status); + + /** + * Returns the index of the previous point at which the string text + * matches the search pattern, starting at the current position. + * The iterator is adjusted so that its current index (as returned by + * getOffset) is the match position if one was found. + * If a match is not found, USEARCH_DONE will be returned and + * the iterator will be adjusted to the index USEARCH_DONE + * @param status for errors if it occurs + * @return The index of the previous match before the current position, + * or USEARCH_DONE if there are no more matches. + * @see #getOffset + * @stable ICU 2.0 + */ + int32_t previous(UErrorCode &status); + + /** + * Resets the iteration. + * Search will begin at the start of the text string if a forward + * iteration is initiated before a backwards iteration. Otherwise if a + * backwards iteration is initiated before a forwards iteration, the + * search will begin at the end of the text string. + * @stable ICU 2.0 + */ + virtual void reset(); + +protected: + // protected data members --------------------------------------------- + + /** + * C search data struct + * @stable ICU 2.0 + */ + USearch *m_search_; + + /** + * Break iterator. + * Currently the C++ breakiterator does not have getRules etc to reproduce + * another in C. Hence we keep the original around and do the verification + * at the end of the match. The user is responsible for deleting this + * break iterator. + * @stable ICU 2.0 + */ + BreakIterator *m_breakiterator_; + + /** + * Unicode string version of the search text + * @stable ICU 2.0 + */ + UnicodeString m_text_; + + // protected constructors and destructors ----------------------------- + + /** + * Default constructor. + * Initializes data to the default values. + * @stable ICU 2.0 + */ + SearchIterator(); + + /** + * Constructor for use by subclasses. + * @param text The target text to be searched. + * @param breakiter A {@link BreakIterator} that is used to restrict the + * points at which matches are detected. If + * handleNext or handlePrev finds a + * match, but the match's start or end index is not a + * boundary as determined by the BreakIterator, + * the match is rejected and handleNext or + * handlePrev is called again. If this parameter + * is nullptr, no break detection is attempted. + * @see #handleNext + * @see #handlePrev + * @stable ICU 2.0 + */ + SearchIterator(const UnicodeString &text, + BreakIterator *breakiter = nullptr); + + /** + * Constructor for use by subclasses. + *

+ * Note: No parsing of the text within the CharacterIterator + * will be done during searching for this version. The block of text + * in CharacterIterator will be used as it is. + * @param text The target text to be searched. + * @param breakiter A {@link BreakIterator} that is used to restrict the + * points at which matches are detected. If + * handleNext or handlePrev finds a + * match, but the match's start or end index is not a + * boundary as determined by the BreakIterator, + * the match is rejected and handleNext or + * handlePrev is called again. If this parameter + * is nullptr, no break detection is attempted. + * @see #handleNext + * @see #handlePrev + * @stable ICU 2.0 + */ + SearchIterator(CharacterIterator &text, BreakIterator *breakiter = nullptr); + + // protected methods -------------------------------------------------- + + /** + * Assignment operator. Sets this iterator to have the same behavior, + * and iterate over the same text, as the one passed in. + * @param that instance to be copied. + * @stable ICU 2.0 + */ + SearchIterator & operator=(const SearchIterator &that); + + /** + * Abstract method which subclasses override to provide the mechanism + * for finding the next match in the target text. This allows different + * subclasses to provide different search algorithms. + *

+ * If a match is found, the implementation should return the index at + * which the match starts and should call + * setMatchLength with the number of characters + * in the target text that make up the match. If no match is found, the + * method should return USEARCH_DONE. + *

+ * @param position The index in the target text at which the search + * should start. + * @param status for error codes if it occurs. + * @return index at which the match starts, else if match is not found + * USEARCH_DONE is returned + * @see #setMatchLength + * @stable ICU 2.0 + */ + virtual int32_t handleNext(int32_t position, UErrorCode &status) + = 0; + + /** + * Abstract method which subclasses override to provide the mechanism for + * finding the previous match in the target text. This allows different + * subclasses to provide different search algorithms. + *

+ * If a match is found, the implementation should return the index at + * which the match starts and should call + * setMatchLength with the number of characters + * in the target text that make up the match. If no match is found, the + * method should return USEARCH_DONE. + *

+ * @param position The index in the target text at which the search + * should start. + * @param status for error codes if it occurs. + * @return index at which the match starts, else if match is not found + * USEARCH_DONE is returned + * @see #setMatchLength + * @stable ICU 2.0 + */ + virtual int32_t handlePrev(int32_t position, UErrorCode &status) + = 0; + + /** + * Sets the length of the currently matched string in the text string to + * be searched. + * Subclasses' handleNext and handlePrev + * methods should call this when they find a match in the target text. + * @param length length of the matched text. + * @see #handleNext + * @see #handlePrev + * @stable ICU 2.0 + */ + virtual void setMatchLength(int32_t length); + + /** + * Sets the offset of the currently matched string in the text string to + * be searched. + * Subclasses' handleNext and handlePrev + * methods should call this when they find a match in the target text. + * @param position start offset of the matched text. + * @see #handleNext + * @see #handlePrev + * @stable ICU 2.0 + */ + virtual void setMatchStart(int32_t position); + + /** + * sets match not found + * @stable ICU 2.0 + */ + void setMatchNotFound(); +}; + +inline bool SearchIterator::operator!=(const SearchIterator &that) const +{ + return !operator==(that); +} +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/selfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/selfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..180238031277f0690c88137ea63cc51a05870406 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/selfmt.h @@ -0,0 +1,374 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/******************************************************************** + * COPYRIGHT: + * Copyright (c) 1997-2011, International Business Machines Corporation and + * others. All Rights Reserved. + * Copyright (C) 2010 , Yahoo! Inc. + ******************************************************************** + * + * File SELFMT.H + * + * Modification History: + * + * Date Name Description + * 11/11/09 kirtig Finished first cut of implementation. + ********************************************************************/ + +#ifndef SELFMT +#define SELFMT + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/messagepattern.h" +#include "unicode/numfmt.h" + +/** + * \file + * \brief C++ API: SelectFormat object + */ + +#if !UCONFIG_NO_FORMATTING + +U_NAMESPACE_BEGIN + +class MessageFormat; + +/** + *

SelectFormat supports the creation of internationalized + * messages by selecting phrases based on keywords. The pattern specifies + * how to map keywords to phrases and provides a default phrase. The + * object provided to the format method is a string that's matched + * against the keywords. If there is a match, the corresponding phrase + * is selected; otherwise, the default phrase is used.

+ * + *

Using SelectFormat for Gender Agreement

+ * + *

Note: Typically, select formatting is done via MessageFormat + * with a select argument type, + * rather than using a stand-alone SelectFormat.

+ * + *

The main use case for the select format is gender based inflection. + * When names or nouns are inserted into sentences, their gender can affect pronouns, + * verb forms, articles, and adjectives. Special care needs to be + * taken for the case where the gender cannot be determined. + * The impact varies between languages:

+ * \htmlonly + *
    + *
  • English has three genders, and unknown gender is handled as a special + * case. Names use the gender of the named person (if known), nouns referring + * to people use natural gender, and inanimate objects are usually neutral. + * The gender only affects pronouns: "he", "she", "it", "they". + * + *
  • German differs from English in that the gender of nouns is rather + * arbitrary, even for nouns referring to people ("Mädchen", girl, is neutral). + * The gender affects pronouns ("er", "sie", "es"), articles ("der", "die", + * "das"), and adjective forms ("guter Mann", "gute Frau", "gutes Mädchen"). + * + *
  • French has only two genders; as in German the gender of nouns + * is rather arbitrary - for sun and moon, the genders + * are the opposite of those in German. The gender affects + * pronouns ("il", "elle"), articles ("le", "la"), + * adjective forms ("bon", "bonne"), and sometimes + * verb forms ("allé", "allée"). + * + *
  • Polish distinguishes five genders (or noun classes), + * human masculine, animate non-human masculine, inanimate masculine, + * feminine, and neuter. + *
+ * \endhtmlonly + *

Some other languages have noun classes that are not related to gender, + * but similar in grammatical use. + * Some African languages have around 20 noun classes.

+ * + *

Note:For the gender of a person in a given sentence, + * we usually need to distinguish only between female, male and other/unknown.

+ * + *

To enable localizers to create sentence patterns that take their + * language's gender dependencies into consideration, software has to provide + * information about the gender associated with a noun or name to + * MessageFormat. + * Two main cases can be distinguished:

+ * + *
    + *
  • For people, natural gender information should be maintained for each person. + * Keywords like "male", "female", "mixed" (for groups of people) + * and "unknown" could be used. + * + *
  • For nouns, grammatical gender information should be maintained for + * each noun and per language, e.g., in resource bundles. + * The keywords "masculine", "feminine", and "neuter" are commonly used, + * but some languages may require other keywords. + *
+ * + *

The resulting keyword is provided to MessageFormat as a + * parameter separate from the name or noun it's associated with. For example, + * to generate a message such as "Jean went to Paris", three separate arguments + * would be provided: The name of the person as argument 0, the gender of + * the person as argument 1, and the name of the city as argument 2. + * The sentence pattern for English, where the gender of the person has + * no impact on this simple sentence, would not refer to argument 1 at all:

+ * + *
{0} went to {2}.
+ * + *

Note: The entire sentence should be included (and partially repeated) + * inside each phrase. Otherwise translators would have to be trained on how to + * move bits of the sentence in and out of the select argument of a message. + * (The examples below do not follow this recommendation!)

+ * + *

The sentence pattern for French, where the gender of the person affects + * the form of the participle, uses a select format based on argument 1:

+ * + * \htmlonly
{0} est {1, select, female {allée} other {allé}} à {2}.
\endhtmlonly + * + *

Patterns can be nested, so that it's possible to handle interactions of + * number and gender where necessary. For example, if the above sentence should + * allow for the names of several people to be inserted, the following sentence + * pattern can be used (with argument 0 the list of people's names, + * argument 1 the number of people, argument 2 their combined gender, and + * argument 3 the city name):

+ * + * \htmlonly + *
{0} {1, plural,
+  *                 one {est {2, select, female {allée} other  {allé}}}
+  *                 other {sont {2, select, female {allées} other {allés}}}
+  *          }à {3}.
+ * \endhtmlonly + * + *

Patterns and Their Interpretation

+ * + *

The SelectFormat pattern string defines the phrase output + * for each user-defined keyword. + * The pattern is a sequence of (keyword, message) pairs. + * A keyword is a "pattern identifier": [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+

+ * + *

Each message is a MessageFormat pattern string enclosed in {curly braces}.

+ * + *

You always have to define a phrase for the default keyword + * other; this phrase is returned when the keyword + * provided to + * the format method matches no other keyword. + * If a pattern does not provide a phrase for other, the method + * it's provided to returns the error U_DEFAULT_KEYWORD_MISSING. + *
+ * Pattern_White_Space between keywords and messages is ignored. + * Pattern_White_Space within a message is preserved and output.

+ * + *

Example:
+  * \htmlonly
+  *
+  * UErrorCode status = U_ZERO_ERROR;
+  * MessageFormat *msgFmt = new MessageFormat(UnicodeString("{0} est  {1, select, female {allée} other {allé}} à Paris."), Locale("fr"),  status);
+  * if (U_FAILURE(status)) {
+  *       return;
+  * }
+  * FieldPosition ignore(FieldPosition::DONT_CARE);
+  * UnicodeString result;
+  *
+  * char* str1= "Kirti,female";
+  * Formattable args1[] = {"Kirti","female"};
+  * msgFmt->format(args1, 2, result, ignore, status);
+  * cout << "Input is " << str1 << " and result is: " << result << endl;
+  * delete msgFmt;
+  *
+  * \endhtmlonly
+  * 
+ *

+ * + * Produces the output:
+ * \htmlonly + * Kirti est allée à Paris. + * \endhtmlonly + * + * @stable ICU 4.4 + */ + +class U_I18N_API SelectFormat : public Format { +public: + + /** + * Creates a new SelectFormat for a given pattern string. + * @param pattern the pattern for this SelectFormat. + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.4 + */ + SelectFormat(const UnicodeString& pattern, UErrorCode& status); + + /** + * copy constructor. + * @stable ICU 4.4 + */ + SelectFormat(const SelectFormat& other); + + /** + * Destructor. + * @stable ICU 4.4 + */ + virtual ~SelectFormat(); + + /** + * Sets the pattern used by this select format. + * for the keyword rules. + * Patterns and their interpretation are specified in the class description. + * + * @param pattern the pattern for this select format + * errors are returned to status if the pattern is invalid. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @stable ICU 4.4 + */ + void applyPattern(const UnicodeString& pattern, UErrorCode& status); + + + using Format::format; + + /** + * Selects the phrase for the given keyword + * + * @param keyword The keyword that is used to select an alternative. + * @param appendTo output parameter to receive result. + * result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status output param set to success/failure code on exit, which + * must not indicate a failure before the function call. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(const UnicodeString& keyword, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const; + + /** + * Assignment operator + * + * @param other the SelectFormat object to copy from. + * @stable ICU 4.4 + */ + SelectFormat& operator=(const SelectFormat& other); + + /** + * Return true if another object is semantically equal to this one. + * + * @param other the SelectFormat object to be compared with. + * @return true if other is semantically equal to this. + * @stable ICU 4.4 + */ + virtual bool operator==(const Format& other) const override; + + /** + * Return true if another object is semantically unequal to this one. + * + * @param other the SelectFormat object to be compared with. + * @return true if other is semantically unequal to this. + * @stable ICU 4.4 + */ + virtual bool operator!=(const Format& other) const; + + /** + * Clones this Format object polymorphically. The caller owns the + * result and should delete it when done. + * @stable ICU 4.4 + */ + virtual SelectFormat* clone() const override; + + /** + * Format an object to produce a string. + * This method handles keyword strings. + * If the Formattable object is not a UnicodeString, + * then it returns a failing UErrorCode. + * + * @param obj A keyword string that is used to select an alternative. + * @param appendTo output parameter to receive result. + * Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. + * On output: the offsets of the alignment field. + * @param status output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + UnicodeString& format(const Formattable& obj, + UnicodeString& appendTo, + FieldPosition& pos, + UErrorCode& status) const override; + + /** + * Returns the pattern from applyPattern() or constructor. + * + * @param appendTo output parameter to receive result. + * Result is appended to existing contents. + * @return the UnicodeString with inserted pattern. + * @stable ICU 4.4 + */ + UnicodeString& toPattern(UnicodeString& appendTo); + + /** + * This method is not yet supported by SelectFormat. + *

+ * Before calling, set parse_pos.index to the offset you want to start + * parsing at in the source. After calling, parse_pos.index is the end of + * the text you parsed. If error occurs, index is unchanged. + *

+ * When parsing, leading whitespace is discarded (with a successful parse), + * while trailing whitespace is left as is. + *

+ * See Format::parseObject() for more. + * + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. + * If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return + * this param is set to the position after the + * last character successfully parsed. If the + * source is not parsed successfully, this param + * will remain unchanged. + * @stable ICU 4.4 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& parse_pos) const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * @stable ICU 4.4 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * @stable ICU 4.4 + */ + virtual UClassID getDynamicClassID() const override; + +private: + friend class MessageFormat; + + SelectFormat() = delete; // default constructor not implemented. + + /** + * Finds the SelectFormat sub-message for the given keyword, or the "other" sub-message. + * @param pattern A MessagePattern. + * @param partIndex the index of the first SelectFormat argument style part. + * @param keyword a keyword to be matched to one of the SelectFormat argument's keywords. + * @param ec Error code. + * @return the sub-message start part index. + */ + static int32_t findSubMessage(const MessagePattern& pattern, int32_t partIndex, + const UnicodeString& keyword, UErrorCode& ec); + + MessagePattern msgPattern; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _SELFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpleformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpleformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..7f58106fadb3b764597b26c7c765222b22e0d58b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpleformatter.h @@ -0,0 +1,341 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 2014-2016, International Business Machines +* Corporation and others. All Rights Reserved. +****************************************************************************** +* simpleformatter.h +*/ + +#ifndef __SIMPLEFORMATTER_H__ +#define __SIMPLEFORMATTER_H__ + +/** + * \file + * \brief C++ API: Simple formatter, minimal subset of MessageFormat. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/unistr.h" + +U_NAMESPACE_BEGIN + +// Forward declaration: +namespace number { +namespace impl { +class SimpleModifier; +} +} + +/** + * Formats simple patterns like "{1} was born in {0}". + * Minimal subset of MessageFormat; fast, simple, minimal dependencies. + * Supports only numbered arguments with no type nor style parameters, + * and formats only string values. + * Quoting via ASCII apostrophe compatible with ICU MessageFormat default behavior. + * + * Factory methods set error codes for syntax errors + * and for too few or too many arguments/placeholders. + * + * SimpleFormatter objects are thread-safe except for assignment and applying new patterns. + * + * Example: + *

+ * UErrorCode errorCode = U_ZERO_ERROR;
+ * SimpleFormatter fmt("{1} '{born}' in {0}", errorCode);
+ * UnicodeString result;
+ *
+ * // Output: "paul {born} in england"
+ * fmt.format("england", "paul", result, errorCode);
+ * 
+ * + * This class is not intended for public subclassing. + * + * @see MessageFormat + * @see UMessagePatternApostropheMode + * @stable ICU 57 + */ +class U_COMMON_API SimpleFormatter final : public UMemory { +public: + /** + * Default constructor. + * @stable ICU 57 + */ + SimpleFormatter() : compiledPattern((char16_t)0) {} + + /** + * Constructs a formatter from the pattern string. + * + * @param pattern The pattern string. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax. + * @stable ICU 57 + */ + SimpleFormatter(const UnicodeString& pattern, UErrorCode &errorCode) { + applyPattern(pattern, errorCode); + } + + /** + * Constructs a formatter from the pattern string. + * The number of arguments checked against the given limits is the + * highest argument number plus one, not the number of occurrences of arguments. + * + * @param pattern The pattern string. + * @param min The pattern must have at least this many arguments. + * @param max The pattern must have at most this many arguments. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax and + * too few or too many arguments. + * @stable ICU 57 + */ + SimpleFormatter(const UnicodeString& pattern, int32_t min, int32_t max, + UErrorCode &errorCode) { + applyPatternMinMaxArguments(pattern, min, max, errorCode); + } + + /** + * Copy constructor. + * @stable ICU 57 + */ + SimpleFormatter(const SimpleFormatter& other) + : compiledPattern(other.compiledPattern) {} + + /** + * Assignment operator. + * @stable ICU 57 + */ + SimpleFormatter &operator=(const SimpleFormatter& other); + + /** + * Destructor. + * @stable ICU 57 + */ + ~SimpleFormatter(); + + /** + * Changes this object according to the new pattern. + * + * @param pattern The pattern string. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax. + * @return true if U_SUCCESS(errorCode). + * @stable ICU 57 + */ + UBool applyPattern(const UnicodeString &pattern, UErrorCode &errorCode) { + return applyPatternMinMaxArguments(pattern, 0, INT32_MAX, errorCode); + } + + /** + * Changes this object according to the new pattern. + * The number of arguments checked against the given limits is the + * highest argument number plus one, not the number of occurrences of arguments. + * + * @param pattern The pattern string. + * @param min The pattern must have at least this many arguments. + * @param max The pattern must have at most this many arguments. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax and + * too few or too many arguments. + * @return true if U_SUCCESS(errorCode). + * @stable ICU 57 + */ + UBool applyPatternMinMaxArguments(const UnicodeString &pattern, + int32_t min, int32_t max, UErrorCode &errorCode); + + /** + * @return The max argument number + 1. + * @stable ICU 57 + */ + int32_t getArgumentLimit() const { + return getArgumentLimit(compiledPattern.getBuffer(), compiledPattern.length()); + } + + /** + * Formats the given value, appending to the appendTo builder. + * The argument value must not be the same object as appendTo. + * getArgumentLimit() must be at most 1. + * + * @param value0 Value for argument {0}. + * @param appendTo Gets the formatted pattern and value appended. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString &format( + const UnicodeString &value0, + UnicodeString &appendTo, UErrorCode &errorCode) const; + + /** + * Formats the given values, appending to the appendTo builder. + * An argument value must not be the same object as appendTo. + * getArgumentLimit() must be at most 2. + * + * @param value0 Value for argument {0}. + * @param value1 Value for argument {1}. + * @param appendTo Gets the formatted pattern and values appended. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString &format( + const UnicodeString &value0, + const UnicodeString &value1, + UnicodeString &appendTo, UErrorCode &errorCode) const; + + /** + * Formats the given values, appending to the appendTo builder. + * An argument value must not be the same object as appendTo. + * getArgumentLimit() must be at most 3. + * + * @param value0 Value for argument {0}. + * @param value1 Value for argument {1}. + * @param value2 Value for argument {2}. + * @param appendTo Gets the formatted pattern and values appended. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString &format( + const UnicodeString &value0, + const UnicodeString &value1, + const UnicodeString &value2, + UnicodeString &appendTo, UErrorCode &errorCode) const; + + /** + * Formats the given values, appending to the appendTo string. + * + * @param values The argument values. + * An argument value must not be the same object as appendTo. + * Can be nullptr if valuesLength==getArgumentLimit()==0. + * @param valuesLength The length of the values array. + * Must be at least getArgumentLimit(). + * @param appendTo Gets the formatted pattern and values appended. + * @param offsets offsets[i] receives the offset of where + * values[i] replaced pattern argument {i}. + * Can be shorter or longer than values. Can be nullptr if offsetsLength==0. + * If there is no {i} in the pattern, then offsets[i] is set to -1. + * @param offsetsLength The length of the offsets array. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return appendTo + * @stable ICU 57 + */ + UnicodeString &formatAndAppend( + const UnicodeString *const *values, int32_t valuesLength, + UnicodeString &appendTo, + int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const; + + /** + * Formats the given values, replacing the contents of the result string. + * May optimize by actually appending to the result if it is the same object + * as the value corresponding to the initial argument in the pattern. + * + * @param values The argument values. + * An argument value may be the same object as result. + * Can be nullptr if valuesLength==getArgumentLimit()==0. + * @param valuesLength The length of the values array. + * Must be at least getArgumentLimit(). + * @param result Gets its contents replaced by the formatted pattern and values. + * @param offsets offsets[i] receives the offset of where + * values[i] replaced pattern argument {i}. + * Can be shorter or longer than values. Can be nullptr if offsetsLength==0. + * If there is no {i} in the pattern, then offsets[i] is set to -1. + * @param offsetsLength The length of the offsets array. + * @param errorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return result + * @stable ICU 57 + */ + UnicodeString &formatAndReplace( + const UnicodeString *const *values, int32_t valuesLength, + UnicodeString &result, + int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const; + + /** + * Returns the pattern text with none of the arguments. + * Like formatting with all-empty string values. + * @stable ICU 57 + */ + UnicodeString getTextWithNoArguments() const { + return getTextWithNoArguments( + compiledPattern.getBuffer(), + compiledPattern.length(), + nullptr, + 0); + } + +#ifndef U_HIDE_INTERNAL_API + /** + * Returns the pattern text with none of the arguments. + * Like formatting with all-empty string values. + * + * TODO(ICU-20406): Replace this with an Iterator interface. + * + * @param offsets offsets[i] receives the offset of where {i} was located + * before it was replaced by an empty string. + * For example, "a{0}b{1}" produces offset 1 for i=0 and 2 for i=1. + * Can be nullptr if offsetsLength==0. + * If there is no {i} in the pattern, then offsets[i] is set to -1. + * @param offsetsLength The length of the offsets array. + * + * @internal + */ + UnicodeString getTextWithNoArguments(int32_t *offsets, int32_t offsetsLength) const { + return getTextWithNoArguments( + compiledPattern.getBuffer(), + compiledPattern.length(), + offsets, + offsetsLength); + } +#endif // U_HIDE_INTERNAL_API + +private: + /** + * Binary representation of the compiled pattern. + * Index 0: One more than the highest argument number. + * Followed by zero or more arguments or literal-text segments. + * + * An argument is stored as its number, less than ARG_NUM_LIMIT. + * A literal-text segment is stored as its length (at least 1) offset by ARG_NUM_LIMIT, + * followed by that many chars. + */ + UnicodeString compiledPattern; + + static inline int32_t getArgumentLimit(const char16_t *compiledPattern, + int32_t compiledPatternLength) { + return compiledPatternLength == 0 ? 0 : compiledPattern[0]; + } + + static UnicodeString getTextWithNoArguments( + const char16_t *compiledPattern, + int32_t compiledPatternLength, + int32_t *offsets, + int32_t offsetsLength); + + static UnicodeString &format( + const char16_t *compiledPattern, int32_t compiledPatternLength, + const UnicodeString *const *values, + UnicodeString &result, const UnicodeString *resultCopy, UBool forbidResultAsValue, + int32_t *offsets, int32_t offsetsLength, + UErrorCode &errorCode); + + // Give access to internals to SimpleModifier for number formatting + friend class number::impl::SimpleModifier; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __SIMPLEFORMATTER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simplenumberformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simplenumberformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..32b79a94da403a36f4c2141f5683a08b4f9d1aac --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simplenumberformatter.h @@ -0,0 +1,329 @@ +// © 2022 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __SIMPLENUMBERFORMATTERH__ +#define __SIMPLENUMBERFORMATTERH__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/dcfmtsym.h" +#include "unicode/usimplenumberformatter.h" +#include "unicode/formattednumber.h" + +/** + * \file + * \brief C++ API: Simple number formatting focused on low memory and code size. + * + * These functions render locale-aware number strings but without the bells and whistles found in + * other number formatting APIs such as those in numberformatter.h, like units and currencies. + * + *
+ * SimpleNumberFormatter snf = SimpleNumberFormatter::forLocale("de-CH", status);
+ * FormattedNumber result = snf.formatInt64(-1000007, status);
+ * assertEquals("", u"-1’000’007", result.toString(status));
+ * 
+ */ + +U_NAMESPACE_BEGIN + + +namespace number { // icu::number + + +namespace impl { +class UFormattedNumberData; +struct SimpleMicroProps; +class AdoptingSignumModifierStore; +} // icu::number::impl + + +#ifndef U_HIDE_DRAFT_API + + +/** + * An input type for SimpleNumberFormatter. + * + * This class is mutable and not intended for public subclassing. This class is movable but not copyable. + * + * @draft ICU 73 + */ +class U_I18N_API SimpleNumber : public UMemory { + public: + /** + * Creates a SimpleNumber for an integer. + * + * @draft ICU 73 + */ + static SimpleNumber forInt64(int64_t value, UErrorCode& status); + + /** + * Changes the value of the SimpleNumber by a power of 10. + * + * This function immediately mutates the inner value. + * + * @draft ICU 73 + */ + void multiplyByPowerOfTen(int32_t power, UErrorCode& status); + + /** + * Rounds the value currently stored in the SimpleNumber to the given power of 10. + * + * This function immediately mutates the inner value. + * + * @draft ICU 73 + */ + void roundTo(int32_t power, UNumberFormatRoundingMode roundingMode, UErrorCode& status); + + /** + * Truncates the most significant digits to the given maximum number of integer digits. + * + * This function immediately mutates the inner value. + * + * @draft ICU 73 + */ + void truncateStart(uint32_t maximumIntegerDigits, UErrorCode& status); + + /** + * Pads the beginning of the number with zeros up to the given minimum number of integer digits. + * + * This setting is applied upon formatting the number. + * + * @draft ICU 73 + */ + void setMinimumIntegerDigits(uint32_t minimumIntegerDigits, UErrorCode& status); + + /** + * Pads the end of the number with zeros up to the given minimum number of fraction digits. + * + * This setting is applied upon formatting the number. + * + * @draft ICU 73 + */ + void setMinimumFractionDigits(uint32_t minimumFractionDigits, UErrorCode& status); + + /** + * Sets the sign of the number: an explicit plus sign, explicit minus sign, or no sign. + * + * This setting is applied upon formatting the number. + * + * NOTE: This does not support accounting sign notation. + * + * @draft ICU 73 + */ + void setSign(USimpleNumberSign sign, UErrorCode& status); + + /** + * Creates a new, empty SimpleNumber that does not contain a value. + * + * NOTE: This number will fail to format; use forInt64() to create a SimpleNumber with a value. + * + * @draft ICU 73 + */ + SimpleNumber() = default; + + /** + * Destruct this SimpleNumber, cleaning up any memory it might own. + * + * @draft ICU 73 + */ + ~SimpleNumber() { + cleanup(); + } + + /** + * SimpleNumber move constructor. + * + * @draft ICU 73 + */ + SimpleNumber(SimpleNumber&& other) noexcept { + fData = other.fData; + fSign = other.fSign; + other.fData = nullptr; + } + + /** + * SimpleNumber move assignment. + * + * @draft ICU 73 + */ + SimpleNumber& operator=(SimpleNumber&& other) noexcept { + cleanup(); + fData = other.fData; + fSign = other.fSign; + other.fData = nullptr; + return *this; + } + + private: + SimpleNumber(impl::UFormattedNumberData* data, UErrorCode& status); + SimpleNumber(const SimpleNumber&) = delete; + SimpleNumber& operator=(const SimpleNumber&) = delete; + + void cleanup(); + + impl::UFormattedNumberData* fData = nullptr; + USimpleNumberSign fSign = UNUM_SIMPLE_NUMBER_NO_SIGN; + + friend class SimpleNumberFormatter; +}; + + +/** + * A special NumberFormatter focused on smaller binary size and memory use. + * + * SimpleNumberFormatter is capable of basic number formatting, including grouping separators, + * sign display, and rounding. It is not capable of currencies, compact notation, or units. + * + * This class is immutable and not intended for public subclassing. This class is movable but not copyable. + * + * @draft ICU 73 + */ +class U_I18N_API SimpleNumberFormatter : public UMemory { + public: + /** + * Creates a new SimpleNumberFormatter with all locale defaults. + * + * @draft ICU 73 + */ + static SimpleNumberFormatter forLocale( + const icu::Locale &locale, + UErrorCode &status); + + /** + * Creates a new SimpleNumberFormatter, overriding the grouping strategy. + * + * @draft ICU 73 + */ + static SimpleNumberFormatter forLocaleAndGroupingStrategy( + const icu::Locale &locale, + UNumberGroupingStrategy groupingStrategy, + UErrorCode &status); + + /** + * Creates a new SimpleNumberFormatter, overriding the grouping strategy and symbols. + * + * IMPORTANT: For efficiency, this function borrows the symbols. The symbols MUST remain valid + * for the lifetime of the SimpleNumberFormatter. + * + * @draft ICU 73 + */ + static SimpleNumberFormatter forLocaleAndSymbolsAndGroupingStrategy( + const icu::Locale &locale, + const DecimalFormatSymbols &symbols, + UNumberGroupingStrategy groupingStrategy, + UErrorCode &status); + + /** + * Formats a value using this SimpleNumberFormatter. + * + * The SimpleNumber argument is "consumed". A new SimpleNumber object should be created for + * every formatting operation. + * + * @draft ICU 73 + */ + FormattedNumber format(SimpleNumber value, UErrorCode &status) const; + + /** + * Formats an integer using this SimpleNumberFormatter. + * + * For more control over the formatting, use SimpleNumber. + * + * @draft ICU 73 + */ + FormattedNumber formatInt64(int64_t value, UErrorCode &status) const { + return format(SimpleNumber::forInt64(value, status), status); + } + +#ifndef U_HIDE_INTERNAL_API + /** + * Run the formatter with the internal types. + * @internal + */ + void formatImpl(impl::UFormattedNumberData* data, USimpleNumberSign sign, UErrorCode& status) const; +#endif // U_HIDE_INTERNAL_API + + /** + * Destruct this SimpleNumberFormatter, cleaning up any memory it might own. + * + * @draft ICU 73 + */ + ~SimpleNumberFormatter() { + cleanup(); + } + + /** + * Creates a shell, initialized but non-functional SimpleNumberFormatter. + * + * @draft ICU 73 + */ + SimpleNumberFormatter() = default; + + /** + * SimpleNumberFormatter: Move constructor. + * + * @draft ICU 73 + */ + SimpleNumberFormatter(SimpleNumberFormatter&& other) noexcept { + fGroupingStrategy = other.fGroupingStrategy; + fOwnedSymbols = other.fOwnedSymbols; + fMicros = other.fMicros; + fPatternModifier = other.fPatternModifier; + other.fOwnedSymbols = nullptr; + other.fMicros = nullptr; + other.fPatternModifier = nullptr; + } + + /** + * SimpleNumberFormatter: Move assignment. + * + * @draft ICU 73 + */ + SimpleNumberFormatter& operator=(SimpleNumberFormatter&& other) noexcept { + cleanup(); + fGroupingStrategy = other.fGroupingStrategy; + fOwnedSymbols = other.fOwnedSymbols; + fMicros = other.fMicros; + fPatternModifier = other.fPatternModifier; + other.fOwnedSymbols = nullptr; + other.fMicros = nullptr; + other.fPatternModifier = nullptr; + return *this; + } + + private: + void initialize( + const icu::Locale &locale, + const DecimalFormatSymbols &symbols, + UNumberGroupingStrategy groupingStrategy, + UErrorCode &status); + + void cleanup(); + + SimpleNumberFormatter(const SimpleNumberFormatter&) = delete; + + SimpleNumberFormatter& operator=(const SimpleNumberFormatter&) = delete; + + UNumberGroupingStrategy fGroupingStrategy = UNUM_GROUPING_AUTO; + + // Owned Pointers: + DecimalFormatSymbols* fOwnedSymbols = nullptr; // can be empty + impl::SimpleMicroProps* fMicros = nullptr; + impl::AdoptingSignumModifierStore* fPatternModifier = nullptr; +}; + + +#endif // U_HIDE_DRAFT_API + +} // namespace number +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __SIMPLENUMBERFORMATTERH__ + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpletz.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpletz.h new file mode 100644 index 0000000000000000000000000000000000000000..9005c9ccbaf6ecb82d1bd93c0f171dbc8314afb2 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/simpletz.h @@ -0,0 +1,940 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************** + * Copyright (C) 1997-2013, International Business Machines * + * Corporation and others. All Rights Reserved. * + ******************************************************************************** + * + * File SIMPLETZ.H + * + * Modification History: + * + * Date Name Description + * 04/21/97 aliu Overhauled header. + * 08/10/98 stephen JDK 1.2 sync + * Added setStartRule() / setEndRule() overloads + * Added hasSameRules() + * 09/02/98 stephen Added getOffset(monthLen) + * Changed getOffset() to take UErrorCode + * 07/09/99 stephen Removed millisPerHour (unused, for HP compiler) + * 12/02/99 aliu Added TimeMode and constructor and setStart/EndRule + * methods that take TimeMode. Added to docs. + ******************************************************************************** + */ + +#ifndef SIMPLETZ_H +#define SIMPLETZ_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: SimpleTimeZone is a concrete subclass of TimeZone. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/basictz.h" + +U_NAMESPACE_BEGIN + +// forward declaration +class InitialTimeZoneRule; +class TimeZoneTransition; +class AnnualTimeZoneRule; + +/** + * SimpleTimeZone is a concrete subclass of TimeZone + * that represents a time zone for use with a Gregorian calendar. This + * class does not handle historical changes. + *

+ * When specifying daylight-savings-time begin and end dates, use a negative value for + * dayOfWeekInMonth to indicate that SimpleTimeZone should + * count from the end of the month backwards. For example, if Daylight Savings + * Time starts or ends at the last Sunday a month, use dayOfWeekInMonth = -1 + * along with dayOfWeek = UCAL_SUNDAY to specify the rule. + * + * @see Calendar + * @see GregorianCalendar + * @see TimeZone + * @author D. Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu + */ +class U_I18N_API SimpleTimeZone: public BasicTimeZone { +public: + + /** + * TimeMode is used, together with a millisecond offset after + * midnight, to specify a rule transition time. Most rules + * transition at a local wall time, that is, according to the + * current time in effect, either standard, or DST. However, some + * rules transition at local standard time, and some at a specific + * UTC time. Although it might seem that all times could be + * converted to wall time, thus eliminating the need for this + * parameter, this is not the case. + * @stable ICU 2.0 + */ + enum TimeMode { + WALL_TIME = 0, + STANDARD_TIME, + UTC_TIME + }; + + /** + * Copy constructor + * @param source the object to be copied. + * @stable ICU 2.0 + */ + SimpleTimeZone(const SimpleTimeZone& source); + + /** + * Default assignment operator + * @param right the object to be copied. + * @stable ICU 2.0 + */ + SimpleTimeZone& operator=(const SimpleTimeZone& right); + + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~SimpleTimeZone(); + + /** + * Returns true if the two TimeZone objects are equal; that is, they have + * the same ID, raw GMT offset, and DST rules. + * + * @param that The SimpleTimeZone object to be compared with. + * @return true if the given time zone is equal to this time zone; false + * otherwise. + * @stable ICU 2.0 + */ + virtual bool operator==(const TimeZone& that) const override; + + /** + * Constructs a SimpleTimeZone with the given raw GMT offset and time zone ID, + * and which doesn't observe daylight savings time. Normally you should use + * TimeZone::createInstance() to create a TimeZone instead of creating a + * SimpleTimeZone directly with this constructor. + * + * @param rawOffsetGMT The given base time zone offset to GMT. + * @param ID The timezone ID which is obtained from + * TimeZone.getAvailableIDs. + * @stable ICU 2.0 + */ + SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID); + + /** + * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, + * and times to start and end daylight savings time. To create a TimeZone that + * doesn't observe daylight savings time, don't use this constructor; use + * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use + * TimeZone.createInstance() to create a TimeZone instead of creating a + * SimpleTimeZone directly with this constructor. + *

+ * Various types of daylight-savings time rules can be specified by using different + * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a + * complete explanation of how these parameters work, see the documentation for + * setStartRule(). + * + * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset + * @param ID The new SimpleTimeZone's time zone ID. + * @param savingsStartMonth The daylight savings starting month. Month is + * 0-based. eg, 0 for January. + * @param savingsStartDayOfWeekInMonth The daylight savings starting + * day-of-week-in-month. See setStartRule() for a + * complete explanation. + * @param savingsStartDayOfWeek The daylight savings starting day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsStartTime The daylight savings starting time, expressed as the + * number of milliseconds after midnight. + * @param savingsEndMonth The daylight savings ending month. Month is + * 0-based. eg, 0 for January. + * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. + * See setStartRule() for a complete explanation. + * @param savingsEndDayOfWeek The daylight savings ending day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsEndTime The daylight savings ending time, expressed as the + * number of milliseconds after midnight. + * @param status An UErrorCode to receive the status. + * @stable ICU 2.0 + */ + SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, + int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, + int8_t savingsStartDayOfWeek, int32_t savingsStartTime, + int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, + int8_t savingsEndDayOfWeek, int32_t savingsEndTime, + UErrorCode& status); + /** + * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, + * and times to start and end daylight savings time. To create a TimeZone that + * doesn't observe daylight savings time, don't use this constructor; use + * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use + * TimeZone.createInstance() to create a TimeZone instead of creating a + * SimpleTimeZone directly with this constructor. + *

+ * Various types of daylight-savings time rules can be specified by using different + * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a + * complete explanation of how these parameters work, see the documentation for + * setStartRule(). + * + * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset + * @param ID The new SimpleTimeZone's time zone ID. + * @param savingsStartMonth The daylight savings starting month. Month is + * 0-based. eg, 0 for January. + * @param savingsStartDayOfWeekInMonth The daylight savings starting + * day-of-week-in-month. See setStartRule() for a + * complete explanation. + * @param savingsStartDayOfWeek The daylight savings starting day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsStartTime The daylight savings starting time, expressed as the + * number of milliseconds after midnight. + * @param savingsEndMonth The daylight savings ending month. Month is + * 0-based. eg, 0 for January. + * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. + * See setStartRule() for a complete explanation. + * @param savingsEndDayOfWeek The daylight savings ending day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsEndTime The daylight savings ending time, expressed as the + * number of milliseconds after midnight. + * @param savingsDST The number of milliseconds added to standard time + * to get DST time. Default is one hour. + * @param status An UErrorCode to receive the status. + * @stable ICU 2.0 + */ + SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, + int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, + int8_t savingsStartDayOfWeek, int32_t savingsStartTime, + int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, + int8_t savingsEndDayOfWeek, int32_t savingsEndTime, + int32_t savingsDST, UErrorCode& status); + + /** + * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, + * and times to start and end daylight savings time. To create a TimeZone that + * doesn't observe daylight savings time, don't use this constructor; use + * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use + * TimeZone.createInstance() to create a TimeZone instead of creating a + * SimpleTimeZone directly with this constructor. + *

+ * Various types of daylight-savings time rules can be specified by using different + * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a + * complete explanation of how these parameters work, see the documentation for + * setStartRule(). + * + * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset + * @param ID The new SimpleTimeZone's time zone ID. + * @param savingsStartMonth The daylight savings starting month. Month is + * 0-based. eg, 0 for January. + * @param savingsStartDayOfWeekInMonth The daylight savings starting + * day-of-week-in-month. See setStartRule() for a + * complete explanation. + * @param savingsStartDayOfWeek The daylight savings starting day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsStartTime The daylight savings starting time, expressed as the + * number of milliseconds after midnight. + * @param savingsStartTimeMode Whether the start time is local wall time, local + * standard time, or UTC time. Default is local wall time. + * @param savingsEndMonth The daylight savings ending month. Month is + * 0-based. eg, 0 for January. + * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. + * See setStartRule() for a complete explanation. + * @param savingsEndDayOfWeek The daylight savings ending day-of-week. + * See setStartRule() for a complete explanation. + * @param savingsEndTime The daylight savings ending time, expressed as the + * number of milliseconds after midnight. + * @param savingsEndTimeMode Whether the end time is local wall time, local + * standard time, or UTC time. Default is local wall time. + * @param savingsDST The number of milliseconds added to standard time + * to get DST time. Default is one hour. + * @param status An UErrorCode to receive the status. + * @stable ICU 2.0 + */ + SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, + int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, + int8_t savingsStartDayOfWeek, int32_t savingsStartTime, + TimeMode savingsStartTimeMode, + int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, + int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode, + int32_t savingsDST, UErrorCode& status); + + /** + * Sets the daylight savings starting year, that is, the year this time zone began + * observing its specified daylight savings time rules. The time zone is considered + * not to observe daylight savings time prior to that year; SimpleTimeZone doesn't + * support historical daylight-savings-time rules. + * @param year the daylight savings starting year. + * @stable ICU 2.0 + */ + void setStartYear(int32_t year); + + /** + * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings + * Time starts at the second Sunday in March, at 2 AM in standard time. + * Therefore, you can set the start rule by calling: + * setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000); + * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate + * the exact starting date. Their exact meaning depend on their respective signs, + * allowing various types of rules to be constructed, as follows: + *

    + *
  • If both dayOfWeekInMonth and dayOfWeek are positive, they specify the + * day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday + * of the month).
  • + *
  • If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify + * the day of week in the month counting backward from the end of the month. + * (e.g., (-1, MONDAY) is the last Monday in the month)
  • + *
  • If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth + * specifies the day of the month, regardless of what day of the week it is. + * (e.g., (10, 0) is the tenth day of the month)
  • + *
  • If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth + * specifies the day of the month counting backward from the end of the + * month, regardless of what day of the week it is (e.g., (-2, 0) is the + * next-to-last day of the month).
  • + *
  • If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the + * first specified day of the week on or after the specified day of the month. + * (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month + * [or the 15th itself if the 15th is a Sunday].)
  • + *
  • If dayOfWeek and DayOfWeekInMonth are both negative, they specify the + * last specified day of the week on or before the specified day of the month. + * (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month + * [or the 20th itself if the 20th is a Tuesday].)
  • + *
+ * @param month the daylight savings starting month. Month is 0-based. + * eg, 0 for January. + * @param dayOfWeekInMonth the daylight savings starting + * day-of-week-in-month. Please see the member description for an example. + * @param dayOfWeek the daylight savings starting day-of-week. Please see + * the member description for an example. + * @param time the daylight savings starting time. Please see the member + * description for an example. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, + int32_t time, UErrorCode& status); + /** + * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings + * Time starts at the second Sunday in March, at 2 AM in standard time. + * Therefore, you can set the start rule by calling: + * setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000); + * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate + * the exact starting date. Their exact meaning depend on their respective signs, + * allowing various types of rules to be constructed, as follows: + *
    + *
  • If both dayOfWeekInMonth and dayOfWeek are positive, they specify the + * day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday + * of the month).
  • + *
  • If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify + * the day of week in the month counting backward from the end of the month. + * (e.g., (-1, MONDAY) is the last Monday in the month)
  • + *
  • If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth + * specifies the day of the month, regardless of what day of the week it is. + * (e.g., (10, 0) is the tenth day of the month)
  • + *
  • If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth + * specifies the day of the month counting backward from the end of the + * month, regardless of what day of the week it is (e.g., (-2, 0) is the + * next-to-last day of the month).
  • + *
  • If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the + * first specified day of the week on or after the specified day of the month. + * (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month + * [or the 15th itself if the 15th is a Sunday].)
  • + *
  • If dayOfWeek and DayOfWeekInMonth are both negative, they specify the + * last specified day of the week on or before the specified day of the month. + * (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month + * [or the 20th itself if the 20th is a Tuesday].)
  • + *
+ * @param month the daylight savings starting month. Month is 0-based. + * eg, 0 for January. + * @param dayOfWeekInMonth the daylight savings starting + * day-of-week-in-month. Please see the member description for an example. + * @param dayOfWeek the daylight savings starting day-of-week. Please see + * the member description for an example. + * @param time the daylight savings starting time. Please see the member + * description for an example. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, + int32_t time, TimeMode mode, UErrorCode& status); + + /** + * Sets the DST start rule to a fixed date within a month. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth The date in that month (1-based). + * @param time The time of that day (number of millis after midnight) + * when DST takes effect in local wall time, which is + * standard time in this case. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time, + UErrorCode& status); + /** + * Sets the DST start rule to a fixed date within a month. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth The date in that month (1-based). + * @param time The time of that day (number of millis after midnight) + * when DST takes effect in local wall time, which is + * standard time in this case. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time, + TimeMode mode, UErrorCode& status); + + /** + * Sets the DST start rule to a weekday before or after a give date within + * a month, e.g., the first Monday on or after the 8th. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth A date within that month (1-based). + * @param dayOfWeek The day of the week on which this rule occurs. + * @param time The time of that day (number of millis after midnight) + * when DST takes effect in local wall time, which is + * standard time in this case. + * @param after If true, this rule selects the first dayOfWeek on + * or after dayOfMonth. If false, this rule selects + * the last dayOfWeek on or before dayOfMonth. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, + int32_t time, UBool after, UErrorCode& status); + /** + * Sets the DST start rule to a weekday before or after a give date within + * a month, e.g., the first Monday on or after the 8th. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth A date within that month (1-based). + * @param dayOfWeek The day of the week on which this rule occurs. + * @param time The time of that day (number of millis after midnight) + * when DST takes effect in local wall time, which is + * standard time in this case. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param after If true, this rule selects the first dayOfWeek on + * or after dayOfMonth. If false, this rule selects + * the last dayOfWeek on or before dayOfMonth. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, + int32_t time, TimeMode mode, UBool after, UErrorCode& status); + + /** + * Sets the daylight savings ending rule. For example, if Daylight + * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. + * Therefore, you can set the end rule by calling: + *
+     *    setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
+     * 
+ * Various other types of rules can be specified by manipulating the dayOfWeek + * and dayOfWeekInMonth parameters. For complete details, see the documentation + * for setStartRule(). + * + * @param month the daylight savings ending month. Month is 0-based. + * eg, 0 for January. + * @param dayOfWeekInMonth the daylight savings ending + * day-of-week-in-month. See setStartRule() for a complete explanation. + * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule() + * for a complete explanation. + * @param time the daylight savings ending time. Please see the member + * description for an example. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, + int32_t time, UErrorCode& status); + + /** + * Sets the daylight savings ending rule. For example, if Daylight + * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. + * Therefore, you can set the end rule by calling: + *
+     *    setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
+     * 
+ * Various other types of rules can be specified by manipulating the dayOfWeek + * and dayOfWeekInMonth parameters. For complete details, see the documentation + * for setStartRule(). + * + * @param month the daylight savings ending month. Month is 0-based. + * eg, 0 for January. + * @param dayOfWeekInMonth the daylight savings ending + * day-of-week-in-month. See setStartRule() for a complete explanation. + * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule() + * for a complete explanation. + * @param time the daylight savings ending time. Please see the member + * description for an example. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, + int32_t time, TimeMode mode, UErrorCode& status); + + /** + * Sets the DST end rule to a fixed date within a month. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth The date in that month (1-based). + * @param time The time of that day (number of millis after midnight) + * when DST ends in local wall time, which is daylight + * time in this case. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, UErrorCode& status); + + /** + * Sets the DST end rule to a fixed date within a month. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth The date in that month (1-based). + * @param time The time of that day (number of millis after midnight) + * when DST ends in local wall time, which is daylight + * time in this case. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, + TimeMode mode, UErrorCode& status); + + /** + * Sets the DST end rule to a weekday before or after a give date within + * a month, e.g., the first Monday on or after the 8th. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth A date within that month (1-based). + * @param dayOfWeek The day of the week on which this rule occurs. + * @param time The time of that day (number of millis after midnight) + * when DST ends in local wall time, which is daylight + * time in this case. + * @param after If true, this rule selects the first dayOfWeek on + * or after dayOfMonth. If false, this rule selects + * the last dayOfWeek on or before dayOfMonth. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, + int32_t time, UBool after, UErrorCode& status); + + /** + * Sets the DST end rule to a weekday before or after a give date within + * a month, e.g., the first Monday on or after the 8th. + * + * @param month The month in which this rule occurs (0-based). + * @param dayOfMonth A date within that month (1-based). + * @param dayOfWeek The day of the week on which this rule occurs. + * @param time The time of that day (number of millis after midnight) + * when DST ends in local wall time, which is daylight + * time in this case. + * @param mode whether the time is local wall time, local standard time, + * or UTC time. Default is local wall time. + * @param after If true, this rule selects the first dayOfWeek on + * or after dayOfMonth. If false, this rule selects + * the last dayOfWeek on or before dayOfMonth. + * @param status An UErrorCode + * @stable ICU 2.0 + */ + void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, + int32_t time, TimeMode mode, UBool after, UErrorCode& status); + + /** + * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time in this time zone, taking daylight savings time into + * account) as of a particular reference date. The reference date is used to determine + * whether daylight savings time is in effect and needs to be figured into the offset + * that is returned (in other words, what is the adjusted GMT offset in this time zone + * at this particular date and time?). For the time zones produced by createTimeZone(), + * the reference data is specified according to the Gregorian calendar, and the date + * and time fields are in GMT, NOT local time. + * + * @param era The reference date's era + * @param year The reference date's year + * @param month The reference date's month (0-based; 0 is January) + * @param day The reference date's day-in-month (1-based) + * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) + * @param millis The reference date's milliseconds in day, UTT (NOT local time). + * @param status An UErrorCode to receive the status. + * @return The offset in milliseconds to add to GMT to get local time. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const override; + + /** + * Gets the time zone offset, for current date, modified in case of + * daylight savings. This is the offset to add *to* UTC to get local time. + * @param era the era of the given date. + * @param year the year in the given date. + * @param month the month in the given date. + * Month is 0-based. e.g., 0 for January. + * @param day the day-in-month of the given date. + * @param dayOfWeek the day-of-week of the given date. + * @param milliseconds the millis in day in standard local time. + * @param monthLength the length of the given month in days. + * @param status An UErrorCode to receive the status. + * @return the offset to add *to* GMT to get local time. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t milliseconds, + int32_t monthLength, UErrorCode& status) const override; + /** + * Gets the time zone offset, for current date, modified in case of + * daylight savings. This is the offset to add *to* UTC to get local time. + * @param era the era of the given date. + * @param year the year in the given date. + * @param month the month in the given date. + * Month is 0-based. e.g., 0 for January. + * @param day the day-in-month of the given date. + * @param dayOfWeek the day-of-week of the given date. + * @param milliseconds the millis in day in standard local time. + * @param monthLength the length of the given month in days. + * @param prevMonthLength length of the previous month in days. + * @param status An UErrorCode to receive the status. + * @return the offset to add *to* GMT to get local time. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t milliseconds, + int32_t monthLength, int32_t prevMonthLength, + UErrorCode& status) const; + + /** + * Redeclared TimeZone method. This implementation simply calls + * the base class method, which otherwise would be hidden. + * @stable ICU 2.8 + */ + virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, + int32_t& dstOffset, UErrorCode& ec) const override; + + /** + * Get time zone offsets from local wall time. + * @stable ICU 69 + */ + virtual void getOffsetFromLocal( + UDate date, UTimeZoneLocalOption nonExistingTimeOpt, + UTimeZoneLocalOption duplicatedTimeOpt, + int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const override; + + /** + * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @return The TimeZone's raw GMT offset. + * @stable ICU 2.0 + */ + virtual int32_t getRawOffset(void) const override; + + /** + * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @param offsetMillis The new raw GMT offset for this time zone. + * @stable ICU 2.0 + */ + virtual void setRawOffset(int32_t offsetMillis) override; + + /** + * Sets the amount of time in ms that the clock is advanced during DST. + * @param millisSavedDuringDST the number of milliseconds the time is + * advanced with respect to standard time when the daylight savings rules + * are in effect. Typically one hour (+3600000). The amount could be negative, + * but not 0. + * @param status An UErrorCode to receive the status. + * @stable ICU 2.0 + */ + void setDSTSavings(int32_t millisSavedDuringDST, UErrorCode& status); + + /** + * Returns the amount of time in ms that the clock is advanced during DST. + * @return the number of milliseconds the time is + * advanced with respect to standard time when the daylight savings rules + * are in effect. Typically one hour (+3600000). The amount could be negative, + * but not 0. + * @stable ICU 2.0 + */ + virtual int32_t getDSTSavings(void) const override; + + /** + * Queries if this TimeZone uses Daylight Savings Time. + * + * @return True if this TimeZone uses Daylight Savings Time; false otherwise. + * @stable ICU 2.0 + */ + virtual UBool useDaylightTime(void) const override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Returns true if the given date is within the period when daylight savings time + * is in effect; false otherwise. If the TimeZone doesn't observe daylight savings + * time, this functions always returns false. + * This method is wasteful since it creates a new GregorianCalendar and + * deletes it each time it is called. This is a deprecated method + * and provided only for Java compatibility. + * + * @param date The date to test. + * @param status An UErrorCode to receive the status. + * @return true if the given date is in Daylight Savings Time; + * false otherwise. + * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. + */ + virtual UBool inDaylightTime(UDate date, UErrorCode& status) const override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Return true if this zone has the same rules and offset as another zone. + * @param other the TimeZone object to be compared with + * @return true if the given zone has the same rules and offset as this one + * @stable ICU 2.0 + */ + UBool hasSameRules(const TimeZone& other) const override; + + /** + * Clones TimeZone objects polymorphically. Clients are responsible for deleting + * the TimeZone object cloned. + * + * @return A new copy of this TimeZone object. + * @stable ICU 2.0 + */ + virtual SimpleTimeZone* clone() const override; + + /** + * Gets the first time zone transition after the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the first transition after the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override; + + /** + * Gets the most recent time zone transition before the base time. + * @param base The base time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives the most recent transition before the base time. + * @return true if the transition is found. + * @stable ICU 3.8 + */ + virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override; + + /** + * Returns the number of TimeZoneRules which represents time transitions, + * for this time zone, that is, all TimeZoneRules for this time zone except + * InitialTimeZoneRule. The return value range is 0 or any positive value. + * @param status Receives error status code. + * @return The number of TimeZoneRules representing time transitions. + * @stable ICU 3.8 + */ + virtual int32_t countTransitionRules(UErrorCode& status) const override; + + /** + * Gets the InitialTimeZoneRule and the set of TimeZoneRule + * which represent time transitions for this time zone. On successful return, + * the argument initial points to non-nullptr InitialTimeZoneRule and + * the array trsrules is filled with 0 or multiple TimeZoneRule + * instances up to the size specified by trscount. The results are referencing the + * rule instance held by this time zone instance. Therefore, after this time zone + * is destructed, they are no longer available. + * @param initial Receives the initial timezone rule + * @param trsrules Receives the timezone transition rules + * @param trscount On input, specify the size of the array 'transitions' receiving + * the timezone transition rules. On output, actual number of + * rules filled in the array will be set. + * @param status Receives error status code. + * @stable ICU 3.8 + */ + virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, + const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const override; + + +public: + + /** + * Override TimeZone Returns a unique class ID POLYMORPHICALLY. Pure virtual + * override. This method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call + * this method. + * + * @return The class ID for this object. All objects of a given class have the + * same class ID. Objects of other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Return the class ID for this class. This is useful only for comparing to a return + * value from getDynamicClassID(). For example: + *
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +private: + /** + * Constants specifying values of startMode and endMode. + */ + enum EMode + { + DOM_MODE = 1, + DOW_IN_MONTH_MODE, + DOW_GE_DOM_MODE, + DOW_LE_DOM_MODE + }; + + SimpleTimeZone() = delete; // default constructor not implemented + + /** + * Internal construction method. + * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset + * @param startMonth the month DST starts + * @param startDay the day DST starts + * @param startDayOfWeek the DOW DST starts + * @param startTime the time DST starts + * @param startTimeMode Whether the start time is local wall time, local + * standard time, or UTC time. Default is local wall time. + * @param endMonth the month DST ends + * @param endDay the day DST ends + * @param endDayOfWeek the DOW DST ends + * @param endTime the time DST ends + * @param endTimeMode Whether the end time is local wall time, local + * standard time, or UTC time. Default is local wall time. + * @param dstSavings The number of milliseconds added to standard time + * to get DST time. Default is one hour. + * @param status An UErrorCode to receive the status. + */ + void construct(int32_t rawOffsetGMT, + int8_t startMonth, int8_t startDay, int8_t startDayOfWeek, + int32_t startTime, TimeMode startTimeMode, + int8_t endMonth, int8_t endDay, int8_t endDayOfWeek, + int32_t endTime, TimeMode endTimeMode, + int32_t dstSavings, UErrorCode& status); + + /** + * Compare a given date in the year to a rule. Return 1, 0, or -1, depending + * on whether the date is after, equal to, or before the rule date. The + * millis are compared directly against the ruleMillis, so any + * standard-daylight adjustments must be handled by the caller. + * + * @return 1 if the date is after the rule date, -1 if the date is before + * the rule date, or 0 if the date is equal to the rule date. + */ + static int32_t compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen, + int8_t dayOfMonth, + int8_t dayOfWeek, int32_t millis, int32_t millisDelta, + EMode ruleMode, int8_t ruleMonth, int8_t ruleDayOfWeek, + int8_t ruleDay, int32_t ruleMillis); + + /** + * Given a set of encoded rules in startDay and startDayOfMonth, decode + * them and set the startMode appropriately. Do the same for endDay and + * endDayOfMonth. + *

+ * Upon entry, the day of week variables may be zero or + * negative, in order to indicate special modes. The day of month + * variables may also be negative. + *

+ * Upon exit, the mode variables will be + * set, and the day of week and day of month variables will be positive. + *

+ * This method also recognizes a startDay or endDay of zero as indicating + * no DST. + */ + void decodeRules(UErrorCode& status); + void decodeStartRule(UErrorCode& status); + void decodeEndRule(UErrorCode& status); + + int8_t startMonth, startDay, startDayOfWeek; // the month, day, DOW, and time DST starts + int32_t startTime; + TimeMode startTimeMode, endTimeMode; // Mode for startTime, endTime; see TimeMode + int8_t endMonth, endDay, endDayOfWeek; // the month, day, DOW, and time DST ends + int32_t endTime; + int32_t startYear; // the year these DST rules took effect + int32_t rawOffset; // the TimeZone's raw GMT offset + UBool useDaylight; // flag indicating whether this TimeZone uses DST + static const int8_t STATICMONTHLENGTH[12]; // lengths of the months + EMode startMode, endMode; // flags indicating what kind of rules the DST rules are + + /** + * A positive value indicating the amount of time saved during DST in ms. + * Typically one hour; sometimes 30 minutes. + */ + int32_t dstSavings; + + /* Private for BasicTimeZone implementation */ + void checkTransitionRules(UErrorCode& status) const; + void initTransitionRules(UErrorCode& status); + void clearTransitionRules(void); + void deleteTransitionRules(void); + UBool transitionRulesInitialized; + InitialTimeZoneRule* initialRule; + TimeZoneTransition* firstTransition; + AnnualTimeZoneRule* stdRule; + AnnualTimeZoneRule* dstRule; +}; + +inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth, + int32_t dayOfWeek, + int32_t time, UErrorCode& status) { + setStartRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status); +} + +inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, + int32_t time, + UErrorCode& status) { + setStartRule(month, dayOfMonth, time, WALL_TIME, status); +} + +inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, + int32_t dayOfWeek, + int32_t time, UBool after, UErrorCode& status) { + setStartRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status); +} + +inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth, + int32_t dayOfWeek, + int32_t time, UErrorCode& status) { + setEndRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status); +} + +inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, + int32_t time, UErrorCode& status) { + setEndRule(month, dayOfMonth, time, WALL_TIME, status); +} + +inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, + int32_t time, UBool after, UErrorCode& status) { + setEndRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status); +} + +inline void +SimpleTimeZone::getOffset(UDate date, UBool local, int32_t& rawOffsetRef, + int32_t& dstOffsetRef, UErrorCode& ec) const { + TimeZone::getOffset(date, local, rawOffsetRef, dstOffsetRef, ec); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _SIMPLETZ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/smpdtfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/smpdtfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..4343bfbca53aa95f2965c2450fbfc3f7ad26804d --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/smpdtfmt.h @@ -0,0 +1,1672 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +* Copyright (C) 1997-2016, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* File SMPDTFMT.H +* +* Modification History: +* +* Date Name Description +* 02/19/97 aliu Converted from java. +* 07/09/97 helena Make ParsePosition into a class. +* 07/21/98 stephen Added GMT_PLUS, GMT_MINUS +* Changed setTwoDigitStartDate to set2DigitYearStart +* Changed getTwoDigitStartDate to get2DigitYearStart +* Removed subParseLong +* Removed getZoneIndex (added in DateFormatSymbols) +* 06/14/99 stephen Removed fgTimeZoneDataSuffix +* 10/14/99 aliu Updated class doc to describe 2-digit year parsing +* {j28 4182066}. +******************************************************************************* +*/ + +#ifndef SMPDTFMT_H +#define SMPDTFMT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Format and parse dates in a language-independent manner. + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/datefmt.h" +#include "unicode/udisplaycontext.h" +#include "unicode/tzfmt.h" /* for UTimeZoneFormatTimeType */ +#include "unicode/brkiter.h" + +U_NAMESPACE_BEGIN + +class DateFormatSymbols; +class DateFormat; +class MessageFormat; +class FieldPositionHandler; +class TimeZoneFormat; +class SharedNumberFormat; +class SimpleDateFormatMutableNFs; +class DateIntervalFormat; + +namespace number { +class LocalizedNumberFormatter; +class SimpleNumberFormatter; +} + +/** + * + * SimpleDateFormat is a concrete class for formatting and parsing dates in a + * language-independent manner. It allows for formatting (millis -> text), + * parsing (text -> millis), and normalization. Formats/Parses a date or time, + * which is the standard milliseconds since 24:00 GMT, Jan 1, 1970. + *

+ * Clients are encouraged to create a date-time formatter using DateFormat::getInstance(), + * getDateInstance(), getDateInstance(), or getDateTimeInstance() rather than + * explicitly constructing an instance of SimpleDateFormat. This way, the client + * is guaranteed to get an appropriate formatting pattern for whatever locale the + * program is running in. However, if the client needs something more unusual than + * the default patterns in the locales, he can construct a SimpleDateFormat directly + * and give it an appropriate pattern (or use one of the factory methods on DateFormat + * and modify the pattern after the fact with toPattern() and applyPattern(). + * + *

Date and Time Patterns:

+ * + *

Date and time formats are specified by date and time pattern strings. + * Within date and time pattern strings, all unquoted ASCII letters [A-Za-z] are reserved + * as pattern letters representing calendar fields. SimpleDateFormat supports + * the date and time formatting algorithm and pattern letters defined by + * UTS#35 + * Unicode Locale Data Markup Language (LDML) and further documented for ICU in the + * ICU + * User Guide. The following pattern letters are currently available (note that the actual + * values depend on CLDR and may change from the examples shown here):

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
FieldSym.No.ExampleDescription
eraG1..3ADEra - Replaced with the Era string for the current date. One to three letters for the + * abbreviated form, four letters for the long (wide) form, five for the narrow form.
4Anno Domini
5A
yeary1..n1996Year. Normally the length specifies the padding, but for two letters it also specifies the maximum + * length. Example:
+ *
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Yearyyyyyyyyyyyyyyy
AD 1101001000100001
AD 121212012001200012
AD 12312323123012300123
AD 12341234341234123401234
AD 123451234545123451234512345
+ *
+ *
Y1..n1997Year (in "Week of Year" based calendars). Normally the length specifies the padding, + * but for two letters it also specifies the maximum length. This year designation is used in ISO + * year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems + * where week date processing is desired. May not always be the same value as calendar year.
u1..n4601Extended year. This is a single number designating the year of this calendar system, encompassing + * all supra-year fields. For example, for the Julian calendar system, year numbers are positive, with an + * era of BCE or CE. An extended year value for the Julian calendar system assigns positive values to CE + * years and negative values to BCE years, with 1 BCE being year 0.
U1..3甲子Cyclic year name. Calendars such as the Chinese lunar calendar (and related calendars) + * and the Hindu calendars use 60-year cycles of year names. Use one through three letters for the abbreviated + * name, four for the full (wide) name, or five for the narrow name (currently the data only provides abbreviated names, + * which will be used for all requested name widths). If the calendar does not provide cyclic year name data, + * or if the year value to be formatted is out of the range of years for which cyclic name data is provided, + * then numeric formatting is used (behaves like 'y').
4(currently also 甲子)
5(currently also 甲子)
quarterQ1..202Quarter - Use one or two for the numerical quarter, three for the abbreviation, or four for the + * full (wide) name (five for the narrow name is not yet supported).
3Q2
42nd quarter
q1..202Stand-Alone Quarter - Use one or two for the numerical quarter, three for the abbreviation, + * or four for the full name (five for the narrow name is not yet supported).
3Q2
42nd quarter
monthM1..209Month - Use one or two for the numerical month, three for the abbreviation, four for + * the full (wide) name, or five for the narrow name. With two ("MM"), the month number is zero-padded + * if necessary (e.g. "08")
3Sep
4September
5S
L1..209Stand-Alone Month - Use one or two for the numerical month, three for the abbreviation, + * four for the full (wide) name, or 5 for the narrow name. With two ("LL"), the month number is zero-padded if + * necessary (e.g. "08")
3Sep
4September
5S
weekw1..227Week of Year. Use "w" to show the minimum number of digits, or "ww" to always show two digits + * (zero-padding if necessary, e.g. "08").
W13Week of Month
dayd1..21Date - Day of the month. Use "d" to show the minimum number of digits, or "dd" to always show + * two digits (zero-padding if necessary, e.g. "08").
D1..3345Day of year
F12Day of Week in Month. The example is for the 2nd Wed in July
g1..n2451334Modified Julian day. This is different from the conventional Julian day number in two regards. + * First, it demarcates days at local zone midnight, rather than noon GMT. Second, it is a local number; + * that is, it depends on the local time zone. It can be thought of as a single number that encompasses + * all the date-related fields.
week
+ * day
E1..3TueDay of week - Use one through three letters for the short day, four for the full (wide) name, + * five for the narrow name, or six for the short name.
4Tuesday
5T
6Tu
e1..22Local day of week. Same as E except adds a numeric value that will depend on the local + * starting day of the week, using one or two letters. For this example, Monday is the first day of the week.
3Tue
4Tuesday
5T
6Tu
c12Stand-Alone local day of week - Use one letter for the local numeric value (same + * as 'e'), three for the short day, four for the full (wide) name, five for the narrow name, or six for + * the short name.
3Tue
4Tuesday
5T
6Tu
perioda1AMAM or PM
hourh1..211Hour [1-12]. When used in skeleton data or in a skeleton passed in an API for flexible data pattern + * generation, it should match the 12-hour-cycle format preferred by the locale (h or K); it should not match + * a 24-hour-cycle format (H or k). Use hh for zero padding.
H1..213Hour [0-23]. When used in skeleton data or in a skeleton passed in an API for flexible data pattern + * generation, it should match the 24-hour-cycle format preferred by the locale (H or k); it should not match a + * 12-hour-cycle format (h or K). Use HH for zero padding.
K1..20Hour [0-11]. When used in a skeleton, only matches K or h, see above. Use KK for zero padding.
k1..224Hour [1-24]. When used in a skeleton, only matches k or H, see above. Use kk for zero padding.
minutem1..259Minute. Use "m" to show the minimum number of digits, or "mm" to always show two digits + * (zero-padding if necessary, e.g. "08").
seconds1..212Second. Use "s" to show the minimum number of digits, or "ss" to always show two digits + * (zero-padding if necessary, e.g. "08").
S1..n3450Fractional Second - truncates (like other time fields) to the count of letters when formatting. + * Appends zeros if more than 3 letters specified. Truncates at three significant digits when parsing. + * (example shows display using pattern SSSS for seconds value 12.34567)
A1..n69540000Milliseconds in day. This field behaves exactly like a composite of all time-related fields, + * not including the zone fields. As such, it also reflects discontinuities of those fields on DST transition + * days. On a day of DST onset, it will jump forward. On a day of DST cessation, it will jump backward. This + * reflects the fact that is must be combined with the offset field to obtain a unique local time value.
zonez1..3PDTThe short specific non-location format. + * Where that is unavailable, falls back to the short localized GMT format ("O").
4Pacific Daylight TimeThe long specific non-location format. + * Where that is unavailable, falls back to the long localized GMT format ("OOOO").
Z1..3-0800The ISO8601 basic format with hours, minutes and optional seconds fields. + * The format is equivalent to RFC 822 zone format (when optional seconds field is absent). + * This is equivalent to the "xxxx" specifier.
4GMT-8:00The long localized GMT format. + * This is equivalent to the "OOOO" specifier.
5-08:00
+ * -07:52:58
The ISO8601 extended format with hours, minutes and optional seconds fields. + * The ISO8601 UTC indicator "Z" is used when local time offset is 0. + * This is equivalent to the "XXXXX" specifier.
O1GMT-8The short localized GMT format.
4GMT-08:00The long localized GMT format.
v1PTThe short generic non-location format. + * Where that is unavailable, falls back to the generic location format ("VVVV"), + * then the short localized GMT format as the final fallback.
4Pacific TimeThe long generic non-location format. + * Where that is unavailable, falls back to generic location format ("VVVV"). + *
V1uslaxThe short time zone ID. + * Where that is unavailable, the special short time zone ID unk (Unknown Zone) is used.
+ * Note: This specifier was originally used for a variant of the short specific non-location format, + * but it was deprecated in the later version of the LDML specification. In CLDR 23/ICU 51, the definition of + * the specifier was changed to designate a short time zone ID.
2America/Los_AngelesThe long time zone ID.
3Los AngelesThe exemplar city (location) for the time zone. + * Where that is unavailable, the localized exemplar city name for the special zone Etc/Unknown is used + * as the fallback (for example, "Unknown City").
4Los Angeles TimeThe generic location format. + * Where that is unavailable, falls back to the long localized GMT format ("OOOO"; + * Note: Fallback is only necessary with a GMT-style Time Zone ID, like Etc/GMT-830.)
+ * This is especially useful when presenting possible timezone choices for user selection, + * since the naming is more uniform than the "v" format.
X1-08
+ * +0530
+ * Z
The ISO8601 basic format with hours field and optional minutes field. + * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
2-0800
+ * Z
The ISO8601 basic format with hours and minutes fields. + * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
3-08:00
+ * Z
The ISO8601 extended format with hours and minutes fields. + * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
4-0800
+ * -075258
+ * Z
The ISO8601 basic format with hours, minutes and optional seconds fields. + * (Note: The seconds field is not supported by the ISO8601 specification.) + * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
5-08:00
+ * -07:52:58
+ * Z
The ISO8601 extended format with hours, minutes and optional seconds fields. + * (Note: The seconds field is not supported by the ISO8601 specification.) + * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
x1-08
+ * +0530
The ISO8601 basic format with hours field and optional minutes field.
2-0800The ISO8601 basic format with hours and minutes fields.
3-08:00The ISO8601 extended format with hours and minutes fields.
4-0800
+ * -075258
The ISO8601 basic format with hours, minutes and optional seconds fields. + * (Note: The seconds field is not supported by the ISO8601 specification.)
5-08:00
+ * -07:52:58
The ISO8601 extended format with hours, minutes and optional seconds fields. + * (Note: The seconds field is not supported by the ISO8601 specification.)
+ * + *

+ * Any characters in the pattern that are not in the ranges of ['a'..'z'] and + * ['A'..'Z'] will be treated as quoted text. For instance, characters + * like ':', '.', ' ', '#' and '@' will appear in the resulting time text + * even they are not embraced within single quotes. + *

+ * A pattern containing any invalid pattern letter will result in a failing + * UErrorCode result during formatting or parsing. + *

+ * Examples using the US locale: + *

+ * \code
+ *    Format Pattern                         Result
+ *    --------------                         -------
+ *    "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->>  1996.07.10 AD at 15:08:56 Pacific Time
+ *    "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
+ *    "h:mm a"                          ->>  12:08 PM
+ *    "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
+ *    "K:mm a, vvv"                     ->>  0:00 PM, PT
+ *    "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
+ * \endcode
+ * 
+ * Code Sample: + *
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
+ *     pdt->setStartRule( Calendar::APRIL, 1, Calendar::SUNDAY, 2*60*60*1000);
+ *     pdt->setEndRule( Calendar::OCTOBER, -1, Calendar::SUNDAY, 2*60*60*1000);
+ *
+ *     // Format the current time.
+ *     SimpleDateFormat* formatter
+ *         = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz", success );
+ *     GregorianCalendar cal(success);
+ *     UDate currentTime_1 = cal.getTime(success);
+ *     FieldPosition fp(FieldPosition::DONT_CARE);
+ *     UnicodeString dateString;
+ *     formatter->format( currentTime_1, dateString, fp );
+ *     cout << "result: " << dateString << endl;
+ *
+ *     // Parse the previous string back into a Date.
+ *     ParsePosition pp(0);
+ *     UDate currentTime_2 = formatter->parse(dateString, pp );
+ * \endcode
+ * 
+ * In the above example, the time value "currentTime_2" obtained from parsing + * will be equal to currentTime_1. However, they may not be equal if the am/pm + * marker 'a' is left out from the format pattern while the "hour in am/pm" + * pattern symbol is used. This information loss can happen when formatting the + * time in PM. + * + *

+ * When parsing a date string using the abbreviated year pattern ("y" or "yy"), + * SimpleDateFormat must interpret the abbreviated year + * relative to some century. It does this by adjusting dates to be + * within 80 years before and 20 years after the time the SimpleDateFormat + * instance is created. For example, using a pattern of "MM/dd/yy" and a + * SimpleDateFormat instance created on Jan 1, 1997, the string + * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" + * would be interpreted as May 4, 1964. + * During parsing, only strings consisting of exactly two digits, as defined by + * Unicode::isDigit(), will be parsed into the default century. + * Any other numeric string, such as a one digit string, a three or more digit + * string, or a two digit string that isn't all digits (for example, "-1"), is + * interpreted literally. So "01/02/3" or "01/02/003" are parsed (for the + * Gregorian calendar), using the same pattern, as Jan 2, 3 AD. Likewise (but + * only in lenient parse mode, the default) "01/02/-3" is parsed as Jan 2, 4 BC. + * + *

+ * If the year pattern has more than two 'y' characters, the year is + * interpreted literally, regardless of the number of digits. So using the + * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D. + * + *

+ * When numeric fields abut one another directly, with no intervening delimiter + * characters, they constitute a run of abutting numeric fields. Such runs are + * parsed specially. For example, the format "HHmmss" parses the input text + * "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to + * parse "1234". In other words, the leftmost field of the run is flexible, + * while the others keep a fixed width. If the parse fails anywhere in the run, + * then the leftmost field is shortened by one character, and the entire run is + * parsed again. This is repeated until either the parse succeeds or the + * leftmost field is one character in length. If the parse still fails at that + * point, the parse of the run fails. + * + *

+ * For time zones that have no names, SimpleDateFormat uses strings GMT+hours:minutes or + * GMT-hours:minutes. + *

+ * The calendar defines what is the first day of the week, the first week of the + * year, whether hours are zero based or not (0 vs 12 or 24), and the timezone. + * There is one common number format to handle all the numbers; the digit count + * is handled programmatically according to the pattern. + * + *

User subclasses are not supported. While clients may write + * subclasses, such code will not necessarily work and will not be + * guaranteed to work stably from release to release. + */ +class U_I18N_API SimpleDateFormat: public DateFormat { +public: + /** + * Construct a SimpleDateFormat using the default pattern for the default + * locale. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and the default locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern, numbering system override, and the default locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * A numbering system override is a string containing either the name of a known numbering system, + * or a set of field and numbering system pairs that specify which fields are to be formatted with + * the alternate numbering system. For example, to specify that all numeric fields in the specified + * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override + * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, + * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon + * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. + * + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param override the override string. + * @param status Output param set to success/failure code. + * @stable ICU 4.2 + */ + SimpleDateFormat(const UnicodeString& pattern, + const UnicodeString& override, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param locale the given locale. + * @param status Output param set to success/failure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + const Locale& locale, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern, numbering system override, and locale. + * The locale is used to obtain the symbols used in formatting (e.g., the + * names of the months), but not to provide the pattern. + *

+ * A numbering system override is a string containing either the name of a known numbering system, + * or a set of field and numbering system pairs that specify which fields are to be formatted with + * the alternate numbering system. For example, to specify that all numeric fields in the specified + * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override + * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, + * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon + * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. + *

+ * [Note:] Not all locales support SimpleDateFormat; for full generality, + * use the factory methods in the DateFormat class. + * @param pattern the pattern for the format. + * @param override the numbering system override. + * @param locale the given locale. + * @param status Output param set to success/failure code. + * @stable ICU 4.2 + */ + SimpleDateFormat(const UnicodeString& pattern, + const UnicodeString& override, + const Locale& locale, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale-specific + * symbol data. The formatter takes ownership of the DateFormatSymbols object; + * the caller is no longer responsible for deleting it. + * @param pattern the given pattern for the format. + * @param formatDataToAdopt the symbols to be adopted. + * @param status Output param set to success/faulure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + DateFormatSymbols* formatDataToAdopt, + UErrorCode& status); + + /** + * Construct a SimpleDateFormat using the given pattern and locale-specific + * symbol data. The DateFormatSymbols object is NOT adopted; the caller + * remains responsible for deleting it. + * @param pattern the given pattern for the format. + * @param formatData the formatting symbols to be use. + * @param status Output param set to success/faulure code. + * @stable ICU 2.0 + */ + SimpleDateFormat(const UnicodeString& pattern, + const DateFormatSymbols& formatData, + UErrorCode& status); + + /** + * Copy constructor. + * @stable ICU 2.0 + */ + SimpleDateFormat(const SimpleDateFormat&); + + /** + * Assignment operator. + * @stable ICU 2.0 + */ + SimpleDateFormat& operator=(const SimpleDateFormat&); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~SimpleDateFormat(); + + /** + * Clone this Format object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 2.0 + */ + virtual SimpleDateFormat* clone() const override; + + /** + * Return true if the given Format objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param other the object to be compared with. + * @return true if the given Format objects are semantically equal. + * @stable ICU 2.0 + */ + virtual bool operator==(const Format& other) const override; + + + using DateFormat::format; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param pos The formatting position. On input: an alignment field, + * if desired. On output: the offsets of the alignment field. + * @return Reference to 'appendTo' parameter. + * @stable ICU 2.1 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPosition& pos) const override; + + /** + * Format a date or time, which is the standard millis since 24:00 GMT, Jan + * 1, 1970. Overrides DateFormat pure virtual method. + *

+ * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> + * 1996.07.10 AD at 15:08:56 PDT + * + * @param cal Calendar set to the date and time to be formatted + * into a date/time string. + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param posIter On return, can be used to iterate over positions + * of fields generated by this format call. Field values + * are defined in UDateFormatField. + * @param status Input/output param set to success/failure code. + * @return Reference to 'appendTo' parameter. + * @stable ICU 4.4 + */ + virtual UnicodeString& format( Calendar& cal, + UnicodeString& appendTo, + FieldPositionIterator* posIter, + UErrorCode& status) const override; + + using DateFormat::parse; + + /** + * Parse a date/time string beginning at the given parse position. For + * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date + * that is equivalent to Date(837039928046). + *

+ * By default, parsing is lenient: If the input is not in the form used by + * this object's format method but can still be parsed as a date, then the + * parse succeeds. Clients may insist on strict adherence to the format by + * calling setLenient(false). + * @see DateFormat::setLenient(boolean) + * + * @param text The date/time string to be parsed + * @param cal A Calendar set on input to the date and time to be used for + * missing values in the date/time string being parsed, and set + * on output to the parsed date/time. When the calendar type is + * different from the internal calendar held by this SimpleDateFormat + * instance, the internal calendar will be cloned to a work + * calendar set to the same milliseconds and time zone as the + * cal parameter, field values will be parsed based on the work + * calendar, then the result (milliseconds and time zone) will + * be set in this calendar. + * @param pos On input, the position at which to start parsing; on + * output, the position at which parsing terminated, or the + * start position if the parse failed. + * @stable ICU 2.1 + */ + virtual void parse( const UnicodeString& text, + Calendar& cal, + ParsePosition& pos) const override; + + + /** + * Set the start UDate used to interpret two-digit year strings. + * When dates are parsed having 2-digit year strings, they are placed within + * a assumed range of 100 years starting on the two digit start date. For + * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or + * some other year. SimpleDateFormat chooses a year so that the resultant + * date is on or after the two digit start date and within 100 years of the + * two digit start date. + *

+ * By default, the two digit start date is set to 80 years before the current + * time at which a SimpleDateFormat object is created. + * @param d start UDate used to interpret two-digit year strings. + * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with + * an error value if there was a parse error. + * @stable ICU 2.0 + */ + virtual void set2DigitYearStart(UDate d, UErrorCode& status); + + /** + * Get the start UDate used to interpret two-digit year strings. + * When dates are parsed having 2-digit year strings, they are placed within + * a assumed range of 100 years starting on the two digit start date. For + * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or + * some other year. SimpleDateFormat chooses a year so that the resultant + * date is on or after the two digit start date and within 100 years of the + * two digit start date. + *

+ * By default, the two digit start date is set to 80 years before the current + * time at which a SimpleDateFormat object is created. + * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with + * an error value if there was a parse error. + * @stable ICU 2.0 + */ + UDate get2DigitYearStart(UErrorCode& status) const; + + /** + * Return a pattern string describing this date format. + * @param result Output param to receive the pattern. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + virtual UnicodeString& toPattern(UnicodeString& result) const; + + /** + * Return a localized pattern string describing this date format. + * In most cases, this will return the same thing as toPattern(), + * but a locale can specify characters to use in pattern descriptions + * in place of the ones described in this class's class documentation. + * (Presumably, letters that would be more mnemonic in that locale's + * language.) This function would produce a pattern using those + * letters. + *

+ * Note: This implementation depends on DateFormatSymbols::getLocalPatternChars() + * to get localized format pattern characters. ICU does not include + * localized pattern character data, therefore, unless user sets localized + * pattern characters manually, this method returns the same result as + * toPattern(). + * + * @param result Receives the localized pattern. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + virtual UnicodeString& toLocalizedPattern(UnicodeString& result, + UErrorCode& status) const; + + /** + * Apply the given unlocalized pattern string to this date format. + * (i.e., after this call, this formatter will format dates according to + * the new pattern) + * + * @param pattern The pattern to be applied. + * @stable ICU 2.0 + */ + virtual void applyPattern(const UnicodeString& pattern); + + /** + * Apply the given localized pattern string to this date format. + * (see toLocalizedPattern() for more information on localized patterns.) + * + * @param pattern The localized pattern to be applied. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ + virtual void applyLocalizedPattern(const UnicodeString& pattern, + UErrorCode& status); + + /** + * Gets the date/time formatting symbols (this is an object carrying + * the various strings and other symbols used in formatting: e.g., month + * names and abbreviations, time zone names, AM/PM strings, etc.) + * @return a copy of the date-time formatting data associated + * with this date-time formatter. + * @stable ICU 2.0 + */ + virtual const DateFormatSymbols* getDateFormatSymbols(void) const; + + /** + * Set the date/time formatting symbols. The caller no longer owns the + * DateFormatSymbols object and should not delete it after making this call. + * @param newFormatSymbols the given date-time formatting symbols to copy. + * @stable ICU 2.0 + */ + virtual void adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols); + + /** + * Set the date/time formatting data. + * @param newFormatSymbols the given date-time formatting symbols to copy. + * @stable ICU 2.0 + */ + virtual void setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols); + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Set the calendar to be used by this date format. Initially, the default + * calendar for the specified or default locale is used. The caller should + * not delete the Calendar object after it is adopted by this call. + * Adopting a new calendar will change to the default symbols. + * + * @param calendarToAdopt Calendar object to be adopted. + * @stable ICU 2.0 + */ + virtual void adoptCalendar(Calendar* calendarToAdopt) override; + + /* Cannot use #ifndef U_HIDE_INTERNAL_API for the following methods since they are virtual */ + /** + * Sets the TimeZoneFormat to be used by this date/time formatter. + * The caller should not delete the TimeZoneFormat object after + * it is adopted by this call. + * @param timeZoneFormatToAdopt The TimeZoneFormat object to be adopted. + * @internal ICU 49 technology preview + */ + virtual void adoptTimeZoneFormat(TimeZoneFormat* timeZoneFormatToAdopt); + + /** + * Sets the TimeZoneFormat to be used by this date/time formatter. + * @param newTimeZoneFormat The TimeZoneFormat object to copy. + * @internal ICU 49 technology preview + */ + virtual void setTimeZoneFormat(const TimeZoneFormat& newTimeZoneFormat); + + /** + * Gets the time zone format object associated with this date/time formatter. + * @return the time zone format associated with this date/time formatter. + * @internal ICU 49 technology preview + */ + virtual const TimeZoneFormat* getTimeZoneFormat(void) const; + + /** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. Note: For getContext, see + * DateFormat. + * @param value The UDisplayContext value to set. + * @param status Input/output status. If at entry this indicates a failure + * status, the function will do nothing; otherwise this will be + * updated with any new status from the function. + * @stable ICU 53 + */ + virtual void setContext(UDisplayContext value, UErrorCode& status) override; + + /** + * Overrides base class method and + * This method clears per field NumberFormat instances + * previously set by {@see adoptNumberFormat(const UnicodeString&, NumberFormat*, UErrorCode)} + * @param formatToAdopt the NumbeferFormat used + * @stable ICU 54 + */ + void adoptNumberFormat(NumberFormat *formatToAdopt) override; + + /** + * Allow the user to set the NumberFormat for several fields + * It can be a single field like: "y"(year) or "M"(month) + * It can be several field combined together: "yM"(year and month) + * Note: + * 1 symbol field is enough for multiple symbol field (so "y" will override "yy", "yyy") + * If the field is not numeric, then override has no effect (like "MMM" will use abbreviation, not numerical field) + * Per field NumberFormat can also be cleared in {@see DateFormat::setNumberFormat(const NumberFormat& newNumberFormat)} + * + * @param fields the fields to override(like y) + * @param formatToAdopt the NumbeferFormat used + * @param status Receives a status code, which will be U_ZERO_ERROR + * if the operation succeeds. + * @stable ICU 54 + */ + void adoptNumberFormat(const UnicodeString& fields, NumberFormat *formatToAdopt, UErrorCode &status); + + /** + * Get the numbering system to be used for a particular field. + * @param field The UDateFormatField to get + * @stable ICU 54 + */ + const NumberFormat * getNumberFormatForField(char16_t field) const; + +#ifndef U_HIDE_INTERNAL_API + /** + * This is for ICU internal use only. Please do not use. + * Check whether the 'field' is smaller than all the fields covered in + * pattern, return true if it is. The sequence of calendar field, + * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... + * @param field the calendar field need to check against + * @return true if the 'field' is smaller than all the fields + * covered in pattern. false otherwise. + * @internal ICU 4.0 + */ + UBool isFieldUnitIgnored(UCalendarDateFields field) const; + + + /** + * This is for ICU internal use only. Please do not use. + * Check whether the 'field' is smaller than all the fields covered in + * pattern, return true if it is. The sequence of calendar field, + * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... + * @param pattern the pattern to check against + * @param field the calendar field need to check against + * @return true if the 'field' is smaller than all the fields + * covered in pattern. false otherwise. + * @internal ICU 4.0 + */ + static UBool isFieldUnitIgnored(const UnicodeString& pattern, + UCalendarDateFields field); + + /** + * This is for ICU internal use only. Please do not use. + * Get the locale of this simple date formatter. + * It is used in DateIntervalFormat. + * + * @return locale in this simple date formatter + * @internal ICU 4.0 + */ + const Locale& getSmpFmtLocale(void) const; +#endif /* U_HIDE_INTERNAL_API */ + +private: + friend class DateFormat; + friend class DateIntervalFormat; + + void initializeDefaultCentury(void); + + void initializeBooleanAttributes(void); + + SimpleDateFormat() = delete; // default constructor not implemented + + /** + * Used by the DateFormat factory methods to construct a SimpleDateFormat. + * @param timeStyle the time style. + * @param dateStyle the date style. + * @param locale the given locale. + * @param status Output param set to success/failure code on + * exit. + */ + SimpleDateFormat(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); + + /** + * Construct a SimpleDateFormat for the given locale. If no resource data + * is available, create an object of last resort, using hard-coded strings. + * This is an internal method, called by DateFormat. It should never fail. + * @param locale the given locale. + * @param status Output param set to success/failure code on + * exit. + */ + SimpleDateFormat(const Locale& locale, UErrorCode& status); // Use default pattern + + /** + * Hook called by format(... FieldPosition& ...) and format(...FieldPositionIterator&...) + */ + UnicodeString& _format(Calendar& cal, UnicodeString& appendTo, FieldPositionHandler& handler, UErrorCode& status) const; + + /** + * Called by format() to format a single field. + * + * @param appendTo Output parameter to receive result. + * Result is appended to existing contents. + * @param ch The format character we encountered in the pattern. + * @param count Number of characters in the current pattern symbol (e.g., + * "yyyy" in the pattern would result in a call to this function + * with ch equal to 'y' and count equal to 4) + * @param capitalizationContext Capitalization context for this date format. + * @param fieldNum Zero-based numbering of current field within the overall format. + * @param handler Records information about field positions. + * @param cal Calendar to use + * @param status Receives a status code, which will be U_ZERO_ERROR if the operation + * succeeds. + */ + void subFormat(UnicodeString &appendTo, + char16_t ch, + int32_t count, + UDisplayContext capitalizationContext, + int32_t fieldNum, + char16_t fieldToOutput, + FieldPositionHandler& handler, + Calendar& cal, + UErrorCode& status) const; // in case of illegal argument + + /** + * Used by subFormat() to format a numeric value. + * Appends to toAppendTo a string representation of "value" + * having a number of digits between "minDigits" and + * "maxDigits". Uses the DateFormat's NumberFormat. + * + * @param currentNumberFormat + * @param appendTo Output parameter to receive result. + * Formatted number is appended to existing contents. + * @param value Value to format. + * @param minDigits Minimum number of digits the result should have + * @param maxDigits Maximum number of digits the result should have + */ + void zeroPaddingNumber(const NumberFormat *currentNumberFormat, + UnicodeString &appendTo, + int32_t value, + int32_t minDigits, + int32_t maxDigits) const; + + /** + * Return true if the given format character, occurring count + * times, represents a numeric field. + */ + static UBool isNumeric(char16_t formatChar, int32_t count); + + /** + * Returns true if the patternOffset is at the start of a numeric field. + */ + static UBool isAtNumericField(const UnicodeString &pattern, int32_t patternOffset); + + /** + * Returns true if the patternOffset is right after a non-numeric field. + */ + static UBool isAfterNonNumericField(const UnicodeString &pattern, int32_t patternOffset); + + /** + * initializes fCalendar from parameters. Returns fCalendar as a convenience. + * @param adoptZone Zone to be adopted, or nullptr for TimeZone::createDefault(). + * @param locale Locale of the calendar + * @param status Error code + * @return the newly constructed fCalendar + */ + Calendar *initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status); + + /** + * Called by several of the constructors to load pattern data and formatting symbols + * out of a resource bundle and initialize the locale based on it. + * @param timeStyle The time style, as passed to DateFormat::createDateInstance(). + * @param dateStyle The date style, as passed to DateFormat::createTimeInstance(). + * @param locale The locale to load the patterns from. + * @param status Filled in with an error code if loading the data from the + * resources fails. + */ + void construct(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); + + /** + * Called by construct() and the various constructors to set up the SimpleDateFormat's + * Calendar and NumberFormat objects. + * @param locale The locale for which we want a Calendar and a NumberFormat. + * @param status Filled in with an error code if creating either subobject fails. + */ + void initialize(const Locale& locale, UErrorCode& status); + + /** + * Private code-size reduction function used by subParse. + * @param text the time text being parsed. + * @param start where to start parsing. + * @param field the date field being parsed. + * @param stringArray the string array to parsed. + * @param stringArrayCount the size of the array. + * @param monthPattern pointer to leap month pattern, or nullptr if none. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t matchString(const UnicodeString& text, int32_t start, UCalendarDateFields field, + const UnicodeString* stringArray, int32_t stringArrayCount, + const UnicodeString* monthPattern, Calendar& cal) const; + + /** + * Private code-size reduction function used by subParse. Only for UCAL_MONTH + * @param text the time text being parsed. + * @param start where to start parsing. + * @param wideStringArray the wide string array to parsed. + * @param shortStringArray the short string array to parsed. + * @param stringArrayCount the size of the string arrays. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t matchAlphaMonthStrings(const UnicodeString& text, int32_t start, + const UnicodeString* wideStringArray, const UnicodeString* shortStringArray, + int32_t stringArrayCount, Calendar& cal) const; + + /** + * Private code-size reduction function used by subParse. + * @param text the time text being parsed. + * @param start where to start parsing. + * @param field the date field being parsed. + * @param stringArray the string array to parsed. + * @param stringArrayCount the size of the array. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t matchQuarterString(const UnicodeString& text, int32_t start, UCalendarDateFields field, + const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const; + + /** + * Used by subParse() to match localized day period strings. + */ + int32_t matchDayPeriodStrings(const UnicodeString& text, int32_t start, + const UnicodeString* stringArray, int32_t stringArrayCount, + int32_t &dayPeriod) const; + + /** + * Private function used by subParse to match literal pattern text. + * + * @param pattern the pattern string + * @param patternOffset the starting offset into the pattern text. On + * output will be set the offset of the first non-literal character in the pattern + * @param text the text being parsed + * @param textOffset the starting offset into the text. On output + * will be set to the offset of the character after the match + * @param whitespaceLenient true if whitespace parse is lenient, false otherwise. + * @param partialMatchLenient true if partial match parse is lenient, false otherwise. + * @param oldLeniency true if old leniency control is lenient, false otherwise. + * + * @return true if the literal text could be matched, false otherwise. + */ + static UBool matchLiterals(const UnicodeString &pattern, int32_t &patternOffset, + const UnicodeString &text, int32_t &textOffset, + UBool whitespaceLenient, UBool partialMatchLenient, UBool oldLeniency); + + /** + * Private member function that converts the parsed date strings into + * timeFields. Returns -start (for ParsePosition) if failed. + * @param text the time text to be parsed. + * @param start where to start parsing. + * @param ch the pattern character for the date field text to be parsed. + * @param count the count of a pattern character. + * @param obeyCount if true then the count is strictly obeyed. + * @param allowNegative + * @param ambiguousYear If true then the two-digit year == the default start year. + * @param saveHebrewMonth Used to hang onto month until year is known. + * @param cal a Calendar set to the date and time to be formatted + * into a date/time string. + * @param patLoc + * @param numericLeapMonthFormatter If non-null, used to parse numeric leap months. + * @param tzTimeType the type of parsed time zone - standard, daylight or unknown (output). + * This parameter can be nullptr if caller does not need the information. + * @return the new start position if matching succeeded; a negative number + * indicating matching failure, otherwise. + */ + int32_t subParse(const UnicodeString& text, int32_t& start, char16_t ch, int32_t count, + UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal, + int32_t patLoc, MessageFormat * numericLeapMonthFormatter, UTimeZoneFormatTimeType *tzTimeType, + int32_t *dayPeriod=nullptr) const; + + void parseInt(const UnicodeString& text, + Formattable& number, + ParsePosition& pos, + UBool allowNegative, + const NumberFormat *fmt) const; + + void parseInt(const UnicodeString& text, + Formattable& number, + int32_t maxDigits, + ParsePosition& pos, + UBool allowNegative, + const NumberFormat *fmt) const; + + int32_t checkIntSuffix(const UnicodeString& text, int32_t start, + int32_t patLoc, UBool isNegative) const; + + /** + * Counts number of digit code points in the specified text. + * + * @param text input text + * @param start start index, inclusive + * @param end end index, exclusive + * @return number of digits found in the text in the specified range. + */ + int32_t countDigits(const UnicodeString& text, int32_t start, int32_t end) const; + + /** + * Translate a pattern, mapping each character in the from string to the + * corresponding character in the to string. Return an error if the original + * pattern contains an unmapped character, or if a quote is unmatched. + * Quoted (single quotes only) material is not translated. + * @param originalPattern the original pattern. + * @param translatedPattern Output param to receive the translited pattern. + * @param from the characters to be translited from. + * @param to the characters to be translited to. + * @param status Receives a status code, which will be U_ZERO_ERROR + * if the operation succeeds. + */ + static void translatePattern(const UnicodeString& originalPattern, + UnicodeString& translatedPattern, + const UnicodeString& from, + const UnicodeString& to, + UErrorCode& status); + + /** + * Sets the starting date of the 100-year window that dates with 2-digit years + * are considered to fall within. + * @param startDate the start date + * @param status Receives a status code, which will be U_ZERO_ERROR + * if the operation succeeds. + */ + void parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status); + + /** + * Return the length matched by the given affix, or -1 if none. + * Runs of white space in the affix, match runs of white space in + * the input. + * @param affix pattern string, taken as a literal + * @param input input text + * @param pos offset into input at which to begin matching + * @return length of input that matches, or -1 if match failure + */ + int32_t compareSimpleAffix(const UnicodeString& affix, + const UnicodeString& input, + int32_t pos) const; + + /** + * Skip over a run of zero or more Pattern_White_Space characters at + * pos in text. + */ + int32_t skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const; + + /** + * Skip over a run of zero or more isUWhiteSpace() characters at pos + * in text. + */ + int32_t skipUWhiteSpace(const UnicodeString& text, int32_t pos) const; + + /** + * Initialize SimpleNumberFormat instance + */ + void initSimpleNumberFormatter(UErrorCode &status); + + /** + * Initialize NumberFormat instances used for numbering system overrides. + */ + void initNumberFormatters(const Locale &locale,UErrorCode &status); + + /** + * Parse the given override string and set up structures for number formats + */ + void processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status); + + /** + * Used to map pattern characters to Calendar field identifiers. + */ + static const UCalendarDateFields fgPatternIndexToCalendarField[]; + + /** + * Map index into pattern character string to DateFormat field number + */ + static const UDateFormatField fgPatternIndexToDateFormatField[]; + + /** + * Lazy TimeZoneFormat instantiation, semantically const + */ + TimeZoneFormat *tzFormat(UErrorCode &status) const; + + const NumberFormat* getNumberFormatByIndex(UDateFormatField index) const; + + /** + * Used to map Calendar field to field level. + * The larger the level, the smaller the field unit. + * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10, + * UCAL_MONTH level is 20. + */ + static const int32_t fgCalendarFieldToLevel[]; + + /** + * Map calendar field letter into calendar field level. + */ + static int32_t getLevelFromChar(char16_t ch); + + /** + * Tell if a character can be used to define a field in a format string. + */ + static UBool isSyntaxChar(char16_t ch); + + /** + * The formatting pattern for this formatter. + */ + UnicodeString fPattern; + + /** + * The numbering system override for dates. + */ + UnicodeString fDateOverride; + + /** + * The numbering system override for times. + */ + UnicodeString fTimeOverride; + + + /** + * The original locale used (for reloading symbols) + */ + Locale fLocale; + + /** + * A pointer to an object containing the strings to use in formatting (e.g., + * month and day names, AM and PM strings, time zone names, etc.) + */ + DateFormatSymbols* fSymbols = nullptr; // Owned + + /** + * The time zone formatter + */ + TimeZoneFormat* fTimeZoneFormat = nullptr; + + /** + * If dates have ambiguous years, we map them into the century starting + * at defaultCenturyStart, which may be any date. If defaultCenturyStart is + * set to SYSTEM_DEFAULT_CENTURY, which it is by default, then the system + * values are used. The instance values defaultCenturyStart and + * defaultCenturyStartYear are only used if explicitly set by the user + * through the API method parseAmbiguousDatesAsAfter(). + */ + UDate fDefaultCenturyStart; + + UBool fHasMinute; + UBool fHasSecond; + UBool fHasHanYearChar; // pattern contains the Han year character \u5E74 + + /** + * Sets fHasMinutes and fHasSeconds. + */ + void parsePattern(); + + /** + * See documentation for defaultCenturyStart. + */ + /*transient*/ int32_t fDefaultCenturyStartYear; + + struct NSOverride : public UMemory { + const SharedNumberFormat *snf; + int32_t hash; + NSOverride *next; + void free(); + NSOverride() : snf(nullptr), hash(0), next(nullptr) { + } + ~NSOverride(); + }; + + /** + * The number format in use for each date field. nullptr means fall back + * to fNumberFormat in DateFormat. + */ + const SharedNumberFormat **fSharedNumberFormatters = nullptr; + + /** + * Number formatter pre-allocated for fast performance + * + * This references the decimal symbols from fNumberFormatter if it is an instance + * of DecimalFormat (and is otherwise null). This should always be cleaned up before + * destroying fNumberFormatter. + */ + const number::SimpleNumberFormatter* fSimpleNumberFormatter = nullptr; + + UBool fHaveDefaultCentury; + + const BreakIterator* fCapitalizationBrkIter = nullptr; +}; + +inline UDate +SimpleDateFormat::get2DigitYearStart(UErrorCode& /*status*/) const +{ + return fDefaultCenturyStart; +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // _SMPDTFMT +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/sortkey.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/sortkey.h new file mode 100644 index 0000000000000000000000000000000000000000..401b5abad0a14c8c55869e064d46d7812f087a9b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/sortkey.h @@ -0,0 +1,344 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ***************************************************************************** + * Copyright (C) 1996-2014, International Business Machines Corporation and others. + * All Rights Reserved. + ***************************************************************************** + * + * File sortkey.h + * + * Created by: Helena Shih + * + * Modification History: + * + * Date Name Description + * + * 6/20/97 helena Java class name change. + * 8/18/97 helena Added internal API documentation. + * 6/26/98 erm Changed to use byte arrays and memcmp. + ***************************************************************************** + */ + +#ifndef SORTKEY_H +#define SORTKEY_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Keys for comparing strings multiple times. + */ + +#if !UCONFIG_NO_COLLATION + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/coll.h" + +U_NAMESPACE_BEGIN + +/* forward declaration */ +class RuleBasedCollator; +class CollationKeyByteSink; + +/** + * + * Collation keys are generated by the Collator class. Use the CollationKey objects + * instead of Collator to compare strings multiple times. A CollationKey + * preprocesses the comparison information from the Collator object to + * make the comparison faster. If you are not going to comparing strings + * multiple times, then using the Collator object is generally faster, + * since it only processes as much of the string as needed to make a + * comparison. + *

For example (with strength == tertiary) + *

When comparing "Abernathy" to "Baggins-Smythworthy", Collator + * only needs to process a couple of characters, while a comparison + * with CollationKeys will process all of the characters. On the other hand, + * if you are doing a sort of a number of fields, it is much faster to use + * CollationKeys, since you will be comparing strings multiple times. + *

Typical use of CollationKeys are in databases, where you store a CollationKey + * in a hidden field, and use it for sorting or indexing. + * + *

Example of use: + *

+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     Collator* myCollator = Collator::createInstance(success);
+ *     CollationKey* keys = new CollationKey [3];
+ *     myCollator->getCollationKey("Tom", keys[0], success );
+ *     myCollator->getCollationKey("Dick", keys[1], success );
+ *     myCollator->getCollationKey("Harry", keys[2], success );
+ *
+ *     // Inside body of sort routine, compare keys this way:
+ *     CollationKey tmp;
+ *     if(keys[0].compareTo( keys[1] ) > 0 ) {
+ *         tmp = keys[0]; keys[0] = keys[1]; keys[1] = tmp;
+ *     }
+ *     //...
+ * \endcode
+ * 
+ *

Because Collator::compare()'s algorithm is complex, it is faster to sort + * long lists of words by retrieving collation keys with Collator::getCollationKey(). + * You can then cache the collation keys and compare them using CollationKey::compareTo(). + *

+ * Note: Collators with different Locale, + * CollationStrength and DecompositionMode settings will return different + * CollationKeys for the same set of strings. Locales have specific + * collation rules, and the way in which secondary and tertiary differences + * are taken into account, for example, will result in different CollationKeys + * for same strings. + *

+ + * @see Collator + * @see RuleBasedCollator + * @version 1.3 12/18/96 + * @author Helena Shih + * @stable ICU 2.0 + */ +class U_I18N_API CollationKey : public UObject { +public: + /** + * This creates an empty collation key based on the null string. An empty + * collation key contains no sorting information. When comparing two empty + * collation keys, the result is Collator::EQUAL. Comparing empty collation key + * with non-empty collation key is always Collator::LESS. + * @stable ICU 2.0 + */ + CollationKey(); + + + /** + * Creates a collation key based on the collation key values. + * @param values the collation key values + * @param count number of collation key values, including trailing nulls. + * @stable ICU 2.0 + */ + CollationKey(const uint8_t* values, + int32_t count); + + /** + * Copy constructor. + * @param other the object to be copied. + * @stable ICU 2.0 + */ + CollationKey(const CollationKey& other); + + /** + * Sort key destructor. + * @stable ICU 2.0 + */ + virtual ~CollationKey(); + + /** + * Assignment operator + * @param other the object to be copied. + * @stable ICU 2.0 + */ + const CollationKey& operator=(const CollationKey& other); + + /** + * Compare if two collation keys are the same. + * @param source the collation key to compare to. + * @return Returns true if two collation keys are equal, false otherwise. + * @stable ICU 2.0 + */ + bool operator==(const CollationKey& source) const; + + /** + * Compare if two collation keys are not the same. + * @param source the collation key to compare to. + * @return Returns true if two collation keys are different, false otherwise. + * @stable ICU 2.0 + */ + bool operator!=(const CollationKey& source) const; + + + /** + * Test to see if the key is in an invalid state. The key will be in an + * invalid state if it couldn't allocate memory for some operation. + * @return Returns true if the key is in an invalid, false otherwise. + * @stable ICU 2.0 + */ + UBool isBogus(void) const; + + /** + * Returns a pointer to the collation key values. The storage is owned + * by the collation key and the pointer will become invalid if the key + * is deleted. + * @param count the output parameter of number of collation key values, + * including any trailing nulls. + * @return a pointer to the collation key values. + * @stable ICU 2.0 + */ + const uint8_t* getByteArray(int32_t& count) const; + +#ifdef U_USE_COLLATION_KEY_DEPRECATES + /** + * Extracts the collation key values into a new array. The caller owns + * this storage and should free it. + * @param count the output parameter of number of collation key values, + * including any trailing nulls. + * @obsolete ICU 2.6. Use getByteArray instead since this API will be removed in that release. + */ + uint8_t* toByteArray(int32_t& count) const; +#endif + +#ifndef U_HIDE_DEPRECATED_API + /** + * Convenience method which does a string(bit-wise) comparison of the + * two collation keys. + * @param target target collation key to be compared with + * @return Returns Collator::LESS if sourceKey < targetKey, + * Collator::GREATER if sourceKey > targetKey and Collator::EQUAL + * otherwise. + * @deprecated ICU 2.6 use the overload with error code + */ + Collator::EComparisonResult compareTo(const CollationKey& target) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Convenience method which does a string(bit-wise) comparison of the + * two collation keys. + * @param target target collation key to be compared with + * @param status error code + * @return Returns UCOL_LESS if sourceKey < targetKey, + * UCOL_GREATER if sourceKey > targetKey and UCOL_EQUAL + * otherwise. + * @stable ICU 2.6 + */ + UCollationResult compareTo(const CollationKey& target, UErrorCode &status) const; + + /** + * Creates an integer that is unique to the collation key. NOTE: this + * is not the same as String.hashCode. + *

Example of use: + *

+    * .    UErrorCode status = U_ZERO_ERROR;
+    * .    Collator *myCollation = Collator::createInstance(Locale::US, status);
+    * .    if (U_FAILURE(status)) return;
+    * .    CollationKey key1, key2;
+    * .    UErrorCode status1 = U_ZERO_ERROR, status2 = U_ZERO_ERROR;
+    * .    myCollation->getCollationKey("abc", key1, status1);
+    * .    if (U_FAILURE(status1)) { delete myCollation; return; }
+    * .    myCollation->getCollationKey("ABC", key2, status2);
+    * .    if (U_FAILURE(status2)) { delete myCollation; return; }
+    * .    // key1.hashCode() != key2.hashCode()
+    * 
+ * @return the hash value based on the string's collation order. + * @see UnicodeString#hashCode + * @stable ICU 2.0 + */ + int32_t hashCode(void) const; + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +private: + /** + * Replaces the current bytes buffer with a new one of newCapacity + * and copies length bytes from the old buffer to the new one. + * @return the new buffer, or nullptr if the allocation failed + */ + uint8_t *reallocate(int32_t newCapacity, int32_t length); + /** + * Set a new length for a new sort key in the existing fBytes. + */ + void setLength(int32_t newLength); + + uint8_t *getBytes() { + return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes; + } + const uint8_t *getBytes() const { + return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes; + } + int32_t getCapacity() const { + return (fFlagAndLength >= 0) ? (int32_t)sizeof(fUnion) : fUnion.fFields.fCapacity; + } + int32_t getLength() const { return fFlagAndLength & 0x7fffffff; } + + /** + * Set the CollationKey to a "bogus" or invalid state + * @return this CollationKey + */ + CollationKey& setToBogus(void); + /** + * Resets this CollationKey to an empty state + * @return this CollationKey + */ + CollationKey& reset(void); + + /** + * Allow private access to RuleBasedCollator + */ + friend class RuleBasedCollator; + friend class CollationKeyByteSink; + + // Class fields. sizeof(CollationKey) is intended to be 48 bytes + // on a machine with 64-bit pointers. + // We use a union to maximize the size of the internal buffer, + // similar to UnicodeString but not as tight and complex. + + // (implicit) *vtable; + /** + * Sort key length and flag. + * Bit 31 is set if the buffer is heap-allocated. + * Bits 30..0 contain the sort key length. + */ + int32_t fFlagAndLength; + /** + * Unique hash value of this CollationKey. + * Special value 2 if the key is bogus. + */ + mutable int32_t fHashCode; + /** + * fUnion provides 32 bytes for the internal buffer or for + * pointer+capacity. + */ + union StackBufferOrFields { + /** fStackBuffer is used iff fFlagAndLength>=0, else fFields is used */ + uint8_t fStackBuffer[32]; + struct { + uint8_t *fBytes; + int32_t fCapacity; + } fFields; + } fUnion; +}; + +inline bool +CollationKey::operator!=(const CollationKey& other) const +{ + return !(*this == other); +} + +inline UBool +CollationKey::isBogus() const +{ + return fHashCode == 2; // kBogusHashCode +} + +inline const uint8_t* +CollationKey::getByteArray(int32_t &count) const +{ + count = getLength(); + return getBytes(); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/std_string.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/std_string.h new file mode 100644 index 0000000000000000000000000000000000000000..bf87230167ecf25ce98aef43a05302c165497c67 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/std_string.h @@ -0,0 +1,41 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2009-2014, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: std_string.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2009feb19 +* created by: Markus W. Scherer +*/ + +#ifndef __STD_STRING_H__ +#define __STD_STRING_H__ + +/** + * \file + * \brief C++ API: Central ICU header for including the C++ standard <string> + * header and for related definitions. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +// Workaround for a libstdc++ bug before libstdc++4.6 (2011). +// https://bugs.llvm.org/show_bug.cgi?id=13364 +#if defined(__GLIBCXX__) +namespace std { class type_info; } +#endif +#include + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __STD_STRING_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/strenum.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/strenum.h new file mode 100644 index 0000000000000000000000000000000000000000..fba5c9b8147ebc56cb003c2755df3f5f57c3e655 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/strenum.h @@ -0,0 +1,281 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2002-2012, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +*/ + +#ifndef STRENUM_H +#define STRENUM_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" +#include "unicode/unistr.h" + +/** + * \file + * \brief C++ API: String Enumeration + */ + +U_NAMESPACE_BEGIN + +/** + * Base class for 'pure' C++ implementations of uenum api. Adds a + * method that returns the next UnicodeString since in C++ this can + * be a common storage format for strings. + * + *

The model is that the enumeration is over strings maintained by + * a 'service.' At any point, the service might change, invalidating + * the enumerator (though this is expected to be rare). The iterator + * returns an error if this has occurred. Lack of the error is no + * guarantee that the service didn't change immediately after the + * call, so the returned string still might not be 'valid' on + * subsequent use.

+ * + *

Strings may take the form of const char*, const char16_t*, or const + * UnicodeString*. The type you get is determine by the variant of + * 'next' that you call. In general the StringEnumeration is + * optimized for one of these types, but all StringEnumerations can + * return all types. Returned strings are each terminated with a NUL. + * Depending on the service data, they might also include embedded NUL + * characters, so API is provided to optionally return the true + * length, counting the embedded NULs but not counting the terminating + * NUL.

+ * + *

The pointers returned by next, unext, and snext become invalid + * upon any subsequent call to the enumeration's destructor, next, + * unext, snext, or reset.

+ * + * ICU 2.8 adds some default implementations and helper functions + * for subclasses. + * + * @stable ICU 2.4 + */ +class U_COMMON_API StringEnumeration : public UObject { +public: + /** + * Destructor. + * @stable ICU 2.4 + */ + virtual ~StringEnumeration(); + + /** + * Clone this object, an instance of a subclass of StringEnumeration. + * Clones can be used concurrently in multiple threads. + * If a subclass does not implement clone(), or if an error occurs, + * then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + virtual StringEnumeration *clone() const; + + /** + *

Return the number of elements that the iterator traverses. If + * the iterator is out of sync with its service, status is set to + * U_ENUM_OUT_OF_SYNC_ERROR, and the return value is zero.

+ * + *

The return value will not change except possibly as a result of + * a subsequent call to reset, or if the iterator becomes out of sync.

+ * + *

This is a convenience function. It can end up being very + * expensive as all the items might have to be pre-fetched + * (depending on the storage format of the data being + * traversed).

+ * + * @param status the error code. + * @return number of elements in the iterator. + * + * @stable ICU 2.4 */ + virtual int32_t count(UErrorCode& status) const = 0; + + /** + *

Returns the next element as a NUL-terminated char*. If there + * are no more elements, returns nullptr. If the resultLength pointer + * is not nullptr, the length of the string (not counting the + * terminating NUL) is returned at that address. If an error + * status is returned, the value at resultLength is undefined.

+ * + *

The returned pointer is owned by this iterator and must not be + * deleted by the caller. The pointer is valid until the next call + * to next, unext, snext, reset, or the enumerator's destructor.

+ * + *

If the iterator is out of sync with its service, status is set + * to U_ENUM_OUT_OF_SYNC_ERROR and nullptr is returned.

+ * + *

If the native service string is a char16_t* string, it is + * converted to char* with the invariant converter. If the + * conversion fails (because a character cannot be converted) then + * status is set to U_INVARIANT_CONVERSION_ERROR and the return + * value is undefined (though not nullptr).

+ * + * Starting with ICU 2.8, the default implementation calls snext() + * and handles the conversion. + * Either next() or snext() must be implemented differently by a subclass. + * + * @param status the error code. + * @param resultLength a pointer to receive the length, can be nullptr. + * @return a pointer to the string, or nullptr. + * + * @stable ICU 2.4 + */ + virtual const char* next(int32_t *resultLength, UErrorCode& status); + + /** + *

Returns the next element as a NUL-terminated char16_t*. If there + * are no more elements, returns nullptr. If the resultLength pointer + * is not nullptr, the length of the string (not counting the + * terminating NUL) is returned at that address. If an error + * status is returned, the value at resultLength is undefined.

+ * + *

The returned pointer is owned by this iterator and must not be + * deleted by the caller. The pointer is valid until the next call + * to next, unext, snext, reset, or the enumerator's destructor.

+ * + *

If the iterator is out of sync with its service, status is set + * to U_ENUM_OUT_OF_SYNC_ERROR and nullptr is returned.

+ * + * Starting with ICU 2.8, the default implementation calls snext() + * and handles the conversion. + * + * @param status the error code. + * @param resultLength a pointer to receive the length, can be nullptr. + * @return a pointer to the string, or nullptr. + * + * @stable ICU 2.4 + */ + virtual const char16_t* unext(int32_t *resultLength, UErrorCode& status); + + /** + *

Returns the next element a UnicodeString*. If there are no + * more elements, returns nullptr.

+ * + *

The returned pointer is owned by this iterator and must not be + * deleted by the caller. The pointer is valid until the next call + * to next, unext, snext, reset, or the enumerator's destructor.

+ * + *

If the iterator is out of sync with its service, status is set + * to U_ENUM_OUT_OF_SYNC_ERROR and nullptr is returned.

+ * + * Starting with ICU 2.8, the default implementation calls next() + * and handles the conversion. + * Either next() or snext() must be implemented differently by a subclass. + * + * @param status the error code. + * @return a pointer to the string, or nullptr. + * + * @stable ICU 2.4 + */ + virtual const UnicodeString* snext(UErrorCode& status); + + /** + *

Resets the iterator. This re-establishes sync with the + * service and rewinds the iterator to start at the first + * element.

+ * + *

Previous pointers returned by next, unext, or snext become + * invalid, and the value returned by count might change.

+ * + * @param status the error code. + * + * @stable ICU 2.4 + */ + virtual void reset(UErrorCode& status) = 0; + + /** + * Compares this enumeration to other to check if both are equal + * + * @param that The other string enumeration to compare this object to + * @return true if the enumerations are equal. false if not. + * @stable ICU 3.6 + */ + virtual bool operator==(const StringEnumeration& that)const; + /** + * Compares this enumeration to other to check if both are not equal + * + * @param that The other string enumeration to compare this object to + * @return true if the enumerations are equal. false if not. + * @stable ICU 3.6 + */ + virtual bool operator!=(const StringEnumeration& that)const; + +protected: + /** + * UnicodeString field for use with default implementations and subclasses. + * @stable ICU 2.8 + */ + UnicodeString unistr; + /** + * char * default buffer for use with default implementations and subclasses. + * @stable ICU 2.8 + */ + char charsBuffer[32]; + /** + * char * buffer for use with default implementations and subclasses. + * Allocated in constructor and in ensureCharsCapacity(). + * @stable ICU 2.8 + */ + char *chars; + /** + * Capacity of chars, for use with default implementations and subclasses. + * @stable ICU 2.8 + */ + int32_t charsCapacity; + + /** + * Default constructor for use with default implementations and subclasses. + * @stable ICU 2.8 + */ + StringEnumeration(); + + /** + * Ensures that chars is at least as large as the requested capacity. + * For use with default implementations and subclasses. + * + * @param capacity Requested capacity. + * @param status ICU in/out error code. + * @stable ICU 2.8 + */ + void ensureCharsCapacity(int32_t capacity, UErrorCode &status); + + /** + * Converts s to Unicode and sets unistr to the result. + * For use with default implementations and subclasses, + * especially for implementations of snext() in terms of next(). + * This is provided with a helper function instead of a default implementation + * of snext() to avoid potential infinite loops between next() and snext(). + * + * For example: + * \code + * const UnicodeString* snext(UErrorCode& status) { + * int32_t resultLength=0; + * const char *s=next(&resultLength, status); + * return setChars(s, resultLength, status); + * } + * \endcode + * + * @param s String to be converted to Unicode. + * @param length Length of the string. + * @param status ICU in/out error code. + * @return A pointer to unistr. + * @stable ICU 2.8 + */ + UnicodeString *setChars(const char *s, int32_t length, UErrorCode &status); +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +/* STRENUM_H */ +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringoptions.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringoptions.h new file mode 100644 index 0000000000000000000000000000000000000000..7b9f70944f62db69997057f5f67912566cdde220 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringoptions.h @@ -0,0 +1,190 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// stringoptions.h +// created: 2017jun08 Markus W. Scherer + +#ifndef __STRINGOPTIONS_H__ +#define __STRINGOPTIONS_H__ + +#include "unicode/utypes.h" + +/** + * \file + * \brief C API: Bit set option bit constants for various string and character processing functions. + */ + +/** + * Option value for case folding: Use default mappings defined in CaseFolding.txt. + * + * @stable ICU 2.0 + */ +#define U_FOLD_CASE_DEFAULT 0 + +/** + * Option value for case folding: + * + * Use the modified set of mappings provided in CaseFolding.txt to handle dotted I + * and dotless i appropriately for Turkic languages (tr, az). + * + * Before Unicode 3.2, CaseFolding.txt contains mappings marked with 'I' that + * are to be included for default mappings and + * excluded for the Turkic-specific mappings. + * + * Unicode 3.2 CaseFolding.txt instead contains mappings marked with 'T' that + * are to be excluded for default mappings and + * included for the Turkic-specific mappings. + * + * @stable ICU 2.0 + */ +#define U_FOLD_CASE_EXCLUDE_SPECIAL_I 1 + +/** + * Titlecase the string as a whole rather than each word. + * (Titlecase only the character at index 0, possibly adjusted.) + * Option bits value for titlecasing APIs that take an options bit set. + * + * It is an error to specify multiple titlecasing iterator options together, + * including both an options bit and an explicit BreakIterator. + * + * @see U_TITLECASE_ADJUST_TO_CASED + * @stable ICU 60 + */ +#define U_TITLECASE_WHOLE_STRING 0x20 + +/** + * Titlecase sentences rather than words. + * (Titlecase only the first character of each sentence, possibly adjusted.) + * Option bits value for titlecasing APIs that take an options bit set. + * + * It is an error to specify multiple titlecasing iterator options together, + * including both an options bit and an explicit BreakIterator. + * + * @see U_TITLECASE_ADJUST_TO_CASED + * @stable ICU 60 + */ +#define U_TITLECASE_SENTENCES 0x40 + +/** + * Do not lowercase non-initial parts of words when titlecasing. + * Option bit for titlecasing APIs that take an options bit set. + * + * By default, titlecasing will titlecase the character at each + * (possibly adjusted) BreakIterator index and + * lowercase all other characters up to the next iterator index. + * With this option, the other characters will not be modified. + * + * @see U_TITLECASE_ADJUST_TO_CASED + * @see UnicodeString::toTitle + * @see CaseMap::toTitle + * @see ucasemap_setOptions + * @see ucasemap_toTitle + * @see ucasemap_utf8ToTitle + * @stable ICU 3.8 + */ +#define U_TITLECASE_NO_LOWERCASE 0x100 + +/** + * Do not adjust the titlecasing BreakIterator indexes; + * titlecase exactly the characters at breaks from the iterator. + * Option bit for titlecasing APIs that take an options bit set. + * + * By default, titlecasing will take each break iterator index, + * adjust it to the next relevant character (see U_TITLECASE_ADJUST_TO_CASED), + * and titlecase that one. + * + * Other characters are lowercased. + * + * It is an error to specify multiple titlecasing adjustment options together. + * + * @see U_TITLECASE_ADJUST_TO_CASED + * @see U_TITLECASE_NO_LOWERCASE + * @see UnicodeString::toTitle + * @see CaseMap::toTitle + * @see ucasemap_setOptions + * @see ucasemap_toTitle + * @see ucasemap_utf8ToTitle + * @stable ICU 3.8 + */ +#define U_TITLECASE_NO_BREAK_ADJUSTMENT 0x200 + +/** + * Adjust each titlecasing BreakIterator index to the next cased character. + * (See the Unicode Standard, chapter 3, Default Case Conversion, R3 toTitlecase(X).) + * Option bit for titlecasing APIs that take an options bit set. + * + * This used to be the default index adjustment in ICU. + * Since ICU 60, the default index adjustment is to the next character that is + * a letter, number, symbol, or private use code point. + * (Uncased modifier letters are skipped.) + * The difference in behavior is small for word titlecasing, + * but the new adjustment is much better for whole-string and sentence titlecasing: + * It yields "49ers" and "«丰(abc)»" instead of "49Ers" and "«丰(Abc)»". + * + * It is an error to specify multiple titlecasing adjustment options together. + * + * @see U_TITLECASE_NO_BREAK_ADJUSTMENT + * @stable ICU 60 + */ +#define U_TITLECASE_ADJUST_TO_CASED 0x400 + +/** + * Option for string transformation functions to not first reset the Edits object. + * Used for example in some case-mapping and normalization functions. + * + * @see CaseMap + * @see Edits + * @see Normalizer2 + * @stable ICU 60 + */ +#define U_EDITS_NO_RESET 0x2000 + +/** + * Omit unchanged text when recording how source substrings + * relate to changed and unchanged result substrings. + * Used for example in some case-mapping and normalization functions. + * + * @see CaseMap + * @see Edits + * @see Normalizer2 + * @stable ICU 60 + */ +#define U_OMIT_UNCHANGED_TEXT 0x4000 + +/** + * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc: + * Compare strings in code point order instead of code unit order. + * @stable ICU 2.2 + */ +#define U_COMPARE_CODE_POINT_ORDER 0x8000 + +/** + * Option bit for unorm_compare: + * Perform case-insensitive comparison. + * @stable ICU 2.2 + */ +#define U_COMPARE_IGNORE_CASE 0x10000 + +/** + * Option bit for unorm_compare: + * Both input strings are assumed to fulfill FCD conditions. + * @stable ICU 2.2 + */ +#define UNORM_INPUT_IS_FCD 0x20000 + +// Related definitions elsewhere. +// Options that are not meaningful in the same functions +// can share the same bits. +// +// Public: +// unicode/unorm.h #define UNORM_COMPARE_NORM_OPTIONS_SHIFT 20 +// +// Internal: (may change or be removed) +// ucase.h #define _STRCASECMP_OPTIONS_MASK 0xffff +// ucase.h #define _FOLD_CASE_OPTIONS_MASK 7 +// ucasemap_imp.h #define U_TITLECASE_ITERATOR_MASK 0xe0 +// ucasemap_imp.h #define U_TITLECASE_ADJUSTMENT_MASK 0x600 +// ustr_imp.h #define _STRNCMP_STYLE 0x1000 +// unormcmp.cpp #define _COMPARE_EQUIV 0x80000 + +#endif // __STRINGOPTIONS_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringpiece.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringpiece.h new file mode 100644 index 0000000000000000000000000000000000000000..df7f36089dd7c53328292f0a8c0ef5566cc1e7d7 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringpiece.h @@ -0,0 +1,343 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +// Copyright (C) 2009-2013, International Business Machines +// Corporation and others. All Rights Reserved. +// +// Copyright 2001 and onwards Google Inc. +// Author: Sanjay Ghemawat + +// This code is a contribution of Google code, and the style used here is +// a compromise between the original Google code and the ICU coding guidelines. +// For example, data types are ICU-ified (size_t,int->int32_t), +// and API comments doxygen-ified, but function names and behavior are +// as in the original, if possible. +// Assertion-style error handling, not available in ICU, was changed to +// parameter "pinning" similar to UnicodeString. +// +// In addition, this is only a partial port of the original Google code, +// limited to what was needed so far. The (nearly) complete original code +// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib +// (see ICU ticket 6765, r25517). + +#ifndef __STRINGPIECE_H__ +#define __STRINGPIECE_H__ + +/** + * \file + * \brief C++ API: StringPiece: Read-only byte string wrapper class. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include +#include + +#include "unicode/uobject.h" +#include "unicode/std_string.h" + +// Arghh! I wish C++ literals were "string". + +U_NAMESPACE_BEGIN + +/** + * A string-like object that points to a sized piece of memory. + * + * We provide non-explicit singleton constructors so users can pass + * in a "const char*" or a "string" wherever a "StringPiece" is + * expected. + * + * Functions or methods may use StringPiece parameters to accept either a + * "const char*" or a "string" value that will be implicitly converted to a + * StringPiece. + * + * Systematic usage of StringPiece is encouraged as it will reduce unnecessary + * conversions from "const char*" to "string" and back again. + * + * @stable ICU 4.2 + */ +class U_COMMON_API StringPiece : public UMemory { + private: + const char* ptr_; + int32_t length_; + + public: + /** + * Default constructor, creates an empty StringPiece. + * @stable ICU 4.2 + */ + StringPiece() : ptr_(nullptr), length_(0) { } + + /** + * Constructs from a NUL-terminated const char * pointer. + * @param str a NUL-terminated const char * pointer + * @stable ICU 4.2 + */ + StringPiece(const char* str); +#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN) + /** + * Constructs from a NUL-terminated const char8_t * pointer. + * @param str a NUL-terminated const char8_t * pointer + * @stable ICU 67 + */ + StringPiece(const char8_t* str) : StringPiece(reinterpret_cast(str)) {} +#endif + /** + * Constructs an empty StringPiece. + * Needed for type disambiguation from multiple other overloads. + * @param p nullptr + * @stable ICU 67 + */ + StringPiece(std::nullptr_t p) : ptr_(p), length_(0) {} + + /** + * Constructs from a std::string. + * @stable ICU 4.2 + */ + StringPiece(const std::string& str) + : ptr_(str.data()), length_(static_cast(str.size())) { } +#if defined(__cpp_lib_char8_t) || defined(U_IN_DOXYGEN) + /** + * Constructs from a std::u8string. + * @stable ICU 67 + */ + StringPiece(const std::u8string& str) + : ptr_(reinterpret_cast(str.data())), + length_(static_cast(str.size())) { } +#endif + + /** + * Constructs from some other implementation of a string piece class, from any + * C++ record type that has these two methods: + * + * \code{.cpp} + * + * struct OtherStringPieceClass { + * const char* data(); // or const char8_t* + * size_t size(); + * }; + * + * \endcode + * + * The other string piece class will typically be std::string_view from C++17 + * or absl::string_view from Abseil. + * + * Starting with C++20, data() may also return a const char8_t* pointer, + * as from std::u8string_view. + * + * @param str the other string piece + * @stable ICU 65 + */ + template ::value +#if defined(__cpp_char8_t) + || std::is_same::value +#endif + ) && + std::is_same::value>::type> + StringPiece(T str) + : ptr_(reinterpret_cast(str.data())), + length_(static_cast(str.size())) {} + + /** + * Constructs from a const char * pointer and a specified length. + * @param offset a const char * pointer (need not be terminated) + * @param len the length of the string; must be non-negative + * @stable ICU 4.2 + */ + StringPiece(const char* offset, int32_t len) : ptr_(offset), length_(len) { } +#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN) + /** + * Constructs from a const char8_t * pointer and a specified length. + * @param str a const char8_t * pointer (need not be terminated) + * @param len the length of the string; must be non-negative + * @stable ICU 67 + */ + StringPiece(const char8_t* str, int32_t len) : + StringPiece(reinterpret_cast(str), len) {} +#endif + + /** + * Substring of another StringPiece. + * @param x the other StringPiece + * @param pos start position in x; must be non-negative and <= x.length(). + * @stable ICU 4.2 + */ + StringPiece(const StringPiece& x, int32_t pos); + /** + * Substring of another StringPiece. + * @param x the other StringPiece + * @param pos start position in x; must be non-negative and <= x.length(). + * @param len length of the substring; + * must be non-negative and will be pinned to at most x.length() - pos. + * @stable ICU 4.2 + */ + StringPiece(const StringPiece& x, int32_t pos, int32_t len); + + /** + * Returns the string pointer. May be nullptr if it is empty. + * + * data() may return a pointer to a buffer with embedded NULs, and the + * returned buffer may or may not be null terminated. Therefore it is + * typically a mistake to pass data() to a routine that expects a NUL + * terminated string. + * @return the string pointer + * @stable ICU 4.2 + */ + const char* data() const { return ptr_; } + /** + * Returns the string length. Same as length(). + * @return the string length + * @stable ICU 4.2 + */ + int32_t size() const { return length_; } + /** + * Returns the string length. Same as size(). + * @return the string length + * @stable ICU 4.2 + */ + int32_t length() const { return length_; } + /** + * Returns whether the string is empty. + * @return true if the string is empty + * @stable ICU 4.2 + */ + UBool empty() const { return length_ == 0; } + + /** + * Sets to an empty string. + * @stable ICU 4.2 + */ + void clear() { ptr_ = nullptr; length_ = 0; } + + /** + * Reset the stringpiece to refer to new data. + * @param xdata pointer the new string data. Need not be nul terminated. + * @param len the length of the new data + * @stable ICU 4.8 + */ + void set(const char* xdata, int32_t len) { ptr_ = xdata; length_ = len; } + + /** + * Reset the stringpiece to refer to new data. + * @param str a pointer to a NUL-terminated string. + * @stable ICU 4.8 + */ + void set(const char* str); + +#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN) + /** + * Resets the stringpiece to refer to new data. + * @param xdata pointer the new string data. Need not be NUL-terminated. + * @param len the length of the new data + * @stable ICU 67 + */ + inline void set(const char8_t* xdata, int32_t len) { + set(reinterpret_cast(xdata), len); + } + + /** + * Resets the stringpiece to refer to new data. + * @param str a pointer to a NUL-terminated string. + * @stable ICU 67 + */ + inline void set(const char8_t* str) { + set(reinterpret_cast(str)); + } +#endif + + /** + * Removes the first n string units. + * @param n prefix length, must be non-negative and <=length() + * @stable ICU 4.2 + */ + void remove_prefix(int32_t n) { + if (n >= 0) { + if (n > length_) { + n = length_; + } + ptr_ += n; + length_ -= n; + } + } + + /** + * Removes the last n string units. + * @param n suffix length, must be non-negative and <=length() + * @stable ICU 4.2 + */ + void remove_suffix(int32_t n) { + if (n >= 0) { + if (n <= length_) { + length_ -= n; + } else { + length_ = 0; + } + } + } + + /** + * Searches the StringPiece for the given search string (needle); + * @param needle The string for which to search. + * @param offset Where to start searching within this string (haystack). + * @return The offset of needle in haystack, or -1 if not found. + * @stable ICU 67 + */ + int32_t find(StringPiece needle, int32_t offset); + + /** + * Compares this StringPiece with the other StringPiece, with semantics + * similar to std::string::compare(). + * @param other The string to compare to. + * @return below zero if this < other; above zero if this > other; 0 if this == other. + * @stable ICU 67 + */ + int32_t compare(StringPiece other); + + /** + * Maximum integer, used as a default value for substring methods. + * @stable ICU 4.2 + */ + static const int32_t npos; // = 0x7fffffff; + + /** + * Returns a substring of this StringPiece. + * @param pos start position; must be non-negative and <= length(). + * @param len length of the substring; + * must be non-negative and will be pinned to at most length() - pos. + * @return the substring StringPiece + * @stable ICU 4.2 + */ + StringPiece substr(int32_t pos, int32_t len = npos) const { + return StringPiece(*this, pos, len); + } +}; + +/** + * Global operator == for StringPiece + * @param x The first StringPiece to compare. + * @param y The second StringPiece to compare. + * @return true if the string data is equal + * @stable ICU 4.8 + */ +U_EXPORT UBool U_EXPORT2 +operator==(const StringPiece& x, const StringPiece& y); + +/** + * Global operator != for StringPiece + * @param x The first StringPiece to compare. + * @param y The second StringPiece to compare. + * @return true if the string data is not equal + * @stable ICU 4.8 + */ +inline bool operator!=(const StringPiece& x, const StringPiece& y) { + return !(x == y); +} + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __STRINGPIECE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringtriebuilder.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringtriebuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..429d7883f15cd84083a3cc3012d642b6b71bea40 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/stringtriebuilder.h @@ -0,0 +1,426 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2012,2014, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: stringtriebuilder.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010dec24 +* created by: Markus W. Scherer +*/ + +#ifndef __STRINGTRIEBUILDER_H__ +#define __STRINGTRIEBUILDER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Builder API for trie builders + */ + +// Forward declaration. +/// \cond +struct UHashtable; +typedef struct UHashtable UHashtable; +/// \endcond + +/** + * Build options for BytesTrieBuilder and CharsTrieBuilder. + * @stable ICU 4.8 + */ +enum UStringTrieBuildOption { + /** + * Builds a trie quickly. + * @stable ICU 4.8 + */ + USTRINGTRIE_BUILD_FAST, + /** + * Builds a trie more slowly, attempting to generate + * a shorter but equivalent serialization. + * This build option also uses more memory. + * + * This option can be effective when many integer values are the same + * and string/byte sequence suffixes can be shared. + * Runtime speed is not expected to improve. + * @stable ICU 4.8 + */ + USTRINGTRIE_BUILD_SMALL +}; + +U_NAMESPACE_BEGIN + +/** + * Base class for string trie builder classes. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API StringTrieBuilder : public UObject { +public: +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + static int32_t hashNode(const void *node); + /** @internal */ + static UBool equalNodes(const void *left, const void *right); +#endif /* U_HIDE_INTERNAL_API */ + +protected: + // Do not enclose the protected default constructor with #ifndef U_HIDE_INTERNAL_API + // or else the compiler will create a public default constructor. + /** @internal */ + StringTrieBuilder(); + /** @internal */ + virtual ~StringTrieBuilder(); + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + void createCompactBuilder(int32_t sizeGuess, UErrorCode &errorCode); + /** @internal */ + void deleteCompactBuilder(); + + /** @internal */ + void build(UStringTrieBuildOption buildOption, int32_t elementsLength, UErrorCode &errorCode); + + /** @internal */ + int32_t writeNode(int32_t start, int32_t limit, int32_t unitIndex); + /** @internal */ + int32_t writeBranchSubNode(int32_t start, int32_t limit, int32_t unitIndex, int32_t length); +#endif /* U_HIDE_INTERNAL_API */ + + class Node; + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + Node *makeNode(int32_t start, int32_t limit, int32_t unitIndex, UErrorCode &errorCode); + /** @internal */ + Node *makeBranchSubNode(int32_t start, int32_t limit, int32_t unitIndex, + int32_t length, UErrorCode &errorCode); +#endif /* U_HIDE_INTERNAL_API */ + + /** @internal */ + virtual int32_t getElementStringLength(int32_t i) const = 0; + /** @internal */ + virtual char16_t getElementUnit(int32_t i, int32_t unitIndex) const = 0; + /** @internal */ + virtual int32_t getElementValue(int32_t i) const = 0; + + // Finds the first unit index after this one where + // the first and last element have different units again. + /** @internal */ + virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t unitIndex) const = 0; + + // Number of different units at unitIndex. + /** @internal */ + virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t unitIndex) const = 0; + /** @internal */ + virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t unitIndex, int32_t count) const = 0; + /** @internal */ + virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t unitIndex, char16_t unit) const = 0; + + /** @internal */ + virtual UBool matchNodesCanHaveValues() const = 0; + + /** @internal */ + virtual int32_t getMaxBranchLinearSubNodeLength() const = 0; + /** @internal */ + virtual int32_t getMinLinearMatch() const = 0; + /** @internal */ + virtual int32_t getMaxLinearMatchLength() const = 0; + +#ifndef U_HIDE_INTERNAL_API + // max(BytesTrie::kMaxBranchLinearSubNodeLength, UCharsTrie::kMaxBranchLinearSubNodeLength). + /** @internal */ + static const int32_t kMaxBranchLinearSubNodeLength=5; + + // Maximum number of nested split-branch levels for a branch on all 2^16 possible char16_t units. + // log2(2^16/kMaxBranchLinearSubNodeLength) rounded up. + /** @internal */ + static const int32_t kMaxSplitBranchLevels=14; + + /** + * Makes sure that there is only one unique node registered that is + * equivalent to newNode. + * @param newNode Input node. The builder takes ownership. + * @param errorCode ICU in/out UErrorCode. + Set to U_MEMORY_ALLOCATION_ERROR if it was success but newNode==nullptr. + * @return newNode if it is the first of its kind, or + * an equivalent node if newNode is a duplicate. + * @internal + */ + Node *registerNode(Node *newNode, UErrorCode &errorCode); + /** + * Makes sure that there is only one unique FinalValueNode registered + * with this value. + * Avoids creating a node if the value is a duplicate. + * @param value A final value. + * @param errorCode ICU in/out UErrorCode. + Set to U_MEMORY_ALLOCATION_ERROR if it was success but newNode==nullptr. + * @return A FinalValueNode with the given value. + * @internal + */ + Node *registerFinalValue(int32_t value, UErrorCode &errorCode); +#endif /* U_HIDE_INTERNAL_API */ + + /* + * C++ note: + * registerNode() and registerFinalValue() take ownership of their input nodes, + * and only return owned nodes. + * If they see a failure UErrorCode, they will delete the input node. + * If they get a nullptr pointer, they will record a U_MEMORY_ALLOCATION_ERROR. + * If there is a failure, they return nullptr. + * + * nullptr Node pointers can be safely passed into other Nodes because + * they call the static Node::hashCode() which checks for a nullptr pointer first. + * + * Therefore, as long as builder functions register a new node, + * they need to check for failures only before explicitly dereferencing + * a Node pointer, or before setting a new UErrorCode. + */ + + // Hash set of nodes, maps from nodes to integer 1. + /** @internal */ + UHashtable *nodes; + + // Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API, + // it is needed for layout of other objects. + /** + * @internal + * \cond + */ + class Node : public UObject { + public: + Node(int32_t initialHash) : hash(initialHash), offset(0) {} + inline int32_t hashCode() const { return hash; } + // Handles node==nullptr. + static inline int32_t hashCode(const Node *node) { return node==nullptr ? 0 : node->hashCode(); } + // Base class operator==() compares the actual class types. + virtual bool operator==(const Node &other) const; + inline bool operator!=(const Node &other) const { return !operator==(other); } + /** + * Traverses the Node graph and numbers branch edges, with rightmost edges first. + * This is to avoid writing a duplicate node twice. + * + * Branch nodes in this trie data structure are not symmetric. + * Most branch edges "jump" to other nodes but the rightmost branch edges + * just continue without a jump. + * Therefore, write() must write the rightmost branch edge last + * (trie units are written backwards), and must write it at that point even if + * it is a duplicate of a node previously written elsewhere. + * + * This function visits and marks right branch edges first. + * Edges are numbered with increasingly negative values because we share the + * offset field which gets positive values when nodes are written. + * A branch edge also remembers the first number for any of its edges. + * + * When a further-left branch edge has a number in the range of the rightmost + * edge's numbers, then it will be written as part of the required right edge + * and we can avoid writing it first. + * + * After root.markRightEdgesFirst(-1) the offsets of all nodes are negative + * edge numbers. + * + * @param edgeNumber The first edge number for this node and its sub-nodes. + * @return An edge number that is at least the maximum-negative + * of the input edge number and the numbers of this node and all of its sub-nodes. + */ + virtual int32_t markRightEdgesFirst(int32_t edgeNumber); + // write() must set the offset to a positive value. + virtual void write(StringTrieBuilder &builder) = 0; + // See markRightEdgesFirst. + inline void writeUnlessInsideRightEdge(int32_t firstRight, int32_t lastRight, + StringTrieBuilder &builder) { + // Note: Edge numbers are negative, lastRight<=firstRight. + // If offset>0 then this node and its sub-nodes have been written already + // and we need not write them again. + // If this node is part of the unwritten right branch edge, + // then we wait until that is written. + if(offset<0 && (offsetStringSearch is a SearchIterator that provides + * language-sensitive text searching based on the comparison rules defined + * in a {@link RuleBasedCollator} object. + * StringSearch ensures that language eccentricity can be + * handled, e.g. for the German collator, characters ß and SS will be matched + * if case is chosen to be ignored. + * See the + * "ICU Collation Design Document" for more information. + *

+ * There are 2 match options for selection:
+ * Let S' be the sub-string of a text string S between the offsets start and + * end [start, end]. + *
+ * A pattern string P matches a text string S at the offsets [start, end] + * if + *

 
+ * option 1. Some canonical equivalent of P matches some canonical equivalent
+ *           of S'
+ * option 2. P matches S' and if P starts or ends with a combining mark,
+ *           there exists no non-ignorable combining mark before or after S?
+ *           in S respectively.
+ * 
+ * Option 2. will be the default. + *

+ * This search has APIs similar to that of other text iteration mechanisms + * such as the break iterators in BreakIterator. Using these + * APIs, it is easy to scan through text looking for all occurrences of + * a given pattern. This search iterator allows changing of direction by + * calling a reset followed by a next or previous. + * Though a direction change can occur without calling reset first, + * this operation comes with some speed penalty. + * Match results in the forward direction will match the result matches in + * the backwards direction in the reverse order + *

+ * SearchIterator provides APIs to specify the starting position + * within the text string to be searched, e.g. setOffset, + * preceding and following. Since the + * starting position will be set as it is specified, please take note that + * there are some danger points which the search may render incorrect + * results: + *

    + *
  • The midst of a substring that requires normalization. + *
  • If the following match is to be found, the position should not be the + * second character which requires to be swapped with the preceding + * character. Vice versa, if the preceding match is to be found, + * position to search from should not be the first character which + * requires to be swapped with the next character. E.g certain Thai and + * Lao characters require swapping. + *
  • If a following pattern match is to be found, any position within a + * contracting sequence except the first will fail. Vice versa if a + * preceding pattern match is to be found, a invalid starting point + * would be any character within a contracting sequence except the last. + *
+ *

+ * A BreakIterator can be used if only matches at logical breaks are desired. + * Using a BreakIterator will only give you results that exactly matches the + * boundaries given by the breakiterator. For instance the pattern "e" will + * not be found in the string "\u00e9" if a character break iterator is used. + *

+ * Options are provided to handle overlapping matches. + * E.g. In English, overlapping matches produces the result 0 and 2 + * for the pattern "abab" in the text "ababab", where else mutually + * exclusive matches only produce the result of 0. + *

+ * Though collator attributes will be taken into consideration while + * performing matches, there are no APIs here for setting and getting the + * attributes. These attributes can be set by getting the collator + * from getCollator and using the APIs in coll.h. + * Lastly to update StringSearch to the new collator attributes, + * reset has to be called. + *

+ * Restriction:
+ * Currently there are no composite characters that consists of a + * character with combining class > 0 before a character with combining + * class == 0. However, if such a character exists in the future, + * StringSearch does not guarantee the results for option 1. + *

+ * Consult the SearchIterator documentation for information on + * and examples of how to use instances of this class to implement text + * searching. + *


+ * UnicodeString target("The quick brown fox jumps over the lazy dog.");
+ * UnicodeString pattern("fox");
+ *
+ * UErrorCode      error = U_ZERO_ERROR;
+ * StringSearch iter(pattern, target, Locale::getUS(), nullptr, status);
+ * for (int pos = iter.first(error);
+ *      pos != USEARCH_DONE; 
+ *      pos = iter.next(error))
+ * {
+ *     printf("Found match at %d pos, length is %d\n", pos, iter.getMatchedLength());
+ * }
+ * 
+ *

+ * Note, StringSearch is not to be subclassed. + *

+ * @see SearchIterator + * @see RuleBasedCollator + * @since ICU 2.0 + */ + +class U_I18N_API StringSearch final : public SearchIterator +{ +public: + + // public constructors and destructors -------------------------------- + + /** + * Creating a StringSearch instance using the argument locale + * language rule set. A collator will be created in the process, which + * will be owned by this instance and will be deleted during + * destruction + * @param pattern The text for which this object will search. + * @param text The text in which to search for the pattern. + * @param locale A locale which defines the language-sensitive + * comparison rules used to determine whether text in the + * pattern and target matches. + * @param breakiter A BreakIterator object used to constrain + * the matches that are found. Matches whose start and end + * indices in the target text are not boundaries as + * determined by the BreakIterator are + * ignored. If this behavior is not desired, + * nullptr can be passed in instead. + * @param status for errors if any. If pattern or text is nullptr, or if + * either the length of pattern or text is 0 then an + * U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + StringSearch(const UnicodeString &pattern, const UnicodeString &text, + const Locale &locale, + BreakIterator *breakiter, + UErrorCode &status); + + /** + * Creating a StringSearch instance using the argument collator + * language rule set. Note, user retains the ownership of this collator, + * it does not get destroyed during this instance's destruction. + * @param pattern The text for which this object will search. + * @param text The text in which to search for the pattern. + * @param coll A RuleBasedCollator object which defines + * the language-sensitive comparison rules used to + * determine whether text in the pattern and target + * matches. User is responsible for the clearing of this + * object. + * @param breakiter A BreakIterator object used to constrain + * the matches that are found. Matches whose start and end + * indices in the target text are not boundaries as + * determined by the BreakIterator are + * ignored. If this behavior is not desired, + * nullptr can be passed in instead. + * @param status for errors if any. If either the length of pattern or + * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + StringSearch(const UnicodeString &pattern, + const UnicodeString &text, + RuleBasedCollator *coll, + BreakIterator *breakiter, + UErrorCode &status); + + /** + * Creating a StringSearch instance using the argument locale + * language rule set. A collator will be created in the process, which + * will be owned by this instance and will be deleted during + * destruction + *

+ * Note: No parsing of the text within the CharacterIterator + * will be done during searching for this version. The block of text + * in CharacterIterator will be used as it is. + * @param pattern The text for which this object will search. + * @param text The text iterator in which to search for the pattern. + * @param locale A locale which defines the language-sensitive + * comparison rules used to determine whether text in the + * pattern and target matches. User is responsible for + * the clearing of this object. + * @param breakiter A BreakIterator object used to constrain + * the matches that are found. Matches whose start and end + * indices in the target text are not boundaries as + * determined by the BreakIterator are + * ignored. If this behavior is not desired, + * nullptr can be passed in instead. + * @param status for errors if any. If either the length of pattern or + * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + StringSearch(const UnicodeString &pattern, CharacterIterator &text, + const Locale &locale, + BreakIterator *breakiter, + UErrorCode &status); + + /** + * Creating a StringSearch instance using the argument collator + * language rule set. Note, user retains the ownership of this collator, + * it does not get destroyed during this instance's destruction. + *

+ * Note: No parsing of the text within the CharacterIterator + * will be done during searching for this version. The block of text + * in CharacterIterator will be used as it is. + * @param pattern The text for which this object will search. + * @param text The text in which to search for the pattern. + * @param coll A RuleBasedCollator object which defines + * the language-sensitive comparison rules used to + * determine whether text in the pattern and target + * matches. User is responsible for the clearing of this + * object. + * @param breakiter A BreakIterator object used to constrain + * the matches that are found. Matches whose start and end + * indices in the target text are not boundaries as + * determined by the BreakIterator are + * ignored. If this behavior is not desired, + * nullptr can be passed in instead. + * @param status for errors if any. If either the length of pattern or + * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + StringSearch(const UnicodeString &pattern, CharacterIterator &text, + RuleBasedCollator *coll, + BreakIterator *breakiter, + UErrorCode &status); + + /** + * Copy constructor that creates a StringSearch instance with the same + * behavior, and iterating over the same text. + * @param that StringSearch instance to be copied. + * @stable ICU 2.0 + */ + StringSearch(const StringSearch &that); + + /** + * Destructor. Cleans up the search iterator data struct. + * If a collator is created in the constructor, it will be destroyed here. + * @stable ICU 2.0 + */ + virtual ~StringSearch(void); + + /** + * Clone this object. + * Clones can be used concurrently in multiple threads. + * If an error occurs, then nullptr is returned. + * The caller must delete the clone. + * + * @return a clone of this object + * + * @see getDynamicClassID + * @stable ICU 2.8 + */ + StringSearch *clone() const; + + // operator overloading --------------------------------------------- + + /** + * Assignment operator. Sets this iterator to have the same behavior, + * and iterate over the same text, as the one passed in. + * @param that instance to be copied. + * @stable ICU 2.0 + */ + StringSearch & operator=(const StringSearch &that); + + /** + * Equality operator. + * @param that instance to be compared. + * @return true if both instances have the same attributes, + * breakiterators, collators and iterate over the same text + * while looking for the same pattern. + * @stable ICU 2.0 + */ + virtual bool operator==(const SearchIterator &that) const override; + + // public get and set methods ---------------------------------------- + + /** + * Sets the index to point to the given position, and clears any state + * that's affected. + *

+ * This method takes the argument index and sets the position in the text + * string accordingly without checking if the index is pointing to a + * valid starting point to begin searching. + * @param position within the text to be set. If position is less + * than or greater than the text range for searching, + * an U_INDEX_OUTOFBOUNDS_ERROR will be returned + * @param status for errors if it occurs + * @stable ICU 2.0 + */ + virtual void setOffset(int32_t position, UErrorCode &status) override; + + /** + * Return the current index in the text being searched. + * If the iteration has gone past the end of the text + * (or past the beginning for a backwards search), USEARCH_DONE + * is returned. + * @return current index in the text being searched. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(void) const override; + + /** + * Set the target text to be searched. + * Text iteration will hence begin at the start of the text string. + * This method is + * useful if you want to re-use an iterator to search for the same + * pattern within a different body of text. + * @param text text string to be searched + * @param status for errors if any. If the text length is 0 then an + * U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + virtual void setText(const UnicodeString &text, UErrorCode &status) override; + + /** + * Set the target text to be searched. + * Text iteration will hence begin at the start of the text string. + * This method is + * useful if you want to re-use an iterator to search for the same + * pattern within a different body of text. + * Note: No parsing of the text within the CharacterIterator + * will be done during searching for this version. The block of text + * in CharacterIterator will be used as it is. + * @param text text string to be searched + * @param status for errors if any. If the text length is 0 then an + * U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + virtual void setText(CharacterIterator &text, UErrorCode &status) override; + + /** + * Gets the collator used for the language rules. + *

+ * Caller may modify but must not delete the RuleBasedCollator! + * Modifications to this collator will affect the original collator passed in to + * the StringSearch> constructor or to setCollator, if any. + * @return collator used for string search + * @stable ICU 2.0 + */ + RuleBasedCollator * getCollator() const; + + /** + * Sets the collator used for the language rules. User retains the + * ownership of this collator, thus the responsibility of deletion lies + * with the user. The iterator's position will not be changed by this method. + * @param coll collator + * @param status for errors if any + * @stable ICU 2.0 + */ + void setCollator(RuleBasedCollator *coll, UErrorCode &status); + + /** + * Sets the pattern used for matching. + * The iterator's position will not be changed by this method. + * @param pattern search pattern to be found + * @param status for errors if any. If the pattern length is 0 then an + * U_ILLEGAL_ARGUMENT_ERROR is returned. + * @stable ICU 2.0 + */ + void setPattern(const UnicodeString &pattern, UErrorCode &status); + + /** + * Gets the search pattern. + * @return pattern used for matching + * @stable ICU 2.0 + */ + const UnicodeString & getPattern() const; + + // public methods ---------------------------------------------------- + + /** + * Reset the iteration. + * Search will begin at the start of the text string if a forward + * iteration is initiated before a backwards iteration. Otherwise if + * a backwards iteration is initiated before a forwards iteration, the + * search will begin at the end of the text string. + * @stable ICU 2.0 + */ + virtual void reset() override; + + /** + * Returns a copy of StringSearch with the same behavior, and + * iterating over the same text, as this one. Note that all data will be + * replicated, except for the user-specified collator and the + * breakiterator. + * @return cloned object + * @stable ICU 2.0 + */ + virtual StringSearch * safeClone() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * + * @stable ICU 2.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +protected: + + // protected method ------------------------------------------------- + + /** + * Search forward for matching text, starting at a given location. + * Clients should not call this method directly; instead they should + * call {@link SearchIterator#next }. + *

+ * If a match is found, this method returns the index at which the match + * starts and calls {@link SearchIterator#setMatchLength } with the number + * of characters in the target text that make up the match. If no match + * is found, the method returns USEARCH_DONE. + *

+ * The StringSearch is adjusted so that its current index + * (as returned by {@link #getOffset }) is the match position if one was + * found. + * If a match is not found, USEARCH_DONE will be returned and + * the StringSearch will be adjusted to the index USEARCH_DONE. + * @param position The index in the target text at which the search + * starts + * @param status for errors if any occurs + * @return The index at which the matched text in the target starts, or + * USEARCH_DONE if no match was found. + * @stable ICU 2.0 + */ + virtual int32_t handleNext(int32_t position, UErrorCode &status) override; + + /** + * Search backward for matching text, starting at a given location. + * Clients should not call this method directly; instead they should call + * SearchIterator.previous(), which this method overrides. + *

+ * If a match is found, this method returns the index at which the match + * starts and calls {@link SearchIterator#setMatchLength } with the number + * of characters in the target text that make up the match. If no match + * is found, the method returns USEARCH_DONE. + *

+ * The StringSearch is adjusted so that its current index + * (as returned by {@link #getOffset }) is the match position if one was + * found. + * If a match is not found, USEARCH_DONE will be returned and + * the StringSearch will be adjusted to the index USEARCH_DONE. + * @param position The index in the target text at which the search + * starts. + * @param status for errors if any occurs + * @return The index at which the matched text in the target starts, or + * USEARCH_DONE if no match was found. + * @stable ICU 2.0 + */ + virtual int32_t handlePrev(int32_t position, UErrorCode &status) override; + +private : + StringSearch() = delete; // default constructor not implemented + + // private data members ---------------------------------------------- + + /** + * Pattern text + * @stable ICU 2.0 + */ + UnicodeString m_pattern_; + /** + * String search struct data + * @stable ICU 2.0 + */ + UStringSearch *m_strsrch_; + +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/symtable.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/symtable.h new file mode 100644 index 0000000000000000000000000000000000000000..647a3884a00c8c566f4bf9440eb68dd72c7435c1 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/symtable.h @@ -0,0 +1,119 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2000-2005, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 02/04/00 aliu Creation. +********************************************************************** +*/ +#ifndef SYMTABLE_H +#define SYMTABLE_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: An interface that defines both lookup protocol and parsing of + * symbolic names. + */ + +U_NAMESPACE_BEGIN + +class ParsePosition; +class UnicodeFunctor; +class UnicodeSet; +class UnicodeString; + +/** + * An interface that defines both lookup protocol and parsing of + * symbolic names. + * + *

A symbol table maintains two kinds of mappings. The first is + * between symbolic names and their values. For example, if the + * variable with the name "start" is set to the value "alpha" + * (perhaps, though not necessarily, through an expression such as + * "$start=alpha"), then the call lookup("start") will return the + * char[] array ['a', 'l', 'p', 'h', 'a']. + * + *

The second kind of mapping is between character values and + * UnicodeMatcher objects. This is used by RuleBasedTransliterator, + * which uses characters in the private use area to represent objects + * such as UnicodeSets. If U+E015 is mapped to the UnicodeSet [a-z], + * then lookupMatcher(0xE015) will return the UnicodeSet [a-z]. + * + *

Finally, a symbol table defines parsing behavior for symbolic + * names. All symbolic names start with the SYMBOL_REF character. + * When a parser encounters this character, it calls parseReference() + * with the position immediately following the SYMBOL_REF. The symbol + * table parses the name, if there is one, and returns it. + * + * @stable ICU 2.8 + */ +class U_COMMON_API SymbolTable /* not : public UObject because this is an interface/mixin class */ { +public: + + /** + * The character preceding a symbol reference name. + * @stable ICU 2.8 + */ + enum { SYMBOL_REF = 0x0024 /*$*/ }; + + /** + * Destructor. + * @stable ICU 2.8 + */ + virtual ~SymbolTable(); + + /** + * Lookup the characters associated with this string and return it. + * Return nullptr if no such name exists. The resultant + * string may have length zero. + * @param s the symbolic name to lookup + * @return a string containing the name's value, or nullptr if + * there is no mapping for s. + * @stable ICU 2.8 + */ + virtual const UnicodeString* lookup(const UnicodeString& s) const = 0; + + /** + * Lookup the UnicodeMatcher associated with the given character, and + * return it. Return nullptr if not found. + * @param ch a 32-bit code point from 0 to 0x10FFFF inclusive. + * @return the UnicodeMatcher object represented by the given + * character, or nullptr if there is no mapping for ch. + * @stable ICU 2.8 + */ + virtual const UnicodeFunctor* lookupMatcher(UChar32 ch) const = 0; + + /** + * Parse a symbol reference name from the given string, starting + * at the given position. If no valid symbol reference name is + * found, return the empty string and leave pos unchanged. That is, if the + * character at pos cannot start a name, or if pos is at or after + * text.length(), then return an empty string. This indicates an + * isolated SYMBOL_REF character. + * @param text the text to parse for the name + * @param pos on entry, the index of the first character to parse. + * This is the character following the SYMBOL_REF character. On + * exit, the index after the last parsed character. If the parse + * failed, pos is unchanged on exit. + * @param limit the index after the last character to be parsed. + * @return the parsed name, or an empty string if there is no + * valid symbolic name at the given position. + * @stable ICU 2.8 + */ + virtual UnicodeString parseReference(const UnicodeString& text, + ParsePosition& pos, int32_t limit) const = 0; +}; +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tblcoll.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tblcoll.h new file mode 100644 index 0000000000000000000000000000000000000000..43cf35d1a81b4c391a0c4af211df44e1a2829aa4 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tblcoll.h @@ -0,0 +1,886 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 1996-2016, International Business Machines Corporation and +* others. All Rights Reserved. +****************************************************************************** +*/ + +/** + * \file + * \brief C++ API: The RuleBasedCollator class implements the Collator abstract base class. + */ + +/** +* File tblcoll.h +* +* Created by: Helena Shih +* +* Modification History: +* +* Date Name Description +* 2/5/97 aliu Added streamIn and streamOut methods. Added +* constructor which reads RuleBasedCollator object from +* a binary file. Added writeToFile method which streams +* RuleBasedCollator out to a binary file. The streamIn +* and streamOut methods use istream and ostream objects +* in binary mode. +* 2/12/97 aliu Modified to use TableCollationData sub-object to +* hold invariant data. +* 2/13/97 aliu Moved several methods into this class from Collation. +* Added a private RuleBasedCollator(Locale&) constructor, +* to be used by Collator::createDefault(). General +* clean up. +* 2/20/97 helena Added clone, operator==, operator!=, operator=, and copy +* constructor and getDynamicClassID. +* 3/5/97 aliu Modified constructFromFile() to add parameter +* specifying whether or not binary loading is to be +* attempted. This is required for dynamic rule loading. +* 05/07/97 helena Added memory allocation error detection. +* 6/17/97 helena Added IDENTICAL strength for compare, changed getRules to +* use MergeCollation::getPattern. +* 6/20/97 helena Java class name change. +* 8/18/97 helena Added internal API documentation. +* 09/03/97 helena Added createCollationKeyValues(). +* 02/10/98 damiba Added compare with "length" parameter +* 08/05/98 erm Synched with 1.2 version of RuleBasedCollator.java +* 04/23/99 stephen Removed EDecompositionMode, merged with +* Normalizer::EMode +* 06/14/99 stephen Removed kResourceBundleSuffix +* 11/02/99 helena Collator performance enhancements. Eliminates the +* UnicodeString construction and special case for NO_OP. +* 11/23/99 srl More performance enhancements. Updates to NormalizerIterator +* internal state management. +* 12/15/99 aliu Update to support Thai collation. Move NormalizerIterator +* to implementation file. +* 01/29/01 synwee Modified into a C++ wrapper which calls C API +* (ucol.h) +* 2012-2014 markus Rewritten in C++ again. +*/ + +#ifndef TBLCOLL_H +#define TBLCOLL_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_COLLATION + +#include "unicode/coll.h" +#include "unicode/locid.h" +#include "unicode/uiter.h" +#include "unicode/ucol.h" + +U_NAMESPACE_BEGIN + +struct CollationCacheEntry; +struct CollationData; +struct CollationSettings; +struct CollationTailoring; +/** +* @stable ICU 2.0 +*/ +class StringSearch; +/** +* @stable ICU 2.0 +*/ +class CollationElementIterator; +class CollationKey; +class SortKeyByteSink; +class UnicodeSet; +class UnicodeString; +class UVector64; + +/** + * The RuleBasedCollator class provides the implementation of + * Collator, using data-driven tables. The user can create a customized + * table-based collation. + *

+ * For more information about the collation service see + * the User Guide. + *

+ * Collation service provides correct sorting orders for most locales supported in ICU. + * If specific data for a locale is not available, the orders eventually falls back + * to the CLDR root sort order. + *

+ * Sort ordering may be customized by providing your own set of rules. For more on + * this subject see the + * Collation Customization section of the User Guide. + *

+ * Note, RuleBasedCollator is not to be subclassed. + * @see Collator + */ +class U_I18N_API RuleBasedCollator final : public Collator { +public: + /** + * RuleBasedCollator constructor. This takes the table rules and builds a + * collation table out of them. Please see RuleBasedCollator class + * description for more details on the collation rule syntax. + * @param rules the collation rules to build the collation table from. + * @param status reporting a success or an error. + * @stable ICU 2.0 + */ + RuleBasedCollator(const UnicodeString& rules, UErrorCode& status); + + /** + * RuleBasedCollator constructor. This takes the table rules and builds a + * collation table out of them. Please see RuleBasedCollator class + * description for more details on the collation rule syntax. + * @param rules the collation rules to build the collation table from. + * @param collationStrength strength for comparison + * @param status reporting a success or an error. + * @stable ICU 2.0 + */ + RuleBasedCollator(const UnicodeString& rules, + ECollationStrength collationStrength, + UErrorCode& status); + + /** + * RuleBasedCollator constructor. This takes the table rules and builds a + * collation table out of them. Please see RuleBasedCollator class + * description for more details on the collation rule syntax. + * @param rules the collation rules to build the collation table from. + * @param decompositionMode the normalisation mode + * @param status reporting a success or an error. + * @stable ICU 2.0 + */ + RuleBasedCollator(const UnicodeString& rules, + UColAttributeValue decompositionMode, + UErrorCode& status); + + /** + * RuleBasedCollator constructor. This takes the table rules and builds a + * collation table out of them. Please see RuleBasedCollator class + * description for more details on the collation rule syntax. + * @param rules the collation rules to build the collation table from. + * @param collationStrength strength for comparison + * @param decompositionMode the normalisation mode + * @param status reporting a success or an error. + * @stable ICU 2.0 + */ + RuleBasedCollator(const UnicodeString& rules, + ECollationStrength collationStrength, + UColAttributeValue decompositionMode, + UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * TODO: document & propose as public API + * @internal + */ + RuleBasedCollator(const UnicodeString &rules, + UParseError &parseError, UnicodeString &reason, + UErrorCode &errorCode); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Copy constructor. + * @param other the RuleBasedCollator object to be copied + * @stable ICU 2.0 + */ + RuleBasedCollator(const RuleBasedCollator& other); + + + /** Opens a collator from a collator binary image created using + * cloneBinary. Binary image used in instantiation of the + * collator remains owned by the user and should stay around for + * the lifetime of the collator. The API also takes a base collator + * which must be the root collator. + * @param bin binary image owned by the user and required through the + * lifetime of the collator + * @param length size of the image. If negative, the API will try to + * figure out the length of the image + * @param base Base collator, for lookup of untailored characters. + * Must be the root collator, must not be nullptr. + * The base is required to be present through the lifetime of the collator. + * @param status for catching errors + * @return newly created collator + * @see cloneBinary + * @stable ICU 3.4 + */ + RuleBasedCollator(const uint8_t *bin, int32_t length, + const RuleBasedCollator *base, + UErrorCode &status); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~RuleBasedCollator(); + + /** + * Assignment operator. + * @param other other RuleBasedCollator object to copy from. + * @stable ICU 2.0 + */ + RuleBasedCollator& operator=(const RuleBasedCollator& other); + + /** + * Returns true if argument is the same as this object. + * @param other Collator object to be compared. + * @return true if arguments is the same as this object. + * @stable ICU 2.0 + */ + virtual bool operator==(const Collator& other) const override; + + /** + * Makes a copy of this object. + * @return a copy of this object, owned by the caller + * @stable ICU 2.0 + */ + virtual RuleBasedCollator* clone() const override; + + /** + * Creates a collation element iterator for the source string. The caller of + * this method is responsible for the memory management of the return + * pointer. + * @param source the string over which the CollationElementIterator will + * iterate. + * @return the collation element iterator of the source string using this as + * the based Collator. + * @stable ICU 2.2 + */ + virtual CollationElementIterator* createCollationElementIterator( + const UnicodeString& source) const; + + /** + * Creates a collation element iterator for the source. The caller of this + * method is responsible for the memory management of the returned pointer. + * @param source the CharacterIterator which produces the characters over + * which the CollationElementItgerator will iterate. + * @return the collation element iterator of the source using this as the + * based Collator. + * @stable ICU 2.2 + */ + virtual CollationElementIterator* createCollationElementIterator( + const CharacterIterator& source) const; + + // Make deprecated versions of Collator::compare() visible. + using Collator::compare; + + /** + * The comparison function compares the character data stored in two + * different strings. Returns information about whether a string is less + * than, greater than or equal to another string. + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source is greater + * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less + * than target + * @stable ICU 2.6 + **/ + virtual UCollationResult compare(const UnicodeString& source, + const UnicodeString& target, + UErrorCode &status) const override; + + /** + * Does the same thing as compare but limits the comparison to a specified + * length + * @param source the source string to be compared with. + * @param target the string that is to be compared with the source string. + * @param length the length the comparison is limited to + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source (up to the specified + * length) is greater than target; UCOL_EQUAL if source (up to specified + * length) is equal to target; UCOL_LESS if source (up to the specified + * length) is less than target. + * @stable ICU 2.6 + */ + virtual UCollationResult compare(const UnicodeString& source, + const UnicodeString& target, + int32_t length, + UErrorCode &status) const override; + + /** + * The comparison function compares the character data stored in two + * different string arrays. Returns information about whether a string array + * is less than, greater than or equal to another string array. + * @param source the source string array to be compared with. + * @param sourceLength the length of the source string array. If this value + * is equal to -1, the string array is null-terminated. + * @param target the string that is to be compared with the source string. + * @param targetLength the length of the target string array. If this value + * is equal to -1, the string array is null-terminated. + * @param status possible error code + * @return Returns an enum value. UCOL_GREATER if source is greater + * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less + * than target + * @stable ICU 2.6 + */ + virtual UCollationResult compare(const char16_t* source, int32_t sourceLength, + const char16_t* target, int32_t targetLength, + UErrorCode &status) const override; + + /** + * Compares two strings using the Collator. + * Returns whether the first one compares less than/equal to/greater than + * the second one. + * This version takes UCharIterator input. + * @param sIter the first ("source") string iterator + * @param tIter the second ("target") string iterator + * @param status ICU status + * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER + * @stable ICU 4.2 + */ + virtual UCollationResult compare(UCharIterator &sIter, + UCharIterator &tIter, + UErrorCode &status) const override; + + /** + * Compares two UTF-8 strings using the Collator. + * Returns whether the first one compares less than/equal to/greater than + * the second one. + * This version takes UTF-8 input. + * Note that a StringPiece can be implicitly constructed + * from a std::string or a NUL-terminated const char * string. + * @param source the first UTF-8 string + * @param target the second UTF-8 string + * @param status ICU status + * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER + * @stable ICU 51 + */ + virtual UCollationResult compareUTF8(const StringPiece &source, + const StringPiece &target, + UErrorCode &status) const override; + + /** + * Transforms the string into a series of characters + * that can be compared with CollationKey.compare(). + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source the source string. + * @param key the transformed key of the source string. + * @param status the error code status. + * @return the transformed key. + * @see CollationKey + * @stable ICU 2.0 + */ + virtual CollationKey& getCollationKey(const UnicodeString& source, + CollationKey& key, + UErrorCode& status) const override; + + /** + * Transforms a specified region of the string into a series of characters + * that can be compared with CollationKey.compare. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source the source string. + * @param sourceLength the length of the source string. + * @param key the transformed key of the source string. + * @param status the error code status. + * @return the transformed key. + * @see CollationKey + * @stable ICU 2.0 + */ + virtual CollationKey& getCollationKey(const char16_t *source, + int32_t sourceLength, + CollationKey& key, + UErrorCode& status) const override; + + /** + * Generates the hash code for the rule-based collation object. + * @return the hash code. + * @stable ICU 2.0 + */ + virtual int32_t hashCode() const override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Gets the locale of the Collator + * @param type can be either requested, valid or actual locale. For more + * information see the definition of ULocDataLocaleType in + * uloc.h + * @param status the error code status. + * @return locale where the collation data lives. If the collator + * was instantiated from rules, locale is empty. + * @deprecated ICU 2.8 likely to change in ICU 3.0, based on feedback + */ + virtual Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the tailoring rules for this collator. + * @return the collation tailoring from which this collator was created + * @stable ICU 2.0 + */ + const UnicodeString& getRules() const; + + /** + * Gets the version information for a Collator. + * @param info the version # information, the result will be filled in + * @stable ICU 2.0 + */ + virtual void getVersion(UVersionInfo info) const override; + +#ifndef U_HIDE_DEPRECATED_API + /** + * Returns the maximum length of any expansion sequences that end with the + * specified comparison order. + * + * This is specific to the kind of collation element values and sequences + * returned by the CollationElementIterator. + * Call CollationElementIterator::getMaxExpansion() instead. + * + * @param order a collation order returned by CollationElementIterator::previous + * or CollationElementIterator::next. + * @return maximum size of the expansion sequences ending with the collation + * element, or 1 if the collation element does not occur at the end of + * any expansion sequence + * @see CollationElementIterator#getMaxExpansion + * @deprecated ICU 51 Use CollationElementIterator::getMaxExpansion() instead. + */ + int32_t getMaxExpansion(int32_t order) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * @return The class ID for this object. All objects of a given class have + * the same class ID. Objects of other classes have different class + * IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + + /** + * Returns the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * Base* polymorphic_pointer = createPolymorphicObject();
+     * if (polymorphic_pointer->getDynamicClassID() ==
+     *                                          Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Do not use this method: The caller and the ICU library might use different heaps. + * Use cloneBinary() instead which writes to caller-provided memory. + * + * Returns a binary format of this collator. + * @param length Returns the length of the data, in bytes + * @param status the error code status. + * @return memory, owned by the caller, of size 'length' bytes. + * @deprecated ICU 52. Use cloneBinary() instead. + */ + uint8_t *cloneRuleData(int32_t &length, UErrorCode &status) const; +#endif /* U_HIDE_DEPRECATED_API */ + + /** Creates a binary image of a collator. This binary image can be stored and + * later used to instantiate a collator using ucol_openBinary. + * This API supports preflighting. + * @param buffer a fill-in buffer to receive the binary image + * @param capacity capacity of the destination buffer + * @param status for catching errors + * @return size of the image + * @see ucol_openBinary + * @stable ICU 3.4 + */ + int32_t cloneBinary(uint8_t *buffer, int32_t capacity, UErrorCode &status) const; + + /** + * Returns current rules. Delta defines whether full rules are returned or + * just the tailoring. + * + * getRules(void) should normally be used instead. + * See https://unicode-org.github.io/icu/userguide/collation/customization#building-on-existing-locales + * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES. + * @param buffer UnicodeString to store the result rules + * @stable ICU 2.2 + * @see UCOL_FULL_RULES + */ + void getRules(UColRuleOption delta, UnicodeString &buffer) const; + + /** + * Universal attribute setter + * @param attr attribute type + * @param value attribute value + * @param status to indicate whether the operation went on smoothly or there were errors + * @stable ICU 2.2 + */ + virtual void setAttribute(UColAttribute attr, UColAttributeValue value, + UErrorCode &status) override; + + /** + * Universal attribute getter. + * @param attr attribute type + * @param status to indicate whether the operation went on smoothly or there were errors + * @return attribute value + * @stable ICU 2.2 + */ + virtual UColAttributeValue getAttribute(UColAttribute attr, + UErrorCode &status) const override; + + /** + * Sets the variable top to the top of the specified reordering group. + * The variable top determines the highest-sorting character + * which is affected by UCOL_ALTERNATE_HANDLING. + * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. + * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, + * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; + * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @see getMaxVariable + * @stable ICU 53 + */ + virtual Collator &setMaxVariable(UColReorderCode group, UErrorCode &errorCode) override; + + /** + * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. + * @return the maximum variable reordering group. + * @see setMaxVariable + * @stable ICU 53 + */ + virtual UColReorderCode getMaxVariable() const override; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Sets the variable top to the primary weight of the specified string. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop one or more (if contraction) char16_ts to which the variable top should be set + * @param len length of variable top string. If -1 it is considered to be zero terminated. + * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
+ * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
+ * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond + * the last reordering group supported by setMaxVariable() + * @return variable top primary weight + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual uint32_t setVariableTop(const char16_t *varTop, int32_t len, UErrorCode &status) override; + + /** + * Sets the variable top to the primary weight of the specified string. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop a UnicodeString size 1 or more (if contraction) of char16_ts to which the variable top should be set + * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
+ * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
+ * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond + * the last reordering group supported by setMaxVariable() + * @return variable top primary weight + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual uint32_t setVariableTop(const UnicodeString &varTop, UErrorCode &status) override; + + /** + * Sets the variable top to the specified primary weight. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See setMaxVariable(). + * @param varTop primary weight, as returned by setVariableTop or ucol_getVariableTop + * @param status error code + * @deprecated ICU 53 Call setMaxVariable() instead. + */ + virtual void setVariableTop(uint32_t varTop, UErrorCode &status) override; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Gets the variable top value of a Collator. + * @param status error code (not changed by function). If error code is set, the return value is undefined. + * @return the variable top primary weight + * @see getMaxVariable + * @stable ICU 2.0 + */ + virtual uint32_t getVariableTop(UErrorCode &status) const override; + + /** + * Get a UnicodeSet that contains all the characters and sequences tailored in + * this collator. + * @param status error code of the operation + * @return a pointer to a UnicodeSet object containing all the + * code points and sequences that may sort differently than + * in the root collator. The object must be disposed of by using delete + * @stable ICU 2.4 + */ + virtual UnicodeSet *getTailoredSet(UErrorCode &status) const override; + + /** + * Get the sort key as an array of bytes from a UnicodeString. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source string to be processed. + * @param result buffer to store result in. If nullptr, number of bytes needed + * will be returned. + * @param resultLength length of the result buffer. If if not enough the + * buffer will be filled to capacity. + * @return Number of bytes needed for storing the sort key + * @stable ICU 2.0 + */ + virtual int32_t getSortKey(const UnicodeString& source, uint8_t *result, + int32_t resultLength) const override; + + /** + * Get the sort key as an array of bytes from a char16_t buffer. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * @param source string to be processed. + * @param sourceLength length of string to be processed. If -1, the string + * is 0 terminated and length will be decided by the function. + * @param result buffer to store result in. If nullptr, number of bytes needed + * will be returned. + * @param resultLength length of the result buffer. If if not enough the + * buffer will be filled to capacity. + * @return Number of bytes needed for storing the sort key + * @stable ICU 2.2 + */ + virtual int32_t getSortKey(const char16_t *source, int32_t sourceLength, + uint8_t *result, int32_t resultLength) const override; + + /** + * Retrieves the reordering codes for this collator. + * @param dest The array to fill with the script ordering. + * @param destCapacity The length of dest. If it is 0, then dest may be nullptr and the function + * will only return the length of the result without writing any codes (pre-flighting). + * @param status A reference to an error code value, which must not indicate + * a failure before the function call. + * @return The length of the script ordering array. + * @see ucol_setReorderCodes + * @see Collator#getEquivalentReorderCodes + * @see Collator#setReorderCodes + * @stable ICU 4.8 + */ + virtual int32_t getReorderCodes(int32_t *dest, + int32_t destCapacity, + UErrorCode& status) const override; + + /** + * Sets the ordering of scripts for this collator. + * @param reorderCodes An array of script codes in the new order. This can be nullptr if the + * length is also set to 0. An empty array will clear any reordering codes on the collator. + * @param reorderCodesLength The length of reorderCodes. + * @param status error code + * @see ucol_setReorderCodes + * @see Collator#getReorderCodes + * @see Collator#getEquivalentReorderCodes + * @stable ICU 4.8 + */ + virtual void setReorderCodes(const int32_t* reorderCodes, + int32_t reorderCodesLength, + UErrorCode& status) override; + + /** + * Implements ucol_strcollUTF8(). + * @internal + */ + virtual UCollationResult internalCompareUTF8( + const char *left, int32_t leftLength, + const char *right, int32_t rightLength, + UErrorCode &errorCode) const override; + + /** Get the short definition string for a collator. This internal API harvests the collator's + * locale and the attribute set and produces a string that can be used for opening + * a collator with the same attributes using the ucol_openFromShortString API. + * This string will be normalized. + * The structure and the syntax of the string is defined in the "Naming collators" + * section of the users guide: + * https://unicode-org.github.io/icu/userguide/collation/concepts#collator-naming-scheme + * This function supports preflighting. + * + * This is internal, and intended to be used with delegate converters. + * + * @param locale a locale that will appear as a collators locale in the resulting + * short string definition. If nullptr, the locale will be harvested + * from the collator. + * @param buffer space to hold the resulting string + * @param capacity capacity of the buffer + * @param status for returning errors. All the preflighting errors are featured + * @return length of the resulting string + * @see ucol_openFromShortString + * @see ucol_normalizeShortDefinitionString + * @see ucol_getShortDefinitionString + * @internal + */ + virtual int32_t internalGetShortDefinitionString(const char *locale, + char *buffer, + int32_t capacity, + UErrorCode &status) const override; + + /** + * Implements ucol_nextSortKeyPart(). + * @internal + */ + virtual int32_t internalNextSortKeyPart( + UCharIterator *iter, uint32_t state[2], + uint8_t *dest, int32_t count, UErrorCode &errorCode) const override; + + // Do not enclose the default constructor with #ifndef U_HIDE_INTERNAL_API + /** + * Only for use in ucol_openRules(). + * @internal + */ + RuleBasedCollator(); + +#ifndef U_HIDE_INTERNAL_API + /** + * Implements ucol_getLocaleByType(). + * Needed because the lifetime of the locale ID string must match that of the collator. + * getLocale() returns a copy of a Locale, with minimal lifetime in a C wrapper. + * @internal + */ + const char *internalGetLocaleID(ULocDataLocaleType type, UErrorCode &errorCode) const; + + /** + * Implements ucol_getContractionsAndExpansions(). + * Gets this collator's sets of contraction strings and/or + * characters and strings that map to multiple collation elements (expansions). + * If addPrefixes is true, then contractions that are expressed as + * prefix/pre-context rules are included. + * @param contractions if not nullptr, the set to hold the contractions + * @param expansions if not nullptr, the set to hold the expansions + * @param addPrefixes include prefix contextual mappings + * @param errorCode in/out ICU error code + * @internal + */ + void internalGetContractionsAndExpansions( + UnicodeSet *contractions, UnicodeSet *expansions, + UBool addPrefixes, UErrorCode &errorCode) const; + + /** + * Adds the contractions that start with character c to the set. + * Ignores prefixes. Used by AlphabeticIndex. + * @internal + */ + void internalAddContractions(UChar32 c, UnicodeSet &set, UErrorCode &errorCode) const; + + /** + * Implements from-rule constructors, and ucol_openRules(). + * @internal + */ + void internalBuildTailoring( + const UnicodeString &rules, + int32_t strength, + UColAttributeValue decompositionMode, + UParseError *outParseError, UnicodeString *outReason, + UErrorCode &errorCode); + + /** @internal */ + static inline RuleBasedCollator *rbcFromUCollator(UCollator *uc) { + return dynamic_cast(fromUCollator(uc)); + } + /** @internal */ + static inline const RuleBasedCollator *rbcFromUCollator(const UCollator *uc) { + return dynamic_cast(fromUCollator(uc)); + } + + /** + * Appends the CEs for the string to the vector. + * @internal for tests & tools + */ + void internalGetCEs(const UnicodeString &str, UVector64 &ces, UErrorCode &errorCode) const; +#endif // U_HIDE_INTERNAL_API + +protected: + /** + * Used internally by registration to define the requested and valid locales. + * @param requestedLocale the requested locale + * @param validLocale the valid locale + * @param actualLocale the actual locale + * @internal + */ + virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale) override; + +private: + friend class CollationElementIterator; + friend class Collator; + + RuleBasedCollator(const CollationCacheEntry *entry); + + /** + * Enumeration of attributes that are relevant for short definition strings + * (e.g., ucol_getShortDefinitionString()). + * Effectively extends UColAttribute. + */ + enum Attributes { + ATTR_VARIABLE_TOP = UCOL_ATTRIBUTE_COUNT, + ATTR_LIMIT + }; + + void adoptTailoring(CollationTailoring *t, UErrorCode &errorCode); + + // Both lengths must be <0 or else both must be >=0. + UCollationResult doCompare(const char16_t *left, int32_t leftLength, + const char16_t *right, int32_t rightLength, + UErrorCode &errorCode) const; + UCollationResult doCompare(const uint8_t *left, int32_t leftLength, + const uint8_t *right, int32_t rightLength, + UErrorCode &errorCode) const; + + void writeSortKey(const char16_t *s, int32_t length, + SortKeyByteSink &sink, UErrorCode &errorCode) const; + + void writeIdenticalLevel(const char16_t *s, const char16_t *limit, + SortKeyByteSink &sink, UErrorCode &errorCode) const; + + const CollationSettings &getDefaultSettings() const; + + void setAttributeDefault(int32_t attribute) { + explicitlySetAttributes &= ~((uint32_t)1 << attribute); + } + void setAttributeExplicitly(int32_t attribute) { + explicitlySetAttributes |= (uint32_t)1 << attribute; + } + UBool attributeHasBeenSetExplicitly(int32_t attribute) const { + // assert(0 <= attribute < ATTR_LIMIT); + return (UBool)((explicitlySetAttributes & ((uint32_t)1 << attribute)) != 0); + } + + /** + * Tests whether a character is "unsafe" for use as a collation starting point. + * + * @param c code point or code unit + * @return true if c is unsafe + * @see CollationElementIterator#setOffset(int) + */ + UBool isUnsafe(UChar32 c) const; + + static void U_CALLCONV computeMaxExpansions(const CollationTailoring *t, UErrorCode &errorCode); + UBool initMaxExpansions(UErrorCode &errorCode) const; + + void setFastLatinOptions(CollationSettings &ownedSettings) const; + + const CollationData *data; + const CollationSettings *settings; // reference-counted + const CollationTailoring *tailoring; // alias of cacheEntry->tailoring + const CollationCacheEntry *cacheEntry; // reference-counted + Locale validLocale; + uint32_t explicitlySetAttributes; + + UBool actualLocaleIsSameAsValid; +}; + +U_NAMESPACE_END + +#endif // !UCONFIG_NO_COLLATION + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // TBLCOLL_H diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/timezone.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/timezone.h new file mode 100644 index 0000000000000000000000000000000000000000..a2c0552c18971545a8943a68dd7001b49c8b6d29 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/timezone.h @@ -0,0 +1,1038 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/************************************************************************* +* Copyright (c) 1997-2016, International Business Machines Corporation +* and others. All Rights Reserved. +************************************************************************** +* +* File TIMEZONE.H +* +* Modification History: +* +* Date Name Description +* 04/21/97 aliu Overhauled header. +* 07/09/97 helena Changed createInstance to createDefault. +* 08/06/97 aliu Removed dependency on internal header for Hashtable. +* 08/10/98 stephen Changed getDisplayName() API conventions to match +* 08/19/98 stephen Changed createTimeZone() to never return 0 +* 09/02/98 stephen Sync to JDK 1.2 8/31 +* - Added getOffset(... monthlen ...) +* - Added hasSameRules() +* 09/15/98 stephen Added getStaticClassID +* 12/03/99 aliu Moved data out of static table into icudata.dll. +* Hashtable replaced by new static data structures. +* 12/14/99 aliu Made GMT public. +* 08/15/01 grhoten Made GMT private and added the getGMT() function +************************************************************************** +*/ + +#ifndef TIMEZONE_H +#define TIMEZONE_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: TimeZone object + */ + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/ures.h" +#include "unicode/ucal.h" + +U_NAMESPACE_BEGIN + +class StringEnumeration; + +/** + * + * TimeZone represents a time zone offset, and also figures out daylight + * savings. + * + *

+ * Typically, you get a TimeZone using createDefault + * which creates a TimeZone based on the time zone where the program + * is running. For example, for a program running in Japan, createDefault + * creates a TimeZone object based on Japanese Standard Time. + * + *

+ * You can also get a TimeZone using createTimeZone along + * with a time zone ID. For instance, the time zone ID for the US Pacific + * Time zone is "America/Los_Angeles". So, you can get a Pacific Time TimeZone object + * with: + * \htmlonly

\endhtmlonly + *
+ * TimeZone *tz = TimeZone::createTimeZone("America/Los_Angeles");
+ * 
+ * \htmlonly
\endhtmlonly + * You can use the createEnumeration method to iterate through + * all the supported time zone IDs, or the getCanonicalID method to check + * if a time zone ID is supported or not. You can then choose a + * supported ID to get a TimeZone. + * If the time zone you want is not represented by one of the + * supported IDs, then you can create a custom time zone ID with + * the following syntax: + * + * \htmlonly
\endhtmlonly + *
+ * GMT[+|-]hh[[:]mm]
+ * 
+ * \htmlonly
\endhtmlonly + * + * For example, you might specify GMT+14:00 as a custom + * time zone ID. The TimeZone that is returned + * when you specify a custom time zone ID uses the specified + * offset from GMT(=UTC) and does not observe daylight saving + * time. For example, you might specify GMT+14:00 as a custom + * time zone ID to create a TimeZone representing 14 hours ahead + * of GMT (with no daylight saving time). In addition, + * getCanonicalID can also be used to + * normalize a custom time zone ID. + * + * TimeZone is an abstract class representing a time zone. A TimeZone is needed for + * Calendar to produce local time for a particular time zone. A TimeZone comprises + * three basic pieces of information: + *
    + *
  • A time zone offset; that, is the number of milliseconds to add or subtract + * from a time expressed in terms of GMT to convert it to the same time in that + * time zone (without taking daylight savings time into account).
  • + *
  • Logic necessary to take daylight savings time into account if daylight savings + * time is observed in that time zone (e.g., the days and hours on which daylight + * savings time begins and ends).
  • + *
  • An ID. This is a text string that uniquely identifies the time zone.
  • + *
+ * + * (Only the ID is actually implemented in TimeZone; subclasses of TimeZone may handle + * daylight savings time and GMT offset in different ways. Currently we have the following + * TimeZone subclasses: RuleBasedTimeZone, SimpleTimeZone, and VTimeZone.) + *

+ * The TimeZone class contains a static list containing a TimeZone object for every + * combination of GMT offset and daylight-savings time rules currently in use in the + * world, each with a unique ID. Each ID consists of a region (usually a continent or + * ocean) and a city in that region, separated by a slash, (for example, US Pacific + * Time is "America/Los_Angeles.") Because older versions of this class used + * three- or four-letter abbreviations instead, there is also a table that maps the older + * abbreviations to the newer ones (for example, "PST" maps to "America/Los_Angeles"). + * Anywhere the API requires an ID, you can use either form. + *

+ * To create a new TimeZone, you call the factory function TimeZone::createTimeZone() + * and pass it a time zone ID. You can use the createEnumeration() function to + * obtain a list of all the time zone IDs recognized by createTimeZone(). + *

+ * You can also use TimeZone::createDefault() to create a TimeZone. This function uses + * platform-specific APIs to produce a TimeZone for the time zone corresponding to + * the client's computer's physical location. For example, if you're in Japan (assuming + * your machine is set up correctly), TimeZone::createDefault() will return a TimeZone + * for Japanese Standard Time ("Asia/Tokyo"). + */ +class U_I18N_API TimeZone : public UObject { +public: + /** + * @stable ICU 2.0 + */ + virtual ~TimeZone(); + + /** + * Returns the "unknown" time zone. + * It behaves like the GMT/UTC time zone but has the + * UCAL_UNKNOWN_ZONE_ID = "Etc/Unknown". + * createTimeZone() returns a mutable clone of this time zone if the input ID is not recognized. + * + * @return the "unknown" time zone. + * @see UCAL_UNKNOWN_ZONE_ID + * @see createTimeZone + * @see getGMT + * @stable ICU 49 + */ + static const TimeZone& U_EXPORT2 getUnknown(); + + /** + * The GMT (=UTC) time zone has a raw offset of zero and does not use daylight + * savings time. This is a commonly used time zone. + * + *

Note: For backward compatibility reason, the ID used by the time + * zone returned by this method is "GMT", although the ICU's canonical + * ID for the GMT time zone is "Etc/GMT". + * + * @return the GMT/UTC time zone. + * @see getUnknown + * @stable ICU 2.0 + */ + static const TimeZone* U_EXPORT2 getGMT(void); + + /** + * Creates a TimeZone for the given ID. + * @param ID the ID for a TimeZone, such as "America/Los_Angeles", + * or a custom ID such as "GMT-8:00". + * @return the specified TimeZone, or a mutable clone of getUnknown() + * if the given ID cannot be understood or if the given ID is "Etc/Unknown". + * The return result is guaranteed to be non-nullptr. + * If you require that the specific zone asked for be returned, + * compare the result with getUnknown() or check the ID of the return result. + * @stable ICU 2.0 + */ + static TimeZone* U_EXPORT2 createTimeZone(const UnicodeString& ID); + + /** + * Returns an enumeration over system time zone IDs with the given + * filter conditions. + * @param zoneType The system time zone type. + * @param region The ISO 3166 two-letter country code or UN M.49 + * three-digit area code. When nullptr, no filtering + * done by region. + * @param rawOffset An offset from GMT in milliseconds, ignoring + * the effect of daylight savings time, if any. + * When nullptr, no filtering done by zone offset. + * @param ec Output param to filled in with a success or + * an error. + * @return an enumeration object, owned by the caller. + * @stable ICU 4.8 + */ + static StringEnumeration* U_EXPORT2 createTimeZoneIDEnumeration( + USystemTimeZoneType zoneType, + const char* region, + const int32_t* rawOffset, + UErrorCode& ec); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Returns an enumeration over all recognized time zone IDs. (i.e., + * all strings that createTimeZone() accepts) + * + * @return an enumeration object, owned by the caller. + * @deprecated ICU 70 Use createEnumeration(UErrorCode&) instead. + */ + static StringEnumeration* U_EXPORT2 createEnumeration(); +#endif // U_HIDE_DEPRECATED_API + + /** + * Returns an enumeration over all recognized time zone IDs. (i.e., + * all strings that createTimeZone() accepts) + * + * @param status Receives the status. + * @return an enumeration object, owned by the caller. + * @stable ICU 70 + */ + static StringEnumeration* U_EXPORT2 createEnumeration(UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Returns an enumeration over time zone IDs with a given raw + * offset from GMT. There may be several times zones with the + * same GMT offset that differ in the way they handle daylight + * savings time. For example, the state of Arizona doesn't + * observe daylight savings time. If you ask for the time zone + * IDs corresponding to GMT-7:00, you'll get back an enumeration + * over two time zone IDs: "America/Denver," which corresponds to + * Mountain Standard Time in the winter and Mountain Daylight Time + * in the summer, and "America/Phoenix", which corresponds to + * Mountain Standard Time year-round, even in the summer. + * + * @param rawOffset an offset from GMT in milliseconds, ignoring + * the effect of daylight savings time, if any + * @return an enumeration object, owned by the caller + * @deprecated ICU 70 Use createEnumerationForRawOffset(int32_t,UErrorCode&) instead. + */ + static StringEnumeration* U_EXPORT2 createEnumeration(int32_t rawOffset); +#endif // U_HIDE_DEPRECATED_API + + /** + * Returns an enumeration over time zone IDs with a given raw + * offset from GMT. There may be several times zones with the + * same GMT offset that differ in the way they handle daylight + * savings time. For example, the state of Arizona doesn't + * observe daylight savings time. If you ask for the time zone + * IDs corresponding to GMT-7:00, you'll get back an enumeration + * over two time zone IDs: "America/Denver," which corresponds to + * Mountain Standard Time in the winter and Mountain Daylight Time + * in the summer, and "America/Phoenix", which corresponds to + * Mountain Standard Time year-round, even in the summer. + * + * @param rawOffset an offset from GMT in milliseconds, ignoring + * the effect of daylight savings time, if any + * @param status Receives the status. + * @return an enumeration object, owned by the caller + * @stable ICU 70 + */ + static StringEnumeration* U_EXPORT2 createEnumerationForRawOffset(int32_t rawOffset, UErrorCode& status); + +#ifndef U_HIDE_DEPRECATED_API + /** + * Returns an enumeration over time zone IDs associated with the + * given region. Some zones are affiliated with no region + * (e.g., "UTC"); these may also be retrieved, as a group. + * + * @param region The ISO 3166 two-letter country code, or nullptr to + * retrieve zones not affiliated with any region. + * @return an enumeration object, owned by the caller + * @deprecated ICU 70 Use createEnumerationForRegion(const char*,UErrorCode&) instead. + */ + static StringEnumeration* U_EXPORT2 createEnumeration(const char* region); +#endif // U_HIDE_DEPRECATED_API + + /** + * Returns an enumeration over time zone IDs associated with the + * given region. Some zones are affiliated with no region + * (e.g., "UTC"); these may also be retrieved, as a group. + * + * @param region The ISO 3166 two-letter country code, or nullptr to + * retrieve zones not affiliated with any region. + * @param status Receives the status. + * @return an enumeration object, owned by the caller + * @stable ICU 70 + */ + static StringEnumeration* U_EXPORT2 createEnumerationForRegion(const char* region, UErrorCode& status); + + /** + * Returns the number of IDs in the equivalency group that + * includes the given ID. An equivalency group contains zones + * that have the same GMT offset and rules. + * + *

The returned count includes the given ID; it is always >= 1. + * The given ID must be a system time zone. If it is not, returns + * zero. + * @param id a system time zone ID + * @return the number of zones in the equivalency group containing + * 'id', or zero if 'id' is not a valid system ID + * @see #getEquivalentID + * @stable ICU 2.0 + */ + static int32_t U_EXPORT2 countEquivalentIDs(const UnicodeString& id); + + /** + * Returns an ID in the equivalency group that + * includes the given ID. An equivalency group contains zones + * that have the same GMT offset and rules. + * + *

The given index must be in the range 0..n-1, where n is the + * value returned by countEquivalentIDs(id). For + * some value of 'index', the returned value will be equal to the + * given id. If the given id is not a valid system time zone, or + * if 'index' is out of range, then returns an empty string. + * @param id a system time zone ID + * @param index a value from 0 to n-1, where n is the value + * returned by countEquivalentIDs(id) + * @return the ID of the index-th zone in the equivalency group + * containing 'id', or an empty string if 'id' is not a valid + * system ID or 'index' is out of range + * @see #countEquivalentIDs + * @stable ICU 2.0 + */ + static const UnicodeString U_EXPORT2 getEquivalentID(const UnicodeString& id, + int32_t index); + + /** + * Creates an instance of TimeZone detected from the current host + * system configuration. If the host system detection routines fail, + * or if they specify a TimeZone or TimeZone offset which is not + * recognized, then the special TimeZone "Etc/Unknown" is returned. + * + * Note that ICU4C does not change the default time zone unless + * `TimeZone::adoptDefault(TimeZone*)` or + * `TimeZone::setDefault(const TimeZone&)` is explicitly called by a + * user. This method does not update the current ICU's default, + * and may return a different TimeZone from the one returned by + * `TimeZone::createDefault()`. + * + *

This function is not thread safe.

+ * + * @return A new instance of TimeZone detected from the current host system + * configuration. + * @see adoptDefault + * @see setDefault + * @see createDefault + * @see getUnknown + * @stable ICU 55 + */ + static TimeZone* U_EXPORT2 detectHostTimeZone(); + + /** + * Creates a new copy of the default TimeZone for this host. Unless the default time + * zone has already been set using adoptDefault() or setDefault(), the default is + * determined by querying the host system configuration. If the host system detection + * routines fail, or if they specify a TimeZone or TimeZone offset which is not + * recognized, then the special TimeZone "Etc/Unknown" is instantiated and made the + * default. + * + * @return A default TimeZone. Clients are responsible for deleting the time zone + * object returned. + * @see getUnknown + * @stable ICU 2.0 + */ + static TimeZone* U_EXPORT2 createDefault(void); + +#ifndef U_HIDE_INTERNAL_API + /** + * If the locale contains the timezone keyword, creates a copy of that TimeZone. + * Otherwise, create the default timezone. + * + * @param locale a locale which may contains 'timezone' keyword/value. + * @return A TimeZone. Clients are responsible for deleting the time zone + * object returned. + * @internal + */ + static TimeZone* U_EXPORT2 forLocaleOrDefault(const Locale& locale); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Sets the default time zone (i.e., what's returned by createDefault()) to be the + * specified time zone. If nullptr is specified for the time zone, the default time + * zone is set to the default host time zone. This call adopts the TimeZone object + * passed in; the client is no longer responsible for deleting it. + * + * @param zone A pointer to the new TimeZone object to use as the default. + * @stable ICU 2.0 + */ + static void U_EXPORT2 adoptDefault(TimeZone* zone); + +#ifndef U_HIDE_SYSTEM_API + /** + * Same as adoptDefault(), except that the TimeZone object passed in is NOT adopted; + * the caller remains responsible for deleting it. + * + * @param zone The given timezone. + * @system + * @stable ICU 2.0 + */ + static void U_EXPORT2 setDefault(const TimeZone& zone); +#endif /* U_HIDE_SYSTEM_API */ + + /** + * Returns the timezone data version currently used by ICU. + * @param status Output param to filled in with a success or an error. + * @return the version string, such as "2007f" + * @stable ICU 3.8 + */ + static const char* U_EXPORT2 getTZDataVersion(UErrorCode& status); + + /** + * Returns the canonical system timezone ID or the normalized + * custom time zone ID for the given time zone ID. + * @param id The input time zone ID to be canonicalized. + * @param canonicalID Receives the canonical system time zone ID + * or the custom time zone ID in normalized format. + * @param status Receives the status. When the given time zone ID + * is neither a known system time zone ID nor a + * valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR + * is set. + * @return A reference to the result. + * @stable ICU 4.0 + */ + static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id, + UnicodeString& canonicalID, UErrorCode& status); + + /** + * Returns the canonical system time zone ID or the normalized + * custom time zone ID for the given time zone ID. + * @param id The input time zone ID to be canonicalized. + * @param canonicalID Receives the canonical system time zone ID + * or the custom time zone ID in normalized format. + * @param isSystemID Receives if the given ID is a known system + * time zone ID. + * @param status Receives the status. When the given time zone ID + * is neither a known system time zone ID nor a + * valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR + * is set. + * @return A reference to the result. + * @stable ICU 4.0 + */ + static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id, + UnicodeString& canonicalID, UBool& isSystemID, UErrorCode& status); + + /** + * Converts a system time zone ID to an equivalent Windows time zone ID. For example, + * Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles". + * + *

There are system time zones that cannot be mapped to Windows zones. When the input + * system time zone ID is unknown or unmappable to a Windows time zone, then the result will be + * empty, but the operation itself remains successful (no error status set on return). + * + *

This implementation utilizes + * Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, + * please read the ICU user guide section + * Updating the Time Zone Data. + * + * @param id A system time zone ID. + * @param winid Receives a Windows time zone ID. When the input system time zone ID is unknown + * or unmappable to a Windows time zone ID, then an empty string is set on return. + * @param status Receives the status. + * @return A reference to the result (winid). + * @see getIDForWindowsID + * + * @stable ICU 52 + */ + static UnicodeString& U_EXPORT2 getWindowsID(const UnicodeString& id, + UnicodeString& winid, UErrorCode& status); + + /** + * Converts a Windows time zone ID to an equivalent system time zone ID + * for a region. For example, system time zone ID "America/Los_Angeles" is returned + * for input Windows ID "Pacific Standard Time" and region "US" (or null), + * "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and + * region "CA". + * + *

Not all Windows time zones can be mapped to system time zones. When the input + * Windows time zone ID is unknown or unmappable to a system time zone, then the result + * will be empty, but the operation itself remains successful (no error status set on return). + * + *

This implementation utilizes + * Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, + * please read the ICU user guide section + * Updating the Time Zone Data. + * + * @param winid A Windows time zone ID. + * @param region A NUL-terminated region code, or nullptr if no regional preference. + * @param id Receives a system time zone ID. When the input Windows time zone ID is unknown + * or unmappable to a system time zone ID, then an empty string is set on return. + * @param status Receives the status. + * @return A reference to the result (id). + * @see getWindowsID + * + * @stable ICU 52 + */ + static UnicodeString& U_EXPORT2 getIDForWindowsID(const UnicodeString& winid, const char* region, + UnicodeString& id, UErrorCode& status); + + /** + * Returns true if the two TimeZones are equal. (The TimeZone version only compares + * IDs, but subclasses are expected to also compare the fields they add.) + * + * @param that The TimeZone object to be compared with. + * @return true if the given TimeZone is equal to this TimeZone; false + * otherwise. + * @stable ICU 2.0 + */ + virtual bool operator==(const TimeZone& that) const; + + /** + * Returns true if the two TimeZones are NOT equal; that is, if operator==() returns + * false. + * + * @param that The TimeZone object to be compared with. + * @return true if the given TimeZone is not equal to this TimeZone; false + * otherwise. + * @stable ICU 2.0 + */ + bool operator!=(const TimeZone& that) const {return !operator==(that);} + + /** + * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time in this time zone, taking daylight savings time into + * account) as of a particular reference date. The reference date is used to determine + * whether daylight savings time is in effect and needs to be figured into the offset + * that is returned (in other words, what is the adjusted GMT offset in this time zone + * at this particular date and time?). For the time zones produced by createTimeZone(), + * the reference data is specified according to the Gregorian calendar, and the date + * and time fields are local standard time. + * + *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, + * which returns both the raw and the DST offset for a given time. This method + * is retained only for backward compatibility. + * + * @param era The reference date's era + * @param year The reference date's year + * @param month The reference date's month (0-based; 0 is January) + * @param day The reference date's day-in-month (1-based) + * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) + * @param millis The reference date's milliseconds in day, local standard time + * @param status Output param to filled in with a success or an error. + * @return The offset in milliseconds to add to GMT to get local time. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const = 0; + + /** + * Gets the time zone offset, for current date, modified in case of + * daylight savings. This is the offset to add *to* UTC to get local time. + * + *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, + * which returns both the raw and the DST offset for a given time. This method + * is retained only for backward compatibility. + * + * @param era the era of the given date. + * @param year the year in the given date. + * @param month the month in the given date. + * Month is 0-based. e.g., 0 for January. + * @param day the day-in-month of the given date. + * @param dayOfWeek the day-of-week of the given date. + * @param milliseconds the millis in day in standard local time. + * @param monthLength the length of the given month in days. + * @param status Output param to filled in with a success or an error. + * @return the offset to add *to* GMT to get local time. + * @stable ICU 2.0 + */ + virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, + uint8_t dayOfWeek, int32_t milliseconds, + int32_t monthLength, UErrorCode& status) const = 0; + + /** + * Returns the time zone raw and GMT offset for the given moment + * in time. Upon return, local-millis = GMT-millis + rawOffset + + * dstOffset. All computations are performed in the proleptic + * Gregorian calendar. The default implementation in the TimeZone + * class delegates to the 8-argument getOffset(). + * + * @param date moment in time for which to return offsets, in + * units of milliseconds from January 1, 1970 0:00 GMT, either GMT + * time or local wall time, depending on `local'. + * @param local if true, `date' is local wall time; otherwise it + * is in GMT time. + * @param rawOffset output parameter to receive the raw offset, that + * is, the offset not including DST adjustments + * @param dstOffset output parameter to receive the DST offset, + * that is, the offset to be added to `rawOffset' to obtain the + * total offset between local and GMT time. If DST is not in + * effect, this value is zero; otherwise it is a positive value, + * typically one hour. + * @param ec input-output error code + * + * @stable ICU 2.8 + */ + virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, + int32_t& dstOffset, UErrorCode& ec) const; + + /** + * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @param offsetMillis The new raw GMT offset for this time zone. + * @stable ICU 2.0 + */ + virtual void setRawOffset(int32_t offsetMillis) = 0; + + /** + * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add + * to GMT to get local time, before taking daylight savings time into account). + * + * @return The TimeZone's raw GMT offset. + * @stable ICU 2.0 + */ + virtual int32_t getRawOffset(void) const = 0; + + /** + * Fills in "ID" with the TimeZone's ID. + * + * @param ID Receives this TimeZone's ID. + * @return A reference to 'ID' + * @stable ICU 2.0 + */ + UnicodeString& getID(UnicodeString& ID) const; + + /** + * Sets the TimeZone's ID to the specified value. This doesn't affect any other + * fields (for example, if you say< + * blockquote>

+     * .     TimeZone* foo = TimeZone::createTimeZone("America/New_York");
+     * .     foo.setID("America/Los_Angeles");
+     * 
\htmlonly\endhtmlonly + * the time zone's GMT offset and daylight-savings rules don't change to those for + * Los Angeles. They're still those for New York. Only the ID has changed.) + * + * @param ID The new time zone ID. + * @stable ICU 2.0 + */ + void setID(const UnicodeString& ID); + + /** + * Enum for use with getDisplayName + * @stable ICU 2.4 + */ + enum EDisplayType { + /** + * Selector for short display name + * @stable ICU 2.4 + */ + SHORT = 1, + /** + * Selector for long display name + * @stable ICU 2.4 + */ + LONG, + /** + * Selector for short generic display name + * @stable ICU 4.4 + */ + SHORT_GENERIC, + /** + * Selector for long generic display name + * @stable ICU 4.4 + */ + LONG_GENERIC, + /** + * Selector for short display name derived + * from time zone offset + * @stable ICU 4.4 + */ + SHORT_GMT, + /** + * Selector for long display name derived + * from time zone offset + * @stable ICU 4.4 + */ + LONG_GMT, + /** + * Selector for short display name derived + * from the time zone's fallback name + * @stable ICU 4.4 + */ + SHORT_COMMONLY_USED, + /** + * Selector for long display name derived + * from the time zone's fallback name + * @stable ICU 4.4 + */ + GENERIC_LOCATION + }; + + /** + * Returns a name of this time zone suitable for presentation to the user + * in the default locale. + * This method returns the long name, not including daylight savings. + * If the display name is not available for the locale, + * then this method returns a string in the localized GMT offset format + * such as GMT[+-]HH:mm. + * @param result the human-readable name of this time zone in the default locale. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName(UnicodeString& result) const; + + /** + * Returns a name of this time zone suitable for presentation to the user + * in the specified locale. + * This method returns the long name, not including daylight savings. + * If the display name is not available for the locale, + * then this method returns a string in the localized GMT offset format + * such as GMT[+-]HH:mm. + * @param locale the locale in which to supply the display name. + * @param result the human-readable name of this time zone in the given locale + * or in the default locale if the given locale is not recognized. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName(const Locale& locale, UnicodeString& result) const; + + /** + * Returns a name of this time zone suitable for presentation to the user + * in the default locale. + * If the display name is not available for the locale, + * then this method returns a string in the localized GMT offset format + * such as GMT[+-]HH:mm. + * @param inDaylight if true, return the daylight savings name. + * @param style + * @param result the human-readable name of this time zone in the default locale. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName(UBool inDaylight, EDisplayType style, UnicodeString& result) const; + + /** + * Returns a name of this time zone suitable for presentation to the user + * in the specified locale. + * If the display name is not available for the locale, + * then this method returns a string in the localized GMT offset format + * such as GMT[+-]HH:mm. + * @param inDaylight if true, return the daylight savings name. + * @param style + * @param locale the locale in which to supply the display name. + * @param result the human-readable name of this time zone in the given locale + * or in the default locale if the given locale is not recognized. + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + UnicodeString& getDisplayName(UBool inDaylight, EDisplayType style, const Locale& locale, UnicodeString& result) const; + + /** + * Queries if this time zone uses daylight savings time. + * @return true if this time zone uses daylight savings time, + * false, otherwise. + *

Note:The default implementation of + * ICU TimeZone uses the tz database, which supports historic + * rule changes, for system time zones. With the implementation, + * there are time zones that used daylight savings time in the + * past, but no longer used currently. For example, Asia/Tokyo has + * never used daylight savings time since 1951. Most clients would + * expect that this method to return false for such case. + * The default implementation of this method returns true + * when the time zone uses daylight savings time in the current + * (Gregorian) calendar year. + *

In Java 7, observesDaylightTime() was added in + * addition to useDaylightTime(). In Java, useDaylightTime() + * only checks if daylight saving time is observed by the last known + * rule. This specification might not be what most users would expect + * if daylight saving time is currently observed, but not scheduled + * in future. In this case, Java's userDaylightTime() returns + * false. To resolve the issue, Java 7 added observesDaylightTime(), + * which takes the current rule into account. The method observesDaylightTime() + * was added in ICU4J for supporting API signature compatibility with JDK. + * In general, ICU4C also provides JDK compatible methods, but the current + * implementation userDaylightTime() serves the purpose + * (takes the current rule into account), observesDaylightTime() + * is not added in ICU4C. In addition to useDaylightTime(), ICU4C + * BasicTimeZone class (Note that TimeZone::createTimeZone(const UnicodeString &ID) + * always returns a BasicTimeZone) provides a series of methods allowing + * historic and future time zone rule iteration, so you can check if daylight saving + * time is observed or not within a given period. + * + * @stable ICU 2.0 + */ + virtual UBool useDaylightTime(void) const = 0; + +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * Queries if the given date is in daylight savings time in + * this time zone. + * This method is wasteful since it creates a new GregorianCalendar and + * deletes it each time it is called. This is a deprecated method + * and provided only for Java compatibility. + * + * @param date the given UDate. + * @param status Output param filled in with success/error code. + * @return true if the given date is in daylight savings time, + * false, otherwise. + * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. + */ + virtual UBool inDaylightTime(UDate date, UErrorCode& status) const = 0; +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Returns true if this zone has the same rule and offset as another zone. + * That is, if this zone differs only in ID, if at all. + * @param other the TimeZone object to be compared with + * @return true if the given zone is the same as this one, + * with the possible exception of the ID + * @stable ICU 2.0 + */ + virtual UBool hasSameRules(const TimeZone& other) const; + + /** + * Clones TimeZone objects polymorphically. Clients are responsible for deleting + * the TimeZone object cloned. + * + * @return A new copy of this TimeZone object. + * @stable ICU 2.0 + */ + virtual TimeZone* clone() const = 0; + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. This method is to + * implement a simple version of RTTI, since not all C++ compilers support genuine + * RTTI. Polymorphic operator==() and clone() methods call this method. + *

+ * Concrete subclasses of TimeZone must use the UOBJECT_DEFINE_RTTI_IMPLEMENTATION + * macro from uobject.h in their implementation to provide correct RTTI information. + * @return The class ID for this object. All objects of a given class have the + * same class ID. Objects of other classes have different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Returns the amount of time to be added to local standard time + * to get local wall clock time. + *

+ * The default implementation always returns 3600000 milliseconds + * (i.e., one hour) if this time zone observes Daylight Saving + * Time. Otherwise, 0 (zero) is returned. + *

+ * If an underlying TimeZone implementation subclass supports + * historical Daylight Saving Time changes, this method returns + * the known latest daylight saving value. + * + * @return the amount of saving time in milliseconds + * @stable ICU 3.6 + */ + virtual int32_t getDSTSavings() const; + + /** + * Gets the region code associated with the given + * system time zone ID. The region code is either ISO 3166 + * 2-letter country code or UN M.49 3-digit area code. + * When the time zone is not associated with a specific location, + * for example - "Etc/UTC", "EST5EDT", then this method returns + * "001" (UN M.49 area code for World). + * + * @param id The system time zone ID. + * @param region Output buffer for receiving the region code. + * @param capacity The size of the output buffer. + * @param status Receives the status. When the given time zone ID + * is not a known system time zone ID, + * U_ILLEGAL_ARGUMENT_ERROR is set. + * @return The length of the output region code. + * @stable ICU 4.8 + */ + static int32_t U_EXPORT2 getRegion(const UnicodeString& id, + char *region, int32_t capacity, UErrorCode& status); + +protected: + + /** + * Default constructor. ID is initialized to the empty string. + * @stable ICU 2.0 + */ + TimeZone(); + + /** + * Construct a TimeZone with a given ID. + * @param id a system time zone ID + * @stable ICU 2.0 + */ + TimeZone(const UnicodeString &id); + + /** + * Copy constructor. + * @param source the object to be copied. + * @stable ICU 2.0 + */ + TimeZone(const TimeZone& source); + + /** + * Default assignment operator. + * @param right the object to be copied. + * @stable ICU 2.0 + */ + TimeZone& operator=(const TimeZone& right); + +#ifndef U_HIDE_INTERNAL_API + /** + * Utility function. For internally loading rule data. + * @param top Top resource bundle for tz data + * @param ruleid ID of rule to load + * @param oldbundle Old bundle to reuse or nullptr + * @param status Status parameter + * @return either a new bundle or *oldbundle + * @internal + */ + static UResourceBundle* loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode&status); +#endif /* U_HIDE_INTERNAL_API */ + +private: + friend class ZoneMeta; + + + static TimeZone* createCustomTimeZone(const UnicodeString&); // Creates a time zone based on the string. + + /** + * Finds the given ID in the Olson tzdata. If the given ID is found in the tzdata, + * returns the pointer to the ID resource. This method is exposed through ZoneMeta class + * for ICU internal implementation and useful for building hashtable using a time zone + * ID as a key. + * @param id zone id string + * @return the pointer of the ID resource, or nullptr. + */ + static const char16_t* findID(const UnicodeString& id); + + /** + * Resolve a link in Olson tzdata. When the given id is known and it's not a link, + * the id itself is returned. When the given id is known and it is a link, then + * dereferenced zone id is returned. When the given id is unknown, then it returns + * nullptr. + * @param id zone id string + * @return the dereferenced zone or nullptr + */ + static const char16_t* dereferOlsonLink(const UnicodeString& id); + + /** + * Returns the region code associated with the given zone, + * or nullptr if the zone is not known. + * @param id zone id string + * @return the region associated with the given zone + */ + static const char16_t* getRegion(const UnicodeString& id); + + public: +#ifndef U_HIDE_INTERNAL_API + /** + * Returns the region code associated with the given zone, + * or nullptr if the zone is not known. + * @param id zone id string + * @param status Status parameter + * @return the region associated with the given zone + * @internal + */ + static const char16_t* getRegion(const UnicodeString& id, UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + private: + /** + * Parses the given custom time zone identifier + * @param id id A string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or + * GMT[+-]hh. + * @param sign Receives parsed sign, 1 for positive, -1 for negative. + * @param hour Receives parsed hour field + * @param minute Receives parsed minute field + * @param second Receives parsed second field + * @return Returns true when the given custom id is valid. + */ + static UBool parseCustomID(const UnicodeString& id, int32_t& sign, int32_t& hour, + int32_t& minute, int32_t& second); + + /** + * Parse a custom time zone identifier and return the normalized + * custom time zone identifier for the given custom id string. + * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or + * GMT[+-]hh. + * @param normalized Receives the normalized custom ID + * @param status Receives the status. When the input ID string is invalid, + * U_ILLEGAL_ARGUMENT_ERROR is set. + * @return The normalized custom id string. + */ + static UnicodeString& getCustomID(const UnicodeString& id, UnicodeString& normalized, + UErrorCode& status); + + /** + * Returns the normalized custom time zone ID for the given offset fields. + * @param hour offset hours + * @param min offset minutes + * @param sec offset seconds + * @param negative sign of the offset, true for negative offset. + * @param id Receives the format result (normalized custom ID) + * @return The reference to id + */ + static UnicodeString& formatCustomID(int32_t hour, int32_t min, int32_t sec, + UBool negative, UnicodeString& id); + + UnicodeString fID; // this time zone's ID + + friend class TZEnumeration; +}; + + +// ------------------------------------- + +inline UnicodeString& +TimeZone::getID(UnicodeString& ID) const +{ + ID = fID; + return ID; +} + +// ------------------------------------- + +inline void +TimeZone::setID(const UnicodeString& ID) +{ + fID = ID; +} +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif //_TIMEZONE +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmunit.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmunit.h new file mode 100644 index 0000000000000000000000000000000000000000..24abb49f1982747943748f00eed62c18850c3f31 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmunit.h @@ -0,0 +1,142 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2009-2016, International Business Machines Corporation, * + * Google, and others. All Rights Reserved. * + ******************************************************************************* + */ + +#ifndef __TMUNIT_H__ +#define __TMUNIT_H__ + + +/** + * \file + * \brief C++ API: time unit object + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/measunit.h" + +#if !UCONFIG_NO_FORMATTING + +U_NAMESPACE_BEGIN + +/** + * Measurement unit for time units. + * @see TimeUnitAmount + * @see TimeUnit + * @stable ICU 4.2 + */ +class U_I18N_API TimeUnit: public MeasureUnit { +public: + /** + * Constants for all the time units we supported. + * @stable ICU 4.2 + */ + enum UTimeUnitFields { + UTIMEUNIT_YEAR, + UTIMEUNIT_MONTH, + UTIMEUNIT_DAY, + UTIMEUNIT_WEEK, + UTIMEUNIT_HOUR, + UTIMEUNIT_MINUTE, + UTIMEUNIT_SECOND, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UTimeUnitFields value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UTIMEUNIT_FIELD_COUNT +#endif // U_HIDE_DEPRECATED_API + }; + + /** + * Create Instance. + * @param timeUnitField time unit field based on which the instance + * is created. + * @param status input-output error code. + * If the timeUnitField is invalid, + * then this will be set to U_ILLEGAL_ARGUMENT_ERROR. + * @return a TimeUnit instance + * @stable ICU 4.2 + */ + static TimeUnit* U_EXPORT2 createInstance(UTimeUnitFields timeUnitField, + UErrorCode& status); + + + /** + * Override clone. + * @stable ICU 4.2 + */ + virtual TimeUnit* clone() const override; + + /** + * Copy operator. + * @stable ICU 4.2 + */ + TimeUnit(const TimeUnit& other); + + /** + * Assignment operator. + * @stable ICU 4.2 + */ + TimeUnit& operator=(const TimeUnit& other); + + /** + * Returns a unique class ID for this object POLYMORPHICALLY. + * This method implements a simple form of RTTI used by ICU. + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 4.2 + */ + virtual UClassID getDynamicClassID() const override; + + /** + * Returns the class ID for this class. This is used to compare to + * the return value of getDynamicClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 4.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + + + /** + * Get time unit field. + * @return time unit field. + * @stable ICU 4.2 + */ + UTimeUnitFields getTimeUnitField() const; + + /** + * Destructor. + * @stable ICU 4.2 + */ + virtual ~TimeUnit(); + +private: + UTimeUnitFields fTimeUnitField; + + /** + * Constructor + * @internal (private) + */ + TimeUnit(UTimeUnitFields timeUnitField); + +}; + + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __TMUNIT_H__ +//eof +// diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutamt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutamt.h new file mode 100644 index 0000000000000000000000000000000000000000..88e892fb0c26c2dcbd21b6d770c55c3900a29022 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutamt.h @@ -0,0 +1,176 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2009-2010, Google, International Business Machines Corporation and * + * others. All Rights Reserved. * + ******************************************************************************* + */ + +#ifndef __TMUTAMT_H__ +#define __TMUTAMT_H__ + + +/** + * \file + * \brief C++ API: time unit amount object. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/measure.h" +#include "unicode/tmunit.h" + +U_NAMESPACE_BEGIN + + +/** + * Express a duration as a time unit and number. Patterned after Currency. + * @see TimeUnitAmount + * @see TimeUnitFormat + * @stable ICU 4.2 + */ +class U_I18N_API TimeUnitAmount: public Measure { +public: + /** + * Construct TimeUnitAmount object with the given number and the + * given time unit. + * @param number a numeric object; number.isNumeric() must be true + * @param timeUnitField the time unit field of a time unit + * @param status the input-output error code. + * If the number is not numeric or the timeUnitField + * is not valid, + * then this will be set to a failing value: + * U_ILLEGAL_ARGUMENT_ERROR. + * @stable ICU 4.2 + */ + TimeUnitAmount(const Formattable& number, + TimeUnit::UTimeUnitFields timeUnitField, + UErrorCode& status); + + /** + * Construct TimeUnitAmount object with the given numeric amount and the + * given time unit. + * @param amount a numeric amount. + * @param timeUnitField the time unit field on which a time unit amount + * object will be created. + * @param status the input-output error code. + * If the timeUnitField is not valid, + * then this will be set to a failing value: + * U_ILLEGAL_ARGUMENT_ERROR. + * @stable ICU 4.2 + */ + TimeUnitAmount(double amount, TimeUnit::UTimeUnitFields timeUnitField, + UErrorCode& status); + + + /** + * Copy constructor + * @stable ICU 4.2 + */ + TimeUnitAmount(const TimeUnitAmount& other); + + + /** + * Assignment operator + * @stable ICU 4.2 + */ + TimeUnitAmount& operator=(const TimeUnitAmount& other); + + + /** + * Clone. + * @return a polymorphic clone of this object. The result will have the same class as returned by getDynamicClassID(). + * @stable ICU 4.2 + */ + virtual TimeUnitAmount* clone() const override; + + + /** + * Destructor + * @stable ICU 4.2 + */ + virtual ~TimeUnitAmount(); + + + /** + * Equality operator. + * @param other the object to compare to. + * @return true if this object is equal to the given object. + * @stable ICU 4.2 + */ + virtual bool operator==(const UObject& other) const; + + + /** + * Not-equality operator. + * @param other the object to compare to. + * @return true if this object is not equal to the given object. + * @stable ICU 4.2 + */ + bool operator!=(const UObject& other) const; + + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 4.2 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 4.2 + */ + virtual UClassID getDynamicClassID(void) const override; + + + /** + * Get the time unit. + * @return time unit object. + * @stable ICU 4.2 + */ + const TimeUnit& getTimeUnit() const; + + /** + * Get the time unit field value. + * @return time unit field value. + * @stable ICU 4.2 + */ + TimeUnit::UTimeUnitFields getTimeUnitField() const; +}; + + + +inline bool +TimeUnitAmount::operator!=(const UObject& other) const { + return !operator==(other); +} + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __TMUTAMT_H__ +//eof +// diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..02e0563a010e63d738db67303944aea4c43a2f83 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tmutfmt.h @@ -0,0 +1,238 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 2008-2014, Google, International Business Machines Corporation + * and others. All Rights Reserved. + ******************************************************************************* + */ + +#ifndef __TMUTFMT_H__ +#define __TMUTFMT_H__ + +#include "unicode/utypes.h" + +/** + * \file + * \brief C++ API: Format and parse duration in single time unit + */ + + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/unistr.h" +#include "unicode/tmunit.h" +#include "unicode/tmutamt.h" +#include "unicode/measfmt.h" +#include "unicode/numfmt.h" +#include "unicode/plurrule.h" + +#ifndef U_HIDE_DEPRECATED_API + +/** + * Constants for various styles. + * There are 2 styles: full name and abbreviated name. + * For example, for English, the full name for hour duration is "3 hours", + * and the abbreviated name is "3 hrs". + * @deprecated ICU 53 Use MeasureFormat and UMeasureFormatWidth instead. + */ +enum UTimeUnitFormatStyle { + /** @deprecated ICU 53 */ + UTMUTFMT_FULL_STYLE, + /** @deprecated ICU 53 */ + UTMUTFMT_ABBREVIATED_STYLE, + /** @deprecated ICU 53 */ + UTMUTFMT_FORMAT_STYLE_COUNT +}; +typedef enum UTimeUnitFormatStyle UTimeUnitFormatStyle; /**< @deprecated ICU 53 */ + + +U_NAMESPACE_BEGIN + +class Hashtable; +class UVector; + +struct TimeUnitFormatReadSink; + +/** + * Format or parse a TimeUnitAmount, using plural rules for the units where available. + * + *

+ * Code Sample: + *

+ *   // create time unit amount instance - a combination of Number and time unit
+ *   UErrorCode status = U_ZERO_ERROR;
+ *   TimeUnitAmount* source = new TimeUnitAmount(2, TimeUnit::UTIMEUNIT_YEAR, status);
+ *   // create time unit format instance
+ *   TimeUnitFormat* format = new TimeUnitFormat(Locale("en"), status);
+ *   // format a time unit amount
+ *   UnicodeString formatted;
+ *   Formattable formattable;
+ *   if (U_SUCCESS(status)) {
+ *       formattable.adoptObject(source);
+ *       formatted = ((Format*)format)->format(formattable, formatted, status);
+ *       Formattable result;
+ *       ((Format*)format)->parseObject(formatted, result, status);
+ *       if (U_SUCCESS(status)) {
+ *           assert (result == formattable);
+ *       }
+ *   }
+ * 
+ * + *

+ * @see TimeUnitAmount + * @see TimeUnitFormat + * @deprecated ICU 53 Use the MeasureFormat class instead. + */ +class U_I18N_API TimeUnitFormat: public MeasureFormat { +public: + + /** + * Create TimeUnitFormat with default locale, and full name style. + * Use setLocale and/or setFormat to modify. + * @deprecated ICU 53 + */ + TimeUnitFormat(UErrorCode& status); + + /** + * Create TimeUnitFormat given locale, and full name style. + * @deprecated ICU 53 + */ + TimeUnitFormat(const Locale& locale, UErrorCode& status); + + /** + * Create TimeUnitFormat given locale and style. + * @deprecated ICU 53 + */ + TimeUnitFormat(const Locale& locale, UTimeUnitFormatStyle style, UErrorCode& status); + + /** + * Copy constructor. + * @deprecated ICU 53 + */ + TimeUnitFormat(const TimeUnitFormat&); + + /** + * deconstructor + * @deprecated ICU 53 + */ + virtual ~TimeUnitFormat(); + + /** + * Clone this Format object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @deprecated ICU 53 + */ + virtual TimeUnitFormat* clone() const override; + + /** + * Assignment operator + * @deprecated ICU 53 + */ + TimeUnitFormat& operator=(const TimeUnitFormat& other); + + /** + * Set the locale used for formatting or parsing. + * @param locale the locale to be set + * @param status output param set to success/failure code on exit + * @deprecated ICU 53 + */ + void setLocale(const Locale& locale, UErrorCode& status); + + + /** + * Set the number format used for formatting or parsing. + * @param format the number formatter to be set + * @param status output param set to success/failure code on exit + * @deprecated ICU 53 + */ + void setNumberFormat(const NumberFormat& format, UErrorCode& status); + + /** + * Parse a TimeUnitAmount. + * @see Format#parseObject(const UnicodeString&, Formattable&, ParsePosition&) const; + * @deprecated ICU 53 + */ + virtual void parseObject(const UnicodeString& source, + Formattable& result, + ParsePosition& pos) const override; + + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @deprecated ICU 53 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @deprecated ICU 53 + */ + virtual UClassID getDynamicClassID(void) const override; + +private: + Hashtable* fTimeUnitToCountToPatterns[TimeUnit::UTIMEUNIT_FIELD_COUNT]; + UTimeUnitFormatStyle fStyle; + + void create(UTimeUnitFormatStyle style, UErrorCode& status); + + // it might actually be simpler to make them Decimal Formats later. + // initialize all private data members + void setup(UErrorCode& status); + + // initialize data member without fill in data for fTimeUnitToCountToPattern + void initDataMembers(UErrorCode& status); + + // initialize fTimeUnitToCountToPatterns from current locale's resource. + void readFromCurrentLocale(UTimeUnitFormatStyle style, const char* key, const UVector& pluralCounts, + UErrorCode& status); + + // check completeness of fTimeUnitToCountToPatterns against all time units, + // and all plural rules, fill in fallback as necessary. + void checkConsistency(UTimeUnitFormatStyle style, const char* key, UErrorCode& status); + + // fill in fTimeUnitToCountToPatterns from locale fall-back chain + void searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, const char* localeName, + TimeUnit::UTimeUnitFields field, const UnicodeString&, + const char*, Hashtable*, UErrorCode&); + + // initialize hash table + Hashtable* initHash(UErrorCode& status); + + // delete hash table + void deleteHash(Hashtable* htable); + + // copy hash table + void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); + // get time unit name, such as "year", from time unit field enum, such as + // UTIMEUNIT_YEAR. + static const char* getTimeUnitName(TimeUnit::UTimeUnitFields field, UErrorCode& status); + + friend struct TimeUnitFormatReadSink; +}; + +U_NAMESPACE_END + +#endif /* U_HIDE_DEPRECATED_API */ +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __TMUTFMT_H__ +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/translit.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/translit.h new file mode 100644 index 0000000000000000000000000000000000000000..9ae32967fc45dcc60f6f5433e585a028adcc7078 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/translit.h @@ -0,0 +1,1593 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2014, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 11/17/99 aliu Creation. +********************************************************************** +*/ +#ifndef TRANSLIT_H +#define TRANSLIT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: Transforms text from one format to another. + */ + +#if !UCONFIG_NO_TRANSLITERATION + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/parseerr.h" +#include "unicode/utrans.h" // UTransPosition, UTransDirection +#include "unicode/strenum.h" + +U_NAMESPACE_BEGIN + +class UnicodeFilter; +class UnicodeSet; +class TransliteratorParser; +class NormalizationTransliterator; +class TransliteratorIDParser; + +/** + * + * Transliterator is an abstract class that + * transliterates text from one format to another. The most common + * kind of transliterator is a script, or alphabet, transliterator. + * For example, a Russian to Latin transliterator changes Russian text + * written in Cyrillic characters to phonetically equivalent Latin + * characters. It does not translate Russian to English! + * Transliteration, unlike translation, operates on characters, without + * reference to the meanings of words and sentences. + * + *

Although script conversion is its most common use, a + * transliterator can actually perform a more general class of tasks. + * In fact, Transliterator defines a very general API + * which specifies only that a segment of the input text is replaced + * by new text. The particulars of this conversion are determined + * entirely by subclasses of Transliterator. + * + *

Transliterators are stateless + * + *

Transliterator objects are stateless; they + * retain no information between calls to + * transliterate(). (However, this does not + * mean that threads may share transliterators without synchronizing + * them. Transliterators are not immutable, so they must be + * synchronized when shared between threads.) This might seem to + * limit the complexity of the transliteration operation. In + * practice, subclasses perform complex transliterations by delaying + * the replacement of text until it is known that no other + * replacements are possible. In other words, although the + * Transliterator objects are stateless, the source text + * itself embodies all the needed information, and delayed operation + * allows arbitrary complexity. + * + *

Batch transliteration + * + *

The simplest way to perform transliteration is all at once, on a + * string of existing text. This is referred to as batch + * transliteration. For example, given a string input + * and a transliterator t, the call + * + * String result = t.transliterate(input); + * + * will transliterate it and return the result. Other methods allow + * the client to specify a substring to be transliterated and to use + * {@link Replaceable } objects instead of strings, in order to + * preserve out-of-band information (such as text styles). + * + *

Keyboard transliteration + * + *

Somewhat more involved is keyboard, or incremental + * transliteration. This is the transliteration of text that is + * arriving from some source (typically the user's keyboard) one + * character at a time, or in some other piecemeal fashion. + * + *

In keyboard transliteration, a Replaceable buffer + * stores the text. As text is inserted, as much as possible is + * transliterated on the fly. This means a GUI that displays the + * contents of the buffer may show text being modified as each new + * character arrives. + * + *

Consider the simple rule-based Transliterator: + *

+ *     th>{theta}
+ *     t>{tau}
+ * 
+ * + * When the user types 't', nothing will happen, since the + * transliterator is waiting to see if the next character is 'h'. To + * remedy this, we introduce the notion of a cursor, marked by a '|' + * in the output string: + *
+ *     t>|{tau}
+ *     {tau}h>{theta}
+ * 
+ * + * Now when the user types 't', tau appears, and if the next character + * is 'h', the tau changes to a theta. This is accomplished by + * maintaining a cursor position (independent of the insertion point, + * and invisible in the GUI) across calls to + * transliterate(). Typically, the cursor will + * be coincident with the insertion point, but in a case like the one + * above, it will precede the insertion point. + * + *

Keyboard transliteration methods maintain a set of three indices + * that are updated with each call to + * transliterate(), including the cursor, start, + * and limit. Since these indices are changed by the method, they are + * passed in an int[] array. The START index + * marks the beginning of the substring that the transliterator will + * look at. It is advanced as text becomes committed (but it is not + * the committed index; that's the CURSOR). The + * CURSOR index, described above, marks the point at + * which the transliterator last stopped, either because it reached + * the end, or because it required more characters to disambiguate + * between possible inputs. The CURSOR can also be + * explicitly set by rules in a rule-based Transliterator. + * Any characters before the CURSOR index are frozen; + * future keyboard transliteration calls within this input sequence + * will not change them. New text is inserted at the + * LIMIT index, which marks the end of the substring that + * the transliterator looks at. + * + *

Because keyboard transliteration assumes that more characters + * are to arrive, it is conservative in its operation. It only + * transliterates when it can do so unambiguously. Otherwise it waits + * for more characters to arrive. When the client code knows that no + * more characters are forthcoming, perhaps because the user has + * performed some input termination operation, then it should call + * finishTransliteration() to complete any + * pending transliterations. + * + *

Inverses + * + *

Pairs of transliterators may be inverses of one another. For + * example, if transliterator A transliterates characters by + * incrementing their Unicode value (so "abc" -> "def"), and + * transliterator B decrements character values, then A + * is an inverse of B and vice versa. If we compose A + * with B in a compound transliterator, the result is the + * identity transliterator, that is, a transliterator that does not + * change its input text. + * + * The Transliterator method getInverse() + * returns a transliterator's inverse, if one exists, or + * null otherwise. However, the result of + * getInverse() usually will not be a true + * mathematical inverse. This is because true inverse transliterators + * are difficult to formulate. For example, consider two + * transliterators: AB, which transliterates the character 'A' + * to 'B', and BA, which transliterates 'B' to 'A'. It might + * seem that these are exact inverses, since + * + * \htmlonly

\endhtmlonly"A" x AB -> "B"
+ * "B" x BA -> "A"\htmlonly
\endhtmlonly + * + * where 'x' represents transliteration. However, + * + * \htmlonly
\endhtmlonly"ABCD" x AB -> "BBCD"
+ * "BBCD" x BA -> "AACD"\htmlonly
\endhtmlonly + * + * so AB composed with BA is not the + * identity. Nonetheless, BA may be usefully considered to be + * AB's inverse, and it is on this basis that + * AB.getInverse() could legitimately return + * BA. + * + *

IDs and display names + * + *

A transliterator is designated by a short identifier string or + * ID. IDs follow the format source-destination, + * where source describes the entity being replaced, and + * destination describes the entity replacing + * source. The entities may be the names of scripts, + * particular sequences of characters, or whatever else it is that the + * transliterator converts to or from. For example, a transliterator + * from Russian to Latin might be named "Russian-Latin". A + * transliterator from keyboard escape sequences to Latin-1 characters + * might be named "KeyboardEscape-Latin1". By convention, system + * entity names are in English, with the initial letters of words + * capitalized; user entity names may follow any format so long as + * they do not contain dashes. + * + *

In addition to programmatic IDs, transliterator objects have + * display names for presentation in user interfaces, returned by + * {@link #getDisplayName }. + * + *

Factory methods and registration + * + *

In general, client code should use the factory method + * {@link #createInstance } to obtain an instance of a + * transliterator given its ID. Valid IDs may be enumerated using + * getAvailableIDs(). Since transliterators are mutable, + * multiple calls to {@link #createInstance } with the same ID will + * return distinct objects. + * + *

In addition to the system transliterators registered at startup, + * user transliterators may be registered by calling + * registerInstance() at run time. A registered instance + * acts a template; future calls to {@link #createInstance } with the ID + * of the registered object return clones of that object. Thus any + * object passed to registerInstance() must implement + * clone() properly. To register a transliterator subclass + * without instantiating it (until it is needed), users may call + * {@link #registerFactory }. In this case, the objects are + * instantiated by invoking the zero-argument public constructor of + * the class. + * + *

Subclassing + * + * Subclasses must implement the abstract method + * handleTransliterate().

Subclasses should override + * the transliterate() method taking a + * Replaceable and the transliterate() + * method taking a String and StringBuffer + * if the performance of these methods can be improved over the + * performance obtained by the default implementations in this class. + * + *

Rule syntax + * + *

A set of rules determines how to perform translations. + * Rules within a rule set are separated by semicolons (';'). + * To include a literal semicolon, prefix it with a backslash ('\'). + * Unicode Pattern_White_Space is ignored. + * If the first non-blank character on a line is '#', + * the entire line is ignored as a comment. + * + *

Each set of rules consists of two groups, one forward, and one + * reverse. This is a convention that is not enforced; rules for one + * direction may be omitted, with the result that translations in + * that direction will not modify the source text. In addition, + * bidirectional forward-reverse rules may be specified for + * symmetrical transformations. + * + *

Note: Another description of the Transliterator rule syntax is available in + * section + * Transform Rules Syntax of UTS #35: Unicode LDML. + * The rules are shown there using arrow symbols ← and → and ↔. + * ICU supports both those and the equivalent ASCII symbols < and > and <>. + * + *

Rule statements take one of the following forms: + * + *

+ *
$alefmadda=\\u0622;
+ *
Variable definition. The name on the + * left is assigned the text on the right. In this example, + * after this statement, instances of the left hand name, + * "$alefmadda", will be replaced by + * the Unicode character U+0622. Variable names must begin + * with a letter and consist only of letters, digits, and + * underscores. Case is significant. Duplicate names cause + * an exception to be thrown, that is, variables cannot be + * redefined. The right hand side may contain well-formed + * text of any length, including no text at all ("$empty=;"). + * The right hand side may contain embedded UnicodeSet + * patterns, for example, "$softvowel=[eiyEIY]".
+ *
ai>$alefmadda;
+ *
Forward translation rule. This rule + * states that the string on the left will be changed to the + * string on the right when performing forward + * transliteration.
+ *
ai<$alefmadda;
+ *
Reverse translation rule. This rule + * states that the string on the right will be changed to + * the string on the left when performing reverse + * transliteration.
+ *
+ * + *
+ *
ai<>$alefmadda;
+ *
Bidirectional translation rule. This + * rule states that the string on the right will be changed + * to the string on the left when performing forward + * transliteration, and vice versa when performing reverse + * transliteration.
+ *
+ * + *

Translation rules consist of a match pattern and an output + * string. The match pattern consists of literal characters, + * optionally preceded by context, and optionally followed by + * context. Context characters, like literal pattern characters, + * must be matched in the text being transliterated. However, unlike + * literal pattern characters, they are not replaced by the output + * text. For example, the pattern "abc{def}" + * indicates the characters "def" must be + * preceded by "abc" for a successful match. + * If there is a successful match, "def" will + * be replaced, but not "abc". The final '}' + * is optional, so "abc{def" is equivalent to + * "abc{def}". Another example is "{123}456" + * (or "123}456") in which the literal + * pattern "123" must be followed by "456". + * + *

The output string of a forward or reverse rule consists of + * characters to replace the literal pattern characters. If the + * output string contains the character '|', this is + * taken to indicate the location of the cursor after + * replacement. The cursor is the point in the text at which the + * next replacement, if any, will be applied. The cursor is usually + * placed within the replacement text; however, it can actually be + * placed into the preceding or following context by using the + * special character '@'. Examples: + * + *

+ *     a {foo} z > | @ bar; # foo -> bar, move cursor before a
+ *     {foo} xyz > bar @@|; # foo -> bar, cursor between y and z
+ * 
+ * + *

UnicodeSet + * + *

UnicodeSet patterns may appear anywhere that + * makes sense. They may appear in variable definitions. + * Contrariwise, UnicodeSet patterns may themselves + * contain variable references, such as "$a=[a-z];$not_a=[^$a]", + * or "$range=a-z;$ll=[$range]". + * + *

UnicodeSet patterns may also be embedded directly + * into rule strings. Thus, the following two rules are equivalent: + * + *

+ *     $vowel=[aeiou]; $vowel>'*'; # One way to do this
+ *     [aeiou]>'*'; # Another way
+ * 
+ * + *

See {@link UnicodeSet} for more documentation and examples. + * + *

Segments + * + *

Segments of the input string can be matched and copied to the + * output string. This makes certain sets of rules simpler and more + * general, and makes reordering possible. For example: + * + *

+ *     ([a-z]) > $1 $1; # double lowercase letters
+ *     ([:Lu:]) ([:Ll:]) > $2 $1; # reverse order of Lu-Ll pairs
+ * 
+ * + *

The segment of the input string to be copied is delimited by + * "(" and ")". Up to + * nine segments may be defined. Segments may not overlap. In the + * output string, "$1" through "$9" + * represent the input string segments, in left-to-right order of + * definition. + * + *

Anchors + * + *

Patterns can be anchored to the beginning or the end of the text. This is done with the + * special characters '^' and '$'. For example: + * + *

+ *   ^ a   > 'BEG_A';   # match 'a' at start of text
+ *     a   > 'A'; # match other instances of 'a'
+ *     z $ > 'END_Z';   # match 'z' at end of text
+ *     z   > 'Z';       # match other instances of 'z'
+ * 
+ * + *

It is also possible to match the beginning or the end of the text using a UnicodeSet. + * This is done by including a virtual anchor character '$' at the end of the + * set pattern. Although this is usually the match character for the end anchor, the set will + * match either the beginning or the end of the text, depending on its placement. For + * example: + * + *

+ *   $x = [a-z$];   # match 'a' through 'z' OR anchor
+ *   $x 1    > 2;   # match '1' after a-z or at the start
+ *      3 $x > 4;   # match '3' before a-z or at the end
+ * 
+ * + *

Example + * + *

The following example rules illustrate many of the features of + * the rule language. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Rule 1.abc{def}>x|y
Rule 2.xyz>r
Rule 3.yz>q
+ * + *

Applying these rules to the string "adefabcdefz" + * yields the following results: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
|adefabcdefzInitial state, no rules match. Advance + * cursor.
a|defabcdefzStill no match. Rule 1 does not match + * because the preceding context is not present.
ad|efabcdefzStill no match. Keep advancing until + * there is a match...
ade|fabcdefz...
adef|abcdefz...
adefa|bcdefz...
adefab|cdefz...
adefabc|defzRule 1 matches; replace "def" + * with "xy" and back up the cursor + * to before the 'y'.
adefabcx|yzAlthough "xyz" is + * present, rule 2 does not match because the cursor is + * before the 'y', not before the 'x'. + * Rule 3 does match. Replace "yz" + * with "q".
adefabcxq|The cursor is at the end; + * transliteration is complete.
+ * + *

The order of rules is significant. If multiple rules may match + * at some point, the first matching rule is applied. + * + *

Forward and reverse rules may have an empty output string. + * Otherwise, an empty left or right hand side of any statement is a + * syntax error. + * + *

Single quotes are used to quote any character other than a + * digit or letter. To specify a single quote itself, inside or + * outside of quotes, use two single quotes in a row. For example, + * the rule "'>'>o''clock" changes the + * string ">" to the string "o'clock". + * + *

Notes + * + *

While a Transliterator is being built from rules, it checks that + * the rules are added in proper order. For example, if the rule + * "a>x" is followed by the rule "ab>y", + * then the second rule will throw an exception. The reason is that + * the second rule can never be triggered, since the first rule + * always matches anything it matches. In other words, the first + * rule masks the second rule. + * + * @author Alan Liu + * @stable ICU 2.0 + */ +class U_I18N_API Transliterator : public UObject { + +private: + + /** + * Programmatic name, e.g., "Latin-Arabic". + */ + UnicodeString ID; + + /** + * This transliterator's filter. Any character for which + * filter.contains() returns false will not be + * altered by this transliterator. If filter is + * null then no filtering is applied. + */ + UnicodeFilter* filter; + + int32_t maximumContextLength; + + public: + + /** + * A context integer or pointer for a factory function, passed by + * value. + * @stable ICU 2.4 + */ + union Token { + /** + * This token, interpreted as a 32-bit integer. + * @stable ICU 2.4 + */ + int32_t integer; + /** + * This token, interpreted as a native pointer. + * @stable ICU 2.4 + */ + void* pointer; + }; + +#ifndef U_HIDE_INTERNAL_API + /** + * Return a token containing an integer. + * @return a token containing an integer. + * @internal + */ + inline static Token integerToken(int32_t); + + /** + * Return a token containing a pointer. + * @return a token containing a pointer. + * @internal + */ + inline static Token pointerToken(void*); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * A function that creates and returns a Transliterator. When + * invoked, it will be passed the ID string that is being + * instantiated, together with the context pointer that was passed + * in when the factory function was first registered. Many + * factory functions will ignore both parameters, however, + * functions that are registered to more than one ID may use the + * ID or the context parameter to parameterize the transliterator + * they create. + * @param ID the string identifier for this transliterator + * @param context a context pointer that will be stored and + * later passed to the factory function when an ID matching + * the registration ID is being instantiated with this factory. + * @stable ICU 2.4 + */ + typedef Transliterator* (U_EXPORT2 *Factory)(const UnicodeString& ID, Token context); + +protected: + + /** + * Default constructor. + * @param ID the string identifier for this transliterator + * @param adoptedFilter the filter. Any character for which + * filter.contains() returns false will not be + * altered by this transliterator. If filter is + * null then no filtering is applied. + * @stable ICU 2.4 + */ + Transliterator(const UnicodeString& ID, UnicodeFilter* adoptedFilter); + + /** + * Copy constructor. + * @stable ICU 2.4 + */ + Transliterator(const Transliterator&); + + /** + * Assignment operator. + * @stable ICU 2.4 + */ + Transliterator& operator=(const Transliterator&); + + /** + * Create a transliterator from a basic ID. This is an ID + * containing only the forward direction source, target, and + * variant. + * @param id a basic ID of the form S-T or S-T/V. + * @param canon canonical ID to assign to the object, or + * nullptr to leave the ID unchanged + * @return a newly created Transliterator or null if the ID is + * invalid. + * @stable ICU 2.4 + */ + static Transliterator* createBasicInstance(const UnicodeString& id, + const UnicodeString* canon); + + friend class TransliteratorParser; // for parseID() + friend class TransliteratorIDParser; // for createBasicInstance() + friend class TransliteratorAlias; // for setID() + +public: + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~Transliterator(); + + /** + * Implements Cloneable. + * All subclasses are encouraged to implement this method if it is + * possible and reasonable to do so. Subclasses that are to be + * registered with the system using registerInstance() + * are required to implement this method. If a subclass does not + * implement clone() properly and is registered with the system + * using registerInstance(), then the default clone() implementation + * will return null, and calls to createInstance() will fail. + * + * @return a copy of the object. + * @see #registerInstance + * @stable ICU 2.0 + */ + virtual Transliterator* clone() const; + + /** + * Transliterates a segment of a string, with optional filtering. + * + * @param text the string to be transliterated + * @param start the beginning index, inclusive; 0 <= start + * <= limit. + * @param limit the ending index, exclusive; start <= limit + * <= text.length(). + * @return The new limit index. The text previously occupying [start, + * limit) has been transliterated, possibly to a string of a different + * length, at [start, new-limit), where + * new-limit is the return value. If the input offsets are out of bounds, + * the returned value is -1 and the input string remains unchanged. + * @stable ICU 2.0 + */ + virtual int32_t transliterate(Replaceable& text, + int32_t start, int32_t limit) const; + + /** + * Transliterates an entire string in place. Convenience method. + * @param text the string to be transliterated + * @stable ICU 2.0 + */ + virtual void transliterate(Replaceable& text) const; + + /** + * Transliterates the portion of the text buffer that can be + * transliterated unambiguosly after new text has been inserted, + * typically as a result of a keyboard event. The new text in + * insertion will be inserted into text + * at index.limit, advancing + * index.limit by insertion.length(). + * Then the transliterator will try to transliterate characters of + * text between index.cursor and + * index.limit. Characters before + * index.cursor will not be changed. + * + *

Upon return, values in index will be updated. + * index.start will be advanced to the first + * character that future calls to this method will read. + * index.cursor and index.limit will + * be adjusted to delimit the range of text that future calls to + * this method may change. + * + *

Typical usage of this method begins with an initial call + * with index.start and index.limit + * set to indicate the portion of text to be + * transliterated, and index.cursor == index.start. + * Thereafter, index can be used without + * modification in future calls, provided that all changes to + * text are made via this method. + * + *

This method assumes that future calls may be made that will + * insert new text into the buffer. As a result, it only performs + * unambiguous transliterations. After the last call to this + * method, there may be untransliterated text that is waiting for + * more input to resolve an ambiguity. In order to perform these + * pending transliterations, clients should call + * {@link #finishTransliteration } after the last call to this + * method has been made. + * + * @param text the buffer holding transliterated and untransliterated text + * @param index an array of three integers. + * + *

  • index.start: the beginning index, + * inclusive; 0 <= index.start <= index.limit. + * + *
  • index.limit: the ending index, exclusive; + * index.start <= index.limit <= text.length(). + * insertion is inserted at + * index.limit. + * + *
  • index.cursor: the next character to be + * considered for transliteration; index.start <= + * index.cursor <= index.limit. Characters before + * index.cursor will not be changed by future calls + * to this method.
+ * + * @param insertion text to be inserted and possibly + * transliterated into the translation buffer at + * index.limit. If null then no text + * is inserted. + * @param status Output param to filled in with a success or an error. + * @see #handleTransliterate + * @exception IllegalArgumentException if index + * is invalid + * @see UTransPosition + * @stable ICU 2.0 + */ + virtual void transliterate(Replaceable& text, UTransPosition& index, + const UnicodeString& insertion, + UErrorCode& status) const; + + /** + * Transliterates the portion of the text buffer that can be + * transliterated unambiguosly after a new character has been + * inserted, typically as a result of a keyboard event. This is a + * convenience method. + * @param text the buffer holding transliterated and + * untransliterated text + * @param index an array of three integers. + * @param insertion text to be inserted and possibly + * transliterated into the translation buffer at + * index.limit. + * @param status Output param to filled in with a success or an error. + * @see #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const + * @stable ICU 2.0 + */ + virtual void transliterate(Replaceable& text, UTransPosition& index, + UChar32 insertion, + UErrorCode& status) const; + + /** + * Transliterates the portion of the text buffer that can be + * transliterated unambiguosly. This is a convenience method; see + * {@link #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const } + * for details. + * @param text the buffer holding transliterated and + * untransliterated text + * @param index an array of three integers. + * @param status Output param to filled in with a success or an error. + * @see #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode &) const + * @stable ICU 2.0 + */ + virtual void transliterate(Replaceable& text, UTransPosition& index, + UErrorCode& status) const; + + /** + * Finishes any pending transliterations that were waiting for + * more characters. Clients should call this method as the last + * call after a sequence of one or more calls to + * transliterate(). + * @param text the buffer holding transliterated and + * untransliterated text. + * @param index the array of indices previously passed to {@link #transliterate } + * @stable ICU 2.0 + */ + virtual void finishTransliteration(Replaceable& text, + UTransPosition& index) const; + +private: + + /** + * This internal method does incremental transliteration. If the + * 'insertion' is non-null then we append it to 'text' before + * proceeding. This method calls through to the pure virtual + * framework method handleTransliterate() to do the actual + * work. + * @param text the buffer holding transliterated and + * untransliterated text + * @param index an array of three integers. See {@link + * #transliterate(Replaceable, int[], String)}. + * @param insertion text to be inserted and possibly + * transliterated into the translation buffer at + * index.limit. + * @param status Output param to filled in with a success or an error. + */ + void _transliterate(Replaceable& text, + UTransPosition& index, + const UnicodeString* insertion, + UErrorCode &status) const; + +protected: + + /** + * Abstract method that concrete subclasses define to implement + * their transliteration algorithm. This method handles both + * incremental and non-incremental transliteration. Let + * originalStart refer to the value of + * pos.start upon entry. + * + *
    + *
  • If incremental is false, then this method + * should transliterate all characters between + * pos.start and pos.limit. Upon return + * pos.start must == pos.limit.
  • + * + *
  • If incremental is true, then this method + * should transliterate all characters between + * pos.start and pos.limit that can be + * unambiguously transliterated, regardless of future insertions + * of text at pos.limit. Upon return, + * pos.start should be in the range + * [originalStart, pos.limit). + * pos.start should be positioned such that + * characters [originalStart, + * pos.start) will not be changed in the future by this + * transliterator and characters [pos.start, + * pos.limit) are unchanged.
  • + *
+ * + *

Implementations of this method should also obey the + * following invariants:

+ * + *
    + *
  • pos.limit and pos.contextLimit + * should be updated to reflect changes in length of the text + * between pos.start and pos.limit. The + * difference pos.contextLimit - pos.limit should + * not change.
  • + * + *
  • pos.contextStart should not change.
  • + * + *
  • Upon return, neither pos.start nor + * pos.limit should be less than + * originalStart.
  • + * + *
  • Text before originalStart and text after + * pos.limit should not change.
  • + * + *
  • Text before pos.contextStart and text after + * pos.contextLimit should be ignored.
  • + *
+ * + *

Subclasses may safely assume that all characters in + * [pos.start, pos.limit) are filtered. + * In other words, the filter has already been applied by the time + * this method is called. See + * filteredTransliterate(). + * + *

This method is not for public consumption. Calling + * this method directly will transliterate + * [pos.start, pos.limit) without + * applying the filter. End user code should call + * transliterate() instead of this method. Subclass code + * and wrapping transliterators should call + * filteredTransliterate() instead of this method.

+ * + * @param text the buffer holding transliterated and + * untransliterated text + * + * @param pos the indices indicating the start, limit, context + * start, and context limit of the text. + * + * @param incremental if true, assume more text may be inserted at + * pos.limit and act accordingly. Otherwise, + * transliterate all text between pos.start and + * pos.limit and move pos.start up to + * pos.limit. + * + * @see #transliterate + * @stable ICU 2.4 + */ + virtual void handleTransliterate(Replaceable& text, + UTransPosition& pos, + UBool incremental) const = 0; + +public: + /** + * Transliterate a substring of text, as specified by index, taking filters + * into account. This method is for subclasses that need to delegate to + * another transliterator. + * @param text the text to be transliterated + * @param index the position indices + * @param incremental if true, then assume more characters may be inserted + * at index.limit, and postpone processing to accommodate future incoming + * characters + * @stable ICU 2.4 + */ + virtual void filteredTransliterate(Replaceable& text, + UTransPosition& index, + UBool incremental) const; + +private: + + /** + * Top-level transliteration method, handling filtering, incremental and + * non-incremental transliteration, and rollback. All transliteration + * public API methods eventually call this method with a rollback argument + * of true. Other entities may call this method but rollback should be + * false. + * + *

If this transliterator has a filter, break up the input text into runs + * of unfiltered characters. Pass each run to + * subclass.handleTransliterate(). + * + *

In incremental mode, if rollback is true, perform a special + * incremental procedure in which several passes are made over the input + * text, adding one character at a time, and committing successful + * transliterations as they occur. Unsuccessful transliterations are rolled + * back and retried with additional characters to give correct results. + * + * @param text the text to be transliterated + * @param index the position indices + * @param incremental if true, then assume more characters may be inserted + * at index.limit, and postpone processing to accommodate future incoming + * characters + * @param rollback if true and if incremental is true, then perform special + * incremental processing, as described above, and undo partial + * transliterations where necessary. If incremental is false then this + * parameter is ignored. + */ + virtual void filteredTransliterate(Replaceable& text, + UTransPosition& index, + UBool incremental, + UBool rollback) const; + +public: + + /** + * Returns the length of the longest context required by this transliterator. + * This is preceding context. The default implementation supplied + * by Transliterator returns zero; subclasses + * that use preceding context should override this method to return the + * correct value. For example, if a transliterator translates "ddd" (where + * d is any digit) to "555" when preceded by "(ddd)", then the preceding + * context length is 5, the length of "(ddd)". + * + * @return The maximum number of preceding context characters this + * transliterator needs to examine + * @stable ICU 2.0 + */ + int32_t getMaximumContextLength(void) const; + +protected: + + /** + * Method for subclasses to use to set the maximum context length. + * @param maxContextLength the new value to be set. + * @see #getMaximumContextLength + * @stable ICU 2.4 + */ + void setMaximumContextLength(int32_t maxContextLength); + +public: + + /** + * Returns a programmatic identifier for this transliterator. + * If this identifier is passed to createInstance(), it + * will return this object, if it has been registered. + * @return a programmatic identifier for this transliterator. + * @see #registerInstance + * @see #registerFactory + * @see #getAvailableIDs + * @stable ICU 2.0 + */ + virtual const UnicodeString& getID(void) const; + + /** + * Returns a name for this transliterator that is appropriate for + * display to the user in the default locale. See {@link #getDisplayName } + * for details. + * @param ID the string identifier for this transliterator + * @param result Output param to receive the display name + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, + UnicodeString& result); + + /** + * Returns a name for this transliterator that is appropriate for + * display to the user in the given locale. This name is taken + * from the locale resource data in the standard manner of the + * java.text package. + * + *

If no localized names exist in the system resource bundles, + * a name is synthesized using a localized + * MessageFormat pattern from the resource data. The + * arguments to this pattern are an integer followed by one or two + * strings. The integer is the number of strings, either 1 or 2. + * The strings are formed by splitting the ID for this + * transliterator at the first '-'. If there is no '-', then the + * entire ID forms the only string. + * @param ID the string identifier for this transliterator + * @param inLocale the Locale in which the display name should be + * localized. + * @param result Output param to receive the display name + * @return A reference to 'result'. + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, + const Locale& inLocale, + UnicodeString& result); + + /** + * Returns the filter used by this transliterator, or nullptr + * if this transliterator uses no filter. + * @return the filter used by this transliterator, or nullptr + * if this transliterator uses no filter. + * @stable ICU 2.0 + */ + const UnicodeFilter* getFilter(void) const; + + /** + * Returns the filter used by this transliterator, or nullptr if this + * transliterator uses no filter. The caller must eventually delete the + * result. After this call, this transliterator's filter is set to + * nullptr. + * @return the filter used by this transliterator, or nullptr if this + * transliterator uses no filter. + * @stable ICU 2.4 + */ + UnicodeFilter* orphanFilter(void); + + /** + * Changes the filter used by this transliterator. If the filter + * is set to null then no filtering will occur. + * + *

Callers must take care if a transliterator is in use by + * multiple threads. The filter should not be changed by one + * thread while another thread may be transliterating. + * @param adoptedFilter the new filter to be adopted. + * @stable ICU 2.0 + */ + void adoptFilter(UnicodeFilter* adoptedFilter); + + /** + * Returns this transliterator's inverse. See the class + * documentation for details. This implementation simply inverts + * the two entities in the ID and attempts to retrieve the + * resulting transliterator. That is, if getID() + * returns "A-B", then this method will return the result of + * createInstance("B-A"), or null if that + * call fails. + * + *

Subclasses with knowledge of their inverse may wish to + * override this method. + * + * @param status Output param to filled in with a success or an error. + * @return a transliterator that is an inverse, not necessarily + * exact, of this transliterator, or null if no such + * transliterator is registered. + * @see #registerInstance + * @stable ICU 2.0 + */ + Transliterator* createInverse(UErrorCode& status) const; + + /** + * Returns a Transliterator object given its ID. + * The ID must be either a system transliterator ID or a ID registered + * using registerInstance(). + * + * @param ID a valid ID, as enumerated by getAvailableIDs() + * @param dir either FORWARD or REVERSE. + * @param parseError Struct to receive information on position + * of error if an error is encountered + * @param status Output param to filled in with a success or an error. + * @return A Transliterator object with the given ID + * @see #registerInstance + * @see #getAvailableIDs + * @see #getID + * @stable ICU 2.0 + */ + static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, + UTransDirection dir, + UParseError& parseError, + UErrorCode& status); + + /** + * Returns a Transliterator object given its ID. + * The ID must be either a system transliterator ID or a ID registered + * using registerInstance(). + * @param ID a valid ID, as enumerated by getAvailableIDs() + * @param dir either FORWARD or REVERSE. + * @param status Output param to filled in with a success or an error. + * @return A Transliterator object with the given ID + * @stable ICU 2.0 + */ + static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, + UTransDirection dir, + UErrorCode& status); + + /** + * Returns a Transliterator object constructed from + * the given rule string. This will be a rule-based Transliterator, + * if the rule string contains only rules, or a + * compound Transliterator, if it contains ID blocks, or a + * null Transliterator, if it contains ID blocks which parse as + * empty for the given direction. + * + * @param ID the id for the transliterator. + * @param rules rules, separated by ';' + * @param dir either FORWARD or REVERSE. + * @param parseError Struct to receive information on position + * of error if an error is encountered + * @param status Output param set to success/failure code. + * @return a newly created Transliterator + * @stable ICU 2.0 + */ + static Transliterator* U_EXPORT2 createFromRules(const UnicodeString& ID, + const UnicodeString& rules, + UTransDirection dir, + UParseError& parseError, + UErrorCode& status); + + /** + * Create a rule string that can be passed to createFromRules() + * to recreate this transliterator. + * @param result the string to receive the rules. Previous + * contents will be deleted. + * @param escapeUnprintable if true then convert unprintable + * character to their hex escape representations, \\uxxxx or + * \\Uxxxxxxxx. Unprintable characters are those other than + * U+000A, U+0020..U+007E. + * @stable ICU 2.0 + */ + virtual UnicodeString& toRules(UnicodeString& result, + UBool escapeUnprintable) const; + + /** + * Return the number of elements that make up this transliterator. + * For example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" + * were created, the return value of this method would be 3. + * + *

If this transliterator is not composed of other + * transliterators, then this method returns 1. + * @return the number of transliterators that compose this + * transliterator, or 1 if this transliterator is not composed of + * multiple transliterators + * @stable ICU 3.0 + */ + int32_t countElements() const; + + /** + * Return an element that makes up this transliterator. For + * example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" + * were created, the return value of this method would be one + * of the three transliterator objects that make up that + * transliterator: [NFD, Jamo-Latin, Latin-Greek]. + * + *

If this transliterator is not composed of other + * transliterators, then this method will return a reference to + * this transliterator when given the index 0. + * @param index a value from 0..countElements()-1 indicating the + * transliterator to return + * @param ec input-output error code + * @return one of the transliterators that makes up this + * transliterator, if this transliterator is made up of multiple + * transliterators, otherwise a reference to this object if given + * an index of 0 + * @stable ICU 3.0 + */ + const Transliterator& getElement(int32_t index, UErrorCode& ec) const; + + /** + * Returns the set of all characters that may be modified in the + * input text by this Transliterator. This incorporates this + * object's current filter; if the filter is changed, the return + * value of this function will change. The default implementation + * returns an empty set. Some subclasses may override + * {@link #handleGetSourceSet } to return a more precise result. The + * return result is approximate in any case and is intended for + * use by tests, tools, or utilities. + * @param result receives result set; previous contents lost + * @return a reference to result + * @see #getTargetSet + * @see #handleGetSourceSet + * @stable ICU 2.4 + */ + UnicodeSet& getSourceSet(UnicodeSet& result) const; + + /** + * Framework method that returns the set of all characters that + * may be modified in the input text by this Transliterator, + * ignoring the effect of this object's filter. The base class + * implementation returns the empty set. Subclasses that wish to + * implement this should override this method. + * @return the set of characters that this transliterator may + * modify. The set may be modified, so subclasses should return a + * newly-created object. + * @param result receives result set; previous contents lost + * @see #getSourceSet + * @see #getTargetSet + * @stable ICU 2.4 + */ + virtual void handleGetSourceSet(UnicodeSet& result) const; + + /** + * Returns the set of all characters that may be generated as + * replacement text by this transliterator. The default + * implementation returns the empty set. Some subclasses may + * override this method to return a more precise result. The + * return result is approximate in any case and is intended for + * use by tests, tools, or utilities requiring such + * meta-information. + * @param result receives result set; previous contents lost + * @return a reference to result + * @see #getTargetSet + * @stable ICU 2.4 + */ + virtual UnicodeSet& getTargetSet(UnicodeSet& result) const; + +public: + + /** + * Registers a factory function that creates transliterators of + * a given ID. + * + * Because ICU may choose to cache Transliterators internally, this must + * be called at application startup, prior to any calls to + * Transliterator::createXXX to avoid undefined behavior. + * + * @param id the ID being registered + * @param factory a function pointer that will be copied and + * called later when the given ID is passed to createInstance() + * @param context a context pointer that will be stored and + * later passed to the factory function when an ID matching + * the registration ID is being instantiated with this factory. + * @stable ICU 2.0 + */ + static void U_EXPORT2 registerFactory(const UnicodeString& id, + Factory factory, + Token context); + + /** + * Registers an instance obj of a subclass of + * Transliterator with the system. When + * createInstance() is called with an ID string that is + * equal to obj->getID(), then obj->clone() is + * returned. + * + * After this call the Transliterator class owns the adoptedObj + * and will delete it. + * + * Because ICU may choose to cache Transliterators internally, this must + * be called at application startup, prior to any calls to + * Transliterator::createXXX to avoid undefined behavior. + * + * @param adoptedObj an instance of subclass of + * Transliterator that defines clone() + * @see #createInstance + * @see #registerFactory + * @see #unregister + * @stable ICU 2.0 + */ + static void U_EXPORT2 registerInstance(Transliterator* adoptedObj); + + /** + * Registers an ID string as an alias of another ID string. + * That is, after calling this function, createInstance(aliasID) + * will return the same thing as createInstance(realID). + * This is generally used to create shorter, more mnemonic aliases + * for long compound IDs. + * + * @param aliasID The new ID being registered. + * @param realID The ID that the new ID is to be an alias for. + * This can be a compound ID and can include filters and should + * refer to transliterators that have already been registered with + * the framework, although this isn't checked. + * @stable ICU 3.6 + */ + static void U_EXPORT2 registerAlias(const UnicodeString& aliasID, + const UnicodeString& realID); + +protected: + +#ifndef U_HIDE_INTERNAL_API + /** + * @param id the ID being registered + * @param factory a function pointer that will be copied and + * called later when the given ID is passed to createInstance() + * @param context a context pointer that will be stored and + * later passed to the factory function when an ID matching + * the registration ID is being instantiated with this factory. + * @internal + */ + static void _registerFactory(const UnicodeString& id, + Factory factory, + Token context); + + /** + * @internal + */ + static void _registerInstance(Transliterator* adoptedObj); + + /** + * @internal + */ + static void _registerAlias(const UnicodeString& aliasID, const UnicodeString& realID); + + /** + * Register two targets as being inverses of one another. For + * example, calling registerSpecialInverse("NFC", "NFD", true) causes + * Transliterator to form the following inverse relationships: + * + *

NFC => NFD
+     * Any-NFC => Any-NFD
+     * NFD => NFC
+     * Any-NFD => Any-NFC
+ * + * (Without the special inverse registration, the inverse of NFC + * would be NFC-Any.) Note that NFD is shorthand for Any-NFD, but + * that the presence or absence of "Any-" is preserved. + * + *

The relationship is symmetrical; registering (a, b) is + * equivalent to registering (b, a). + * + *

The relevant IDs must still be registered separately as + * factories or classes. + * + *

Only the targets are specified. Special inverses always + * have the form Any-Target1 <=> Any-Target2. The target should + * have canonical casing (the casing desired to be produced when + * an inverse is formed) and should contain no whitespace or other + * extraneous characters. + * + * @param target the target against which to register the inverse + * @param inverseTarget the inverse of target, that is + * Any-target.getInverse() => Any-inverseTarget + * @param bidirectional if true, register the reverse relation + * as well, that is, Any-inverseTarget.getInverse() => Any-target + * @internal + */ + static void _registerSpecialInverse(const UnicodeString& target, + const UnicodeString& inverseTarget, + UBool bidirectional); +#endif /* U_HIDE_INTERNAL_API */ + +public: + + /** + * Unregisters a transliterator or class. This may be either + * a system transliterator or a user transliterator or class. + * Any attempt to construct an unregistered transliterator based + * on its ID will fail. + * + * Because ICU may choose to cache Transliterators internally, this should + * be called during application shutdown, after all calls to + * Transliterator::createXXX to avoid undefined behavior. + * + * @param ID the ID of the transliterator or class + * @return the Object that was registered with + * ID, or null if none was + * @see #registerInstance + * @see #registerFactory + * @stable ICU 2.0 + */ + static void U_EXPORT2 unregister(const UnicodeString& ID); + +public: + + /** + * Return a StringEnumeration over the IDs available at the time of the + * call, including user-registered IDs. + * @param ec input-output error code + * @return a newly-created StringEnumeration over the transliterators + * available at the time of the call. The caller should delete this object + * when done using it. + * @stable ICU 3.0 + */ + static StringEnumeration* U_EXPORT2 getAvailableIDs(UErrorCode& ec); + + /** + * Return the number of registered source specifiers. + * @return the number of registered source specifiers. + * @stable ICU 2.0 + */ + static int32_t U_EXPORT2 countAvailableSources(void); + + /** + * Return a registered source specifier. + * @param index which specifier to return, from 0 to n-1, where + * n = countAvailableSources() + * @param result fill-in parameter to receive the source specifier. + * If index is out of range, result will be empty. + * @return reference to result + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getAvailableSource(int32_t index, + UnicodeString& result); + + /** + * Return the number of registered target specifiers for a given + * source specifier. + * @param source the given source specifier. + * @return the number of registered target specifiers for a given + * source specifier. + * @stable ICU 2.0 + */ + static int32_t U_EXPORT2 countAvailableTargets(const UnicodeString& source); + + /** + * Return a registered target specifier for a given source. + * @param index which specifier to return, from 0 to n-1, where + * n = countAvailableTargets(source) + * @param source the source specifier + * @param result fill-in parameter to receive the target specifier. + * If source is invalid or if index is out of range, result will + * be empty. + * @return reference to result + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getAvailableTarget(int32_t index, + const UnicodeString& source, + UnicodeString& result); + + /** + * Return the number of registered variant specifiers for a given + * source-target pair. + * @param source the source specifiers. + * @param target the target specifiers. + * @stable ICU 2.0 + */ + static int32_t U_EXPORT2 countAvailableVariants(const UnicodeString& source, + const UnicodeString& target); + + /** + * Return a registered variant specifier for a given source-target + * pair. + * @param index which specifier to return, from 0 to n-1, where + * n = countAvailableVariants(source, target) + * @param source the source specifier + * @param target the target specifier + * @param result fill-in parameter to receive the variant + * specifier. If source is invalid or if target is invalid or if + * index is out of range, result will be empty. + * @return reference to result + * @stable ICU 2.0 + */ + static UnicodeString& U_EXPORT2 getAvailableVariant(int32_t index, + const UnicodeString& source, + const UnicodeString& target, + UnicodeString& result); + +protected: + +#ifndef U_HIDE_INTERNAL_API + /** + * Non-mutexed internal method + * @internal + */ + static int32_t _countAvailableSources(void); + + /** + * Non-mutexed internal method + * @internal + */ + static UnicodeString& _getAvailableSource(int32_t index, + UnicodeString& result); + + /** + * Non-mutexed internal method + * @internal + */ + static int32_t _countAvailableTargets(const UnicodeString& source); + + /** + * Non-mutexed internal method + * @internal + */ + static UnicodeString& _getAvailableTarget(int32_t index, + const UnicodeString& source, + UnicodeString& result); + + /** + * Non-mutexed internal method + * @internal + */ + static int32_t _countAvailableVariants(const UnicodeString& source, + const UnicodeString& target); + + /** + * Non-mutexed internal method + * @internal + */ + static UnicodeString& _getAvailableVariant(int32_t index, + const UnicodeString& source, + const UnicodeString& target, + UnicodeString& result); +#endif /* U_HIDE_INTERNAL_API */ + +protected: + + /** + * Set the ID of this transliterators. Subclasses shouldn't do + * this, unless the underlying script behavior has changed. + * @param id the new id t to be set. + * @stable ICU 2.4 + */ + void setID(const UnicodeString& id); + +public: + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). + * Note that Transliterator is an abstract base class, and therefor + * no fully constructed object will have a dynamic + * UCLassID that equals the UClassID returned from + * TRansliterator::getStaticClassID(). + * @return The class ID for class Transliterator. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID polymorphically. This method + * is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + *

Concrete subclasses of Transliterator must use the + * UOBJECT_DEFINE_RTTI_IMPLEMENTATION macro from + * uobject.h to provide the RTTI functions. + * + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + +private: + static UBool initializeRegistry(UErrorCode &status); + +public: +#ifndef U_HIDE_OBSOLETE_API + /** + * Return the number of IDs currently registered with the system. + * To retrieve the actual IDs, call getAvailableID(i) with + * i from 0 to countAvailableIDs() - 1. + * @return the number of IDs currently registered with the system. + * @obsolete ICU 3.4 use getAvailableIDs() instead + */ + static int32_t U_EXPORT2 countAvailableIDs(void); + + /** + * Return the index-th available ID. index must be between 0 + * and countAvailableIDs() - 1, inclusive. If index is out of + * range, the result of getAvailableID(0) is returned. + * @param index the given ID index. + * @return the index-th available ID. index must be between 0 + * and countAvailableIDs() - 1, inclusive. If index is out of + * range, the result of getAvailableID(0) is returned. + * @obsolete ICU 3.4 use getAvailableIDs() instead; this function + * is not thread safe, since it returns a reference to storage that + * may become invalid if another thread calls unregister + */ + static const UnicodeString& U_EXPORT2 getAvailableID(int32_t index); +#endif /* U_HIDE_OBSOLETE_API */ +}; + +inline int32_t Transliterator::getMaximumContextLength(void) const { + return maximumContextLength; +} + +inline void Transliterator::setID(const UnicodeString& id) { + ID = id; + // NUL-terminate the ID string, which is a non-aliased copy. + ID.append((char16_t)0); + ID.truncate(ID.length()-1); +} + +#ifndef U_HIDE_INTERNAL_API +inline Transliterator::Token Transliterator::integerToken(int32_t i) { + Token t; + t.integer = i; + return t; +} + +inline Transliterator::Token Transliterator::pointerToken(void* p) { + Token t; + t.pointer = p; + return t; +} +#endif /* U_HIDE_INTERNAL_API */ + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_TRANSLITERATION */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzfmt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzfmt.h new file mode 100644 index 0000000000000000000000000000000000000000..4bd80e0e343ea1665f55e583c18b685dca3589b3 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzfmt.h @@ -0,0 +1,1102 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2011-2015, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +*/ +#ifndef __TZFMT_H +#define __TZFMT_H + +/** + * \file + * \brief C++ API: TimeZoneFormat + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/format.h" +#include "unicode/timezone.h" +#include "unicode/tznames.h" + +U_CDECL_BEGIN +/** + * Constants for time zone display format style used by format/parse APIs + * in TimeZoneFormat. + * @stable ICU 50 + */ +typedef enum UTimeZoneFormatStyle { + /** + * Generic location format, such as "United States Time (New York)", "Italy Time" + * @stable ICU 50 + */ + UTZFMT_STYLE_GENERIC_LOCATION, + /** + * Generic long non-location format, such as "Eastern Time". + * @stable ICU 50 + */ + UTZFMT_STYLE_GENERIC_LONG, + /** + * Generic short non-location format, such as "ET". + * @stable ICU 50 + */ + UTZFMT_STYLE_GENERIC_SHORT, + /** + * Specific long format, such as "Eastern Standard Time". + * @stable ICU 50 + */ + UTZFMT_STYLE_SPECIFIC_LONG, + /** + * Specific short format, such as "EST", "PDT". + * @stable ICU 50 + */ + UTZFMT_STYLE_SPECIFIC_SHORT, + /** + * Localized GMT offset format, such as "GMT-05:00", "UTC+0100" + * @stable ICU 50 + */ + UTZFMT_STYLE_LOCALIZED_GMT, + /** + * Short localized GMT offset format, such as "GMT-5", "UTC+1:30" + * This style is equivalent to the LDML date format pattern "O". + * @stable ICU 51 + */ + UTZFMT_STYLE_LOCALIZED_GMT_SHORT, + /** + * Short ISO 8601 local time difference (basic format) or the UTC indicator. + * For example, "-05", "+0530", and "Z"(UTC). + * This style is equivalent to the LDML date format pattern "X". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_SHORT, + /** + * Short ISO 8601 locale time difference (basic format). + * For example, "-05" and "+0530". + * This style is equivalent to the LDML date format pattern "x". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT, + /** + * Fixed width ISO 8601 local time difference (basic format) or the UTC indicator. + * For example, "-0500", "+0530", and "Z"(UTC). + * This style is equivalent to the LDML date format pattern "XX". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_FIXED, + /** + * Fixed width ISO 8601 local time difference (basic format). + * For example, "-0500" and "+0530". + * This style is equivalent to the LDML date format pattern "xx". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED, + /** + * ISO 8601 local time difference (basic format) with optional seconds field, or the UTC indicator. + * For example, "-0500", "+052538", and "Z"(UTC). + * This style is equivalent to the LDML date format pattern "XXXX". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_FULL, + /** + * ISO 8601 local time difference (basic format) with optional seconds field. + * For example, "-0500" and "+052538". + * This style is equivalent to the LDML date format pattern "xxxx". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, + /** + * Fixed width ISO 8601 local time difference (extended format) or the UTC indicator. + * For example, "-05:00", "+05:30", and "Z"(UTC). + * This style is equivalent to the LDML date format pattern "XXX". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_EXTENDED_FIXED, + /** + * Fixed width ISO 8601 local time difference (extended format). + * For example, "-05:00" and "+05:30". + * This style is equivalent to the LDML date format pattern "xxx" and "ZZZZZ". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED, + /** + * ISO 8601 local time difference (extended format) with optional seconds field, or the UTC indicator. + * For example, "-05:00", "+05:25:38", and "Z"(UTC). + * This style is equivalent to the LDML date format pattern "XXXXX". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_EXTENDED_FULL, + /** + * ISO 8601 local time difference (extended format) with optional seconds field. + * For example, "-05:00" and "+05:25:38". + * This style is equivalent to the LDML date format pattern "xxxxx". + * @stable ICU 51 + */ + UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL, + /** + * Time Zone ID, such as "America/Los_Angeles". + * @stable ICU 51 + */ + UTZFMT_STYLE_ZONE_ID, + /** + * Short Time Zone ID (BCP 47 Unicode location extension, time zone type value), such as "uslax". + * @stable ICU 51 + */ + UTZFMT_STYLE_ZONE_ID_SHORT, + /** + * Exemplar location, such as "Los Angeles" and "Paris". + * @stable ICU 51 + */ + UTZFMT_STYLE_EXEMPLAR_LOCATION +} UTimeZoneFormatStyle; + +/** + * Constants for GMT offset pattern types. + * @stable ICU 50 + */ +typedef enum UTimeZoneFormatGMTOffsetPatternType { + /** + * Positive offset with hours and minutes fields + * @stable ICU 50 + */ + UTZFMT_PAT_POSITIVE_HM, + /** + * Positive offset with hours, minutes and seconds fields + * @stable ICU 50 + */ + UTZFMT_PAT_POSITIVE_HMS, + /** + * Negative offset with hours and minutes fields + * @stable ICU 50 + */ + UTZFMT_PAT_NEGATIVE_HM, + /** + * Negative offset with hours, minutes and seconds fields + * @stable ICU 50 + */ + UTZFMT_PAT_NEGATIVE_HMS, + /** + * Positive offset with hours field + * @stable ICU 51 + */ + UTZFMT_PAT_POSITIVE_H, + /** + * Negative offset with hours field + * @stable ICU 51 + */ + UTZFMT_PAT_NEGATIVE_H, + + /* The following cannot be #ifndef U_HIDE_INTERNAL_API, needed for other .h declarations */ + /** + * Number of UTimeZoneFormatGMTOffsetPatternType types. + * @internal + */ + UTZFMT_PAT_COUNT = 6 +} UTimeZoneFormatGMTOffsetPatternType; + +/** + * Constants for time types used by TimeZoneFormat APIs for + * receiving time type (standard time, daylight time or unknown). + * @stable ICU 50 + */ +typedef enum UTimeZoneFormatTimeType { + /** + * Unknown + * @stable ICU 50 + */ + UTZFMT_TIME_TYPE_UNKNOWN, + /** + * Standard time + * @stable ICU 50 + */ + UTZFMT_TIME_TYPE_STANDARD, + /** + * Daylight saving time + * @stable ICU 50 + */ + UTZFMT_TIME_TYPE_DAYLIGHT +} UTimeZoneFormatTimeType; + +/** + * Constants for parse option flags, used for specifying optional parse behavior. + * @stable ICU 50 + */ +typedef enum UTimeZoneFormatParseOption { + /** + * No option. + * @stable ICU 50 + */ + UTZFMT_PARSE_OPTION_NONE = 0x00, + /** + * When a time zone display name is not found within a set of display names + * used for the specified style, look for the name from display names used + * by other styles. + * @stable ICU 50 + */ + UTZFMT_PARSE_OPTION_ALL_STYLES = 0x01, + /** + * When parsing a time zone display name in \link UTZFMT_STYLE_SPECIFIC_SHORT \endlink, + * look for the IANA tz database compatible zone abbreviations in addition + * to the localized names coming from the icu::TimeZoneNames currently + * used by the icu::TimeZoneFormat. + * @stable ICU 54 + */ + UTZFMT_PARSE_OPTION_TZ_DATABASE_ABBREVIATIONS = 0x02 +} UTimeZoneFormatParseOption; + +U_CDECL_END + +U_NAMESPACE_BEGIN + +class TimeZoneGenericNames; +class TZDBTimeZoneNames; +class UVector; + +/** + * TimeZoneFormat supports time zone display name formatting and parsing. + * An instance of TimeZoneFormat works as a subformatter of {@link SimpleDateFormat}, + * but you can also directly get a new instance of TimeZoneFormat and + * formatting/parsing time zone display names. + *

+ * ICU implements the time zone display names defined by UTS#35 + * Unicode Locale Data Markup Language (LDML). {@link TimeZoneNames} represents the + * time zone display name data model and this class implements the algorithm for actual + * formatting and parsing. + * + * @see SimpleDateFormat + * @see TimeZoneNames + * @stable ICU 50 + */ +class U_I18N_API TimeZoneFormat : public Format { +public: + /** + * Copy constructor. + * @stable ICU 50 + */ + TimeZoneFormat(const TimeZoneFormat& other); + + /** + * Destructor. + * @stable ICU 50 + */ + virtual ~TimeZoneFormat(); + + /** + * Assignment operator. + * @stable ICU 50 + */ + TimeZoneFormat& operator=(const TimeZoneFormat& other); + + /** + * Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @param other The object to be compared with. + * @return Return true if the given Format objects are semantically equal. + * Objects of different subclasses are considered unequal. + * @stable ICU 50 + */ + virtual bool operator==(const Format& other) const override; + + /** + * Clone this object polymorphically. The caller is responsible + * for deleting the result when done. + * @return A copy of the object + * @stable ICU 50 + */ + virtual TimeZoneFormat* clone() const override; + + /** + * Creates an instance of TimeZoneFormat for the given locale. + * @param locale The locale. + * @param status Receives the status. + * @return An instance of TimeZoneFormat for the given locale, + * owned by the caller. + * @stable ICU 50 + */ + static TimeZoneFormat* U_EXPORT2 createInstance(const Locale& locale, UErrorCode& status); + + /** + * Returns the time zone display name data used by this instance. + * @return The time zone display name data. + * @stable ICU 50 + */ + const TimeZoneNames* getTimeZoneNames() const; + + /** + * Sets the time zone display name data to this format instance. + * The caller should not delete the TimeZoenNames object after it is adopted + * by this call. + * @param tznames TimeZoneNames object to be adopted. + * @stable ICU 50 + */ + void adoptTimeZoneNames(TimeZoneNames *tznames); + + /** + * Sets the time zone display name data to this format instance. + * @param tznames TimeZoneNames object to be set. + * @stable ICU 50 + */ + void setTimeZoneNames(const TimeZoneNames &tznames); + + /** + * Returns the localized GMT format pattern. + * @param pattern Receives the localized GMT format pattern. + * @return A reference to the result pattern. + * @see #setGMTPattern + * @stable ICU 50 + */ + UnicodeString& getGMTPattern(UnicodeString& pattern) const; + + /** + * Sets the localized GMT format pattern. The pattern must contain + * a single argument {0}, for example "GMT {0}". + * @param pattern The localized GMT format pattern to be used by this object. + * @param status Receives the status. + * @see #getGMTPattern + * @stable ICU 50 + */ + void setGMTPattern(const UnicodeString& pattern, UErrorCode& status); + + /** + * Returns the offset pattern used for localized GMT format. + * @param type The offset pattern type enum. + * @param pattern Receives the offset pattern. + * @return A reference to the result pattern. + * @see #setGMTOffsetPattern + * @stable ICU 50 + */ + UnicodeString& getGMTOffsetPattern(UTimeZoneFormatGMTOffsetPatternType type, UnicodeString& pattern) const; + + /** + * Sets the offset pattern for the given offset type. + * @param type The offset pattern type enum. + * @param pattern The offset pattern used for localized GMT format for the type. + * @param status Receives the status. + * @see #getGMTOffsetPattern + * @stable ICU 50 + */ + void setGMTOffsetPattern(UTimeZoneFormatGMTOffsetPatternType type, const UnicodeString& pattern, UErrorCode& status); + + /** + * Returns the decimal digit characters used for localized GMT format. + * The return string contains exactly 10 code points (may include Unicode + * supplementary character) representing digit 0 to digit 9 in the ascending + * order. + * @param digits Receives the decimal digits used for localized GMT format. + * @see #setGMTOffsetDigits + * @stable ICU 50 + */ + UnicodeString& getGMTOffsetDigits(UnicodeString& digits) const; + + /** + * Sets the decimal digit characters used for localized GMT format. + * The input digits must contain exactly 10 code points + * (Unicode supplementary characters are also allowed) representing + * digit 0 to digit 9 in the ascending order. When the input digits + * does not satisfy the condition, U_ILLEGAL_ARGUMENT_ERROR + * will be set to the return status. + * @param digits The decimal digits used for localized GMT format. + * @param status Receives the status. + * @see #getGMTOffsetDigits + * @stable ICU 50 + */ + void setGMTOffsetDigits(const UnicodeString& digits, UErrorCode& status); + + /** + * Returns the localized GMT format string for GMT(UTC) itself (GMT offset is 0). + * @param gmtZeroFormat Receives the localized GMT string string for GMT(UTC) itself. + * @return A reference to the result GMT string. + * @see #setGMTZeroFormat + * @stable ICU 50 + */ + UnicodeString& getGMTZeroFormat(UnicodeString& gmtZeroFormat) const; + + /** + * Sets the localized GMT format string for GMT(UTC) itself (GMT offset is 0). + * @param gmtZeroFormat The localized GMT format string for GMT(UTC). + * @param status Receives the status. + * @see #getGMTZeroFormat + * @stable ICU 50 + */ + void setGMTZeroFormat(const UnicodeString& gmtZeroFormat, UErrorCode& status); + + /** + * Returns the bitwise flags of UTimeZoneFormatParseOption representing the default parse + * options used by this object. + * @return the default parse options. + * @see ParseOption + * @stable ICU 50 + */ + uint32_t getDefaultParseOptions(void) const; + + /** + * Sets the default parse options. + *

Note: By default, an instance of TimeZoneFormat + * created by {@link #createInstance} has no parse options set (UTZFMT_PARSE_OPTION_NONE). + * To specify multiple options, use bitwise flags of UTimeZoneFormatParseOption. + * @see #UTimeZoneFormatParseOption + * @stable ICU 50 + */ + void setDefaultParseOptions(uint32_t flags); + + /** + * Returns the ISO 8601 basic time zone string for the given offset. + * For example, "-08", "-0830" and "Z" + * + * @param offset the offset from GMT(UTC) in milliseconds. + * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. + * @param isShort true if shortest form is used. + * @param ignoreSeconds true if non-zero offset seconds is appended. + * @param result Receives the ISO format string. + * @param status Receives the status + * @return the ISO 8601 basic format. + * @see #formatOffsetISO8601Extended + * @see #parseOffsetISO8601 + * @stable ICU 51 + */ + UnicodeString& formatOffsetISO8601Basic(int32_t offset, UBool useUtcIndicator, UBool isShort, UBool ignoreSeconds, + UnicodeString& result, UErrorCode& status) const; + + /** + * Returns the ISO 8601 extended time zone string for the given offset. + * For example, "-08:00", "-08:30" and "Z" + * + * @param offset the offset from GMT(UTC) in milliseconds. + * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. + * @param isShort true if shortest form is used. + * @param ignoreSeconds true if non-zero offset seconds is appended. + * @param result Receives the ISO format string. + * @param status Receives the status + * @return the ISO 8601 basic format. + * @see #formatOffsetISO8601Extended + * @see #parseOffsetISO8601 + * @stable ICU 51 + */ + UnicodeString& formatOffsetISO8601Extended(int32_t offset, UBool useUtcIndicator, UBool isShort, UBool ignoreSeconds, + UnicodeString& result, UErrorCode& status) const; + + /** + * Returns the localized GMT(UTC) offset format for the given offset. + * The localized GMT offset is defined by; + *

    + *
  • GMT format pattern (e.g. "GMT {0}" - see {@link #getGMTPattern}) + *
  • Offset time pattern (e.g. "+HH:mm" - see {@link #getGMTOffsetPattern}) + *
  • Offset digits (e.g. "0123456789" - see {@link #getGMTOffsetDigits}) + *
  • GMT zero format (e.g. "GMT" - see {@link #getGMTZeroFormat}) + *
+ * This format always uses 2 digit hours and minutes. When the given offset has non-zero + * seconds, 2 digit seconds field will be appended. For example, + * GMT+05:00 and GMT+05:28:06. + * @param offset the offset from GMT(UTC) in milliseconds. + * @param status Receives the status + * @param result Receives the localized GMT format string. + * @return A reference to the result. + * @see #parseOffsetLocalizedGMT + * @stable ICU 50 + */ + UnicodeString& formatOffsetLocalizedGMT(int32_t offset, UnicodeString& result, UErrorCode& status) const; + + /** + * Returns the short localized GMT(UTC) offset format for the given offset. + * The short localized GMT offset is defined by; + *
    + *
  • GMT format pattern (e.g. "GMT {0}" - see {@link #getGMTPattern}) + *
  • Offset time pattern (e.g. "+HH:mm" - see {@link #getGMTOffsetPattern}) + *
  • Offset digits (e.g. "0123456789" - see {@link #getGMTOffsetDigits}) + *
  • GMT zero format (e.g. "GMT" - see {@link #getGMTZeroFormat}) + *
+ * This format uses the shortest representation of offset. The hours field does not + * have leading zero and lower fields with zero will be truncated. For example, + * GMT+5 and GMT+530. + * @param offset the offset from GMT(UTC) in milliseconds. + * @param status Receives the status + * @param result Receives the short localized GMT format string. + * @return A reference to the result. + * @see #parseOffsetShortLocalizedGMT + * @stable ICU 51 + */ + UnicodeString& formatOffsetShortLocalizedGMT(int32_t offset, UnicodeString& result, UErrorCode& status) const; + + using Format::format; + + /** + * Returns the display name of the time zone at the given date for the style. + * @param style The style (e.g. UTZFMT_STYLE_GENERIC_LONG, UTZFMT_STYLE_LOCALIZED_GMT...) + * @param tz The time zone. + * @param date The date. + * @param name Receives the display name. + * @param timeType the output argument for receiving the time type (standard/daylight/unknown) + * used for the display name, or nullptr if the information is not necessary. + * @return A reference to the result + * @see #UTimeZoneFormatStyle + * @see #UTimeZoneFormatTimeType + * @stable ICU 50 + */ + virtual UnicodeString& format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date, + UnicodeString& name, UTimeZoneFormatTimeType* timeType = nullptr) const; + + /** + * Returns offset from GMT(UTC) in milliseconds for the given ISO 8601 + * style time zone string. When the given string is not an ISO 8601 time zone + * string, this method sets the current position as the error index + * to ParsePosition pos and returns 0. + * @param text The text contains ISO8601 style time zone string (e.g. "-08:00", "Z") + * at the position. + * @param pos The ParsePosition object. + * @return The offset from GMT(UTC) in milliseconds for the given ISO 8601 style + * time zone string. + * @see #formatOffsetISO8601Basic + * @see #formatOffsetISO8601Extended + * @stable ICU 50 + */ + int32_t parseOffsetISO8601(const UnicodeString& text, ParsePosition& pos) const; + + /** + * Returns offset from GMT(UTC) in milliseconds for the given localized GMT + * offset format string. When the given string cannot be parsed, this method + * sets the current position as the error index to ParsePosition pos + * and returns 0. + * @param text The text contains a localized GMT offset string at the position. + * @param pos The ParsePosition object. + * @return The offset from GMT(UTC) in milliseconds for the given localized GMT + * offset format string. + * @see #formatOffsetLocalizedGMT + * @stable ICU 50 + */ + int32_t parseOffsetLocalizedGMT(const UnicodeString& text, ParsePosition& pos) const; + + /** + * Returns offset from GMT(UTC) in milliseconds for the given short localized GMT + * offset format string. When the given string cannot be parsed, this method + * sets the current position as the error index to ParsePosition pos + * and returns 0. + * @param text The text contains a short localized GMT offset string at the position. + * @param pos The ParsePosition object. + * @return The offset from GMT(UTC) in milliseconds for the given short localized GMT + * offset format string. + * @see #formatOffsetShortLocalizedGMT + * @stable ICU 51 + */ + int32_t parseOffsetShortLocalizedGMT(const UnicodeString& text, ParsePosition& pos) const; + + /** + * Returns a TimeZone by parsing the time zone string according to + * the given parse position, the specified format style and parse options. + * + * @param text The text contains a time zone string at the position. + * @param style The format style + * @param pos The position. + * @param parseOptions The parse options represented by bitwise flags of UTimeZoneFormatParseOption. + * @param timeType The output argument for receiving the time type (standard/daylight/unknown), + * or nullptr if the information is not necessary. + * @return A TimeZone, or null if the input could not be parsed. + * @see UTimeZoneFormatStyle + * @see UTimeZoneFormatParseOption + * @see UTimeZoneFormatTimeType + * @stable ICU 50 + */ + virtual TimeZone* parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos, + int32_t parseOptions, UTimeZoneFormatTimeType* timeType = nullptr) const; + + /** + * Returns a TimeZone by parsing the time zone string according to + * the given parse position, the specified format style and the default parse options. + * + * @param text The text contains a time zone string at the position. + * @param style The format style + * @param pos The position. + * @param timeType The output argument for receiving the time type (standard/daylight/unknown), + * or nullptr if the information is not necessary. + * @return A TimeZone, or null if the input could not be parsed. + * @see UTimeZoneFormatStyle + * @see UTimeZoneFormatParseOption + * @see UTimeZoneFormatTimeType + * @stable ICU 50 + */ + TimeZone* parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos, + UTimeZoneFormatTimeType* timeType = nullptr) const; + + /* ---------------------------------------------- + * Format APIs + * ---------------------------------------------- */ + + /** + * Format an object to produce a time zone display string using localized GMT offset format. + * This method handles Formattable objects with a TimeZone. If a the Formattable + * object type is not a TimeZone, then it returns a failing UErrorCode. + * @param obj The object to format. Must be a TimeZone. + * @param appendTo Output parameter to receive result. Result is appended to existing contents. + * @param pos On input: an alignment field, if desired. On output: the offsets of the alignment field. + * @param status Output param filled with success/failure status. + * @return Reference to 'appendTo' parameter. + * @stable ICU 50 + */ + virtual UnicodeString& format(const Formattable& obj, UnicodeString& appendTo, + FieldPosition& pos, UErrorCode& status) const override; + + /** + * Parse a string to produce an object. This methods handles parsing of + * time zone display strings into Formattable objects with TimeZone. + * @param source The string to be parsed into an object. + * @param result Formattable to be set to the parse result. If parse fails, return contents are undefined. + * @param parse_pos The position to start parsing at. Upon return this param is set to the position after the + * last character successfully parsed. If the source is not parsed successfully, this param + * will remain unchanged. + * @return A newly created Formattable* object, or nullptr on failure. The caller owns this and should + * delete it when done. + * @stable ICU 50 + */ + virtual void parseObject(const UnicodeString& source, Formattable& result, ParsePosition& parse_pos) const override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * @stable ICU 50 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * ICU "poor man's RTTI", returns a UClassID for the actual class. + * @stable ICU 50 + */ + virtual UClassID getDynamicClassID() const override; + +protected: + /** + * Constructs a TimeZoneFormat object for the specified locale. + * @param locale the locale + * @param status receives the status. + * @stable ICU 50 + */ + TimeZoneFormat(const Locale& locale, UErrorCode& status); + +private: + /* Locale of this object */ + Locale fLocale; + + /* Stores the region (could be implicit default) */ + char fTargetRegion[ULOC_COUNTRY_CAPACITY]; + + /* TimeZoneNames object used by this formatter */ + TimeZoneNames* fTimeZoneNames; + + /* TimeZoneGenericNames object used by this formatter - lazily instantiated */ + TimeZoneGenericNames* fTimeZoneGenericNames; + + /* Localized GMT format pattern - e.g. "GMT{0}" */ + UnicodeString fGMTPattern; + + /* Array of offset patterns used by Localized GMT format - e.g. "+HH:mm" */ + UnicodeString fGMTOffsetPatterns[UTZFMT_PAT_COUNT]; + + /* Localized decimal digits used by Localized GMT format */ + UChar32 fGMTOffsetDigits[10]; + + /* Localized GMT zero format - e.g. "GMT" */ + UnicodeString fGMTZeroFormat; + + /* Bit flags representing parse options */ + uint32_t fDefParseOptionFlags; + + /* Constant parts of GMT format pattern, populated from localized GMT format pattern*/ + UnicodeString fGMTPatternPrefix; /* Substring before {0} */ + UnicodeString fGMTPatternSuffix; /* Substring after {0} */ + + /* Compiled offset patterns generated from fGMTOffsetPatterns[] */ + UVector* fGMTOffsetPatternItems[UTZFMT_PAT_COUNT]; + + UBool fAbuttingOffsetHoursAndMinutes; + + /* TZDBTimeZoneNames object used for parsing */ + TZDBTimeZoneNames* fTZDBTimeZoneNames; + + /** + * Returns the time zone's specific format string. + * @param tz the time zone + * @param stdType the name type used for standard time + * @param dstType the name type used for daylight time + * @param date the date + * @param name receives the time zone's specific format name string + * @param timeType when null, actual time type is set + * @return a reference to name. + */ + UnicodeString& formatSpecific(const TimeZone& tz, UTimeZoneNameType stdType, UTimeZoneNameType dstType, + UDate date, UnicodeString& name, UTimeZoneFormatTimeType *timeType) const; + + /** + * Returns the time zone's generic format string. + * @param tz the time zone + * @param genType the generic name type + * @param date the date + * @param name receives the time zone's generic format name string + * @return a reference to name. + */ + UnicodeString& formatGeneric(const TimeZone& tz, int32_t genType, UDate date, UnicodeString& name) const; + + /** + * Lazily create a TimeZoneGenericNames instance + * @param status receives the status + * @return the cached TimeZoneGenericNames. + */ + const TimeZoneGenericNames* getTimeZoneGenericNames(UErrorCode& status) const; + + /** + * Lazily create a TZDBTimeZoneNames instance + * @param status receives the status + * @return the cached TZDBTimeZoneNames. + */ + const TZDBTimeZoneNames* getTZDBTimeZoneNames(UErrorCode& status) const; + + /** + * Private method returning the time zone's exemplar location string. + * This method will never return empty. + * @param tz the time zone + * @param name receives the time zone's exemplar location name + * @return a reference to name. + */ + UnicodeString& formatExemplarLocation(const TimeZone& tz, UnicodeString& name) const; + + /** + * Private enum specifying a combination of offset fields + */ + enum OffsetFields { + FIELDS_H, + FIELDS_HM, + FIELDS_HMS + }; + + /** + * Parses the localized GMT pattern string and initialize + * localized gmt pattern fields. + * @param gmtPattern the localized GMT pattern string such as "GMT {0}" + * @param status U_ILLEGAL_ARGUMENT_ERROR is set when the specified pattern does not + * contain an argument "{0}". + */ + void initGMTPattern(const UnicodeString& gmtPattern, UErrorCode& status); + + /** + * Parse the GMT offset pattern into runtime optimized format. + * @param pattern the offset pattern string + * @param required the required set of fields, such as FIELDS_HM + * @param status U_ILLEGAL_ARGUMENT is set when the specified pattern does not contain + * pattern letters for the required fields. + * @return A list of GMTOffsetField objects, or nullptr on error. + */ + static UVector* parseOffsetPattern(const UnicodeString& pattern, OffsetFields required, UErrorCode& status); + + /** + * Appends seconds field to the offset pattern with hour/minute + * Note: This code will be obsoleted once we add hour-minute-second pattern data in CLDR. + * @param offsetHM the offset pattern including hours and minutes fields + * @param result the output offset pattern including hour, minute and seconds fields + * @param status receives the status + * @return a reference to result + */ + static UnicodeString& expandOffsetPattern(const UnicodeString& offsetHM, UnicodeString& result, UErrorCode& status); + + /** + * Truncates minutes field to the offset pattern with hour/minute + * Note: This code will be obsoleted once we add hour pattern data in CLDR. + * @param offsetHM the offset pattern including hours and minutes fields + * @param result the output offset pattern including only hours field + * @param status receives the status + * @return a reference to result + */ + static UnicodeString& truncateOffsetPattern(const UnicodeString& offsetHM, UnicodeString& result, UErrorCode& status); + + /** + * Break input string into UChar32[]. Each array element represents + * a code point. This method is used for parsing localized digit + * characters and support characters in Unicode supplemental planes. + * @param str the string + * @param codeArray receives the result + * @param capacity the capacity of codeArray + * @return true when the specified code array is fully filled with code points + * (no under/overflow). + */ + static UBool toCodePoints(const UnicodeString& str, UChar32* codeArray, int32_t capacity); + + /** + * Private method supprting all of ISO8601 formats + * @param offset the offset from GMT(UTC) in milliseconds. + * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. + * @param isShort true if shortest form is used. + * @param ignoreSeconds true if non-zero offset seconds is appended. + * @param result Receives the result + * @param status Receives the status + * @return the ISO 8601 basic format. + */ + UnicodeString& formatOffsetISO8601(int32_t offset, UBool isBasic, UBool useUtcIndicator, + UBool isShort, UBool ignoreSeconds, UnicodeString& result, UErrorCode& status) const; + + /** + * Private method used for localized GMT formatting. + * @param offset the zone's UTC offset + * @param isShort true if the short localized GMT format is desired. + * @param result receives the localized GMT format string + * @param status receives the status + */ + UnicodeString& formatOffsetLocalizedGMT(int32_t offset, UBool isShort, UnicodeString& result, UErrorCode& status) const; + + /** + * Returns offset from GMT(UTC) in milliseconds for the given ISO 8601 style + * (extended format) time zone string. When the given string is not an ISO 8601 time + * zone string, this method sets the current position as the error index + * to ParsePosition pos and returns 0. + * @param text the text contains ISO 8601 style time zone string (e.g. "-08:00", "Z") + * at the position. + * @param pos the position, non-negative error index will be set on failure. + * @param extendedOnly true if parsing the text as ISO 8601 extended offset format (e.g. "-08:00"), + * or false to evaluate the text as basic format. + * @param hasDigitOffset receiving if the parsed zone string contains offset digits. + * @return the offset from GMT(UTC) in milliseconds for the given ISO 8601 style + * time zone string. + */ + int32_t parseOffsetISO8601(const UnicodeString& text, ParsePosition& pos, UBool extendedOnly, + UBool* hasDigitOffset = nullptr) const; + + /** + * Appends localized digits to the buffer. + * This code assumes that the input number is 0 - 59 + * @param buf the target buffer + * @param n the integer number + * @param minDigits the minimum digits width + */ + void appendOffsetDigits(UnicodeString& buf, int32_t n, uint8_t minDigits) const; + + /** + * Returns offset from GMT(UTC) in milliseconds for the given localized GMT + * offset format string. When the given string cannot be parsed, this method + * sets the current position as the error index to ParsePosition pos + * and returns 0. + * @param text the text contains a localized GMT offset string at the position. + * @param pos the position, non-negative error index will be set on failure. + * @param isShort true if this parser to try the short format first + * @param hasDigitOffset receiving if the parsed zone string contains offset digits. + * @return the offset from GMT(UTC) in milliseconds for the given localized GMT + * offset format string. + */ + int32_t parseOffsetLocalizedGMT(const UnicodeString& text, ParsePosition& pos, + UBool isShort, UBool* hasDigitOffset) const; + + /** + * Parse localized GMT format generated by the patter used by this formatter, except + * GMT Zero format. + * @param text the input text + * @param start the start index + * @param isShort true if the short localized format is parsed. + * @param parsedLen receives the parsed length + * @return the parsed offset in milliseconds + */ + int32_t parseOffsetLocalizedGMTPattern(const UnicodeString& text, int32_t start, + UBool isShort, int32_t& parsedLen) const; + + /** + * Parses localized GMT offset fields into offset. + * @param text the input text + * @param start the start index + * @param isShort true if this is a short format - currently not used + * @param parsedLen the parsed length, or 0 on failure. + * @return the parsed offset in milliseconds. + */ + int32_t parseOffsetFields(const UnicodeString& text, int32_t start, UBool isShort, int32_t& parsedLen) const; + + /** + * Parse localized GMT offset fields with the given pattern. + * @param text the input text + * @param start the start index + * @param pattenItems the pattern (already itemized) + * @param forceSingleHourDigit true if hours field is parsed as a single digit + * @param hour receives the hour offset field + * @param min receives the minute offset field + * @param sec receives the second offset field + * @return the parsed length + */ + int32_t parseOffsetFieldsWithPattern(const UnicodeString& text, int32_t start, + UVector* patternItems, UBool forceSingleHourDigit, int32_t& hour, int32_t& min, int32_t& sec) const; + + /** + * Parses abutting localized GMT offset fields (such as 0800) into offset. + * @param text the input text + * @param start the start index + * @param parsedLen the parsed length, or 0 on failure + * @return the parsed offset in milliseconds. + */ + int32_t parseAbuttingOffsetFields(const UnicodeString& text, int32_t start, int32_t& parsedLen) const; + + /** + * Parses the input text using the default format patterns (e.g. "UTC{0}"). + * @param text the input text + * @param start the start index + * @param parsedLen the parsed length, or 0 on failure + * @return the parsed offset in milliseconds. + */ + int32_t parseOffsetDefaultLocalizedGMT(const UnicodeString& text, int start, int32_t& parsedLen) const; + + /** + * Parses the input GMT offset fields with the default offset pattern. + * @param text the input text + * @param start the start index + * @param separator the separator character, e.g. ':' + * @param parsedLen the parsed length, or 0 on failure. + * @return the parsed offset in milliseconds. + */ + int32_t parseDefaultOffsetFields(const UnicodeString& text, int32_t start, char16_t separator, + int32_t& parsedLen) const; + + /** + * Reads an offset field value. This method will stop parsing when + * 1) number of digits reaches maxDigits + * 2) just before already parsed number exceeds maxVal + * + * @param text the text + * @param start the start offset + * @param minDigits the minimum number of required digits + * @param maxDigits the maximum number of digits + * @param minVal the minimum value + * @param maxVal the maximum value + * @param parsedLen the actual parsed length. + * @return the integer value parsed + */ + int32_t parseOffsetFieldWithLocalizedDigits(const UnicodeString& text, int32_t start, + uint8_t minDigits, uint8_t maxDigits, uint16_t minVal, uint16_t maxVal, int32_t& parsedLen) const; + + /** + * Reads a single decimal digit, either localized digits used by this object + * or any Unicode numeric character. + * @param text the text + * @param start the start index + * @param len the actual length read from the text + * the start index is not a decimal number. + * @return the integer value of the parsed digit, or -1 on failure. + */ + int32_t parseSingleLocalizedDigit(const UnicodeString& text, int32_t start, int32_t& len) const; + + /** + * Formats offset using ASCII digits. The input offset range must be + * within +/-24 hours (exclusive). + * @param offset The offset + * @param sep The field separator character or 0 if not required + * @param minFields The minimum fields + * @param maxFields The maximum fields + * @return The offset string + */ + static UnicodeString& formatOffsetWithAsciiDigits(int32_t offset, char16_t sep, + OffsetFields minFields, OffsetFields maxFields, UnicodeString& result); + + /** + * Parses offset represented by contiguous ASCII digits. + *

+ * Note: This method expects the input position is already at the start of + * ASCII digits and does not parse sign (+/-). + * @param text The text contains a sequence of ASCII digits + * @param pos The parse position + * @param minFields The minimum Fields to be parsed + * @param maxFields The maximum Fields to be parsed + * @param fixedHourWidth true if hours field must be width of 2 + * @return Parsed offset, 0 or positive number. + */ + static int32_t parseAbuttingAsciiOffsetFields(const UnicodeString& text, ParsePosition& pos, + OffsetFields minFields, OffsetFields maxFields, UBool fixedHourWidth); + + /** + * Parses offset represented by ASCII digits and separators. + *

+ * Note: This method expects the input position is already at the start of + * ASCII digits and does not parse sign (+/-). + * @param text The text + * @param pos The parse position + * @param sep The separator character + * @param minFields The minimum Fields to be parsed + * @param maxFields The maximum Fields to be parsed + * @return Parsed offset, 0 or positive number. + */ + static int32_t parseAsciiOffsetFields(const UnicodeString& text, ParsePosition& pos, char16_t sep, + OffsetFields minFields, OffsetFields maxFields); + + /** + * Unquotes the message format style pattern. + * @param pattern the pattern + * @param result receive the unquoted pattern. + * @return A reference to result. + */ + static UnicodeString& unquote(const UnicodeString& pattern, UnicodeString& result); + + /** + * Initialize localized GMT format offset hour/min/sec patterns. + * This method parses patterns into optimized run-time format. + * @param status receives the status. + */ + void initGMTOffsetPatterns(UErrorCode& status); + + /** + * Check if there are any GMT format offset patterns without + * any separators between hours field and minutes field and update + * fAbuttingOffsetHoursAndMinutes field. This method must be called + * after all patterns are parsed into pattern items. + */ + void checkAbuttingHoursAndMinutes(); + + /** + * Creates an instance of TimeZone for the given offset + * @param offset the offset + * @return A TimeZone with the given offset + */ + TimeZone* createTimeZoneForOffset(int32_t offset) const; + + /** + * Returns the time type for the given name type + * @param nameType the name type + * @return the time type (unknown/standard/daylight) + */ + static UTimeZoneFormatTimeType getTimeType(UTimeZoneNameType nameType); + + /** + * Returns the time zone ID of a match at the specified index within + * the MatchInfoCollection. + * @param matches the collection of matches + * @param idx the index within matches + * @param tzID receives the resolved time zone ID + * @return a reference to tzID. + */ + UnicodeString& getTimeZoneID(const TimeZoneNames::MatchInfoCollection* matches, int32_t idx, UnicodeString& tzID) const; + + + /** + * Parse a zone ID. + * @param text the text contains a time zone ID string at the position. + * @param pos the position + * @param tzID receives the zone ID + * @return a reference to tzID + */ + UnicodeString& parseZoneID(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; + + /** + * Parse a short zone ID. + * @param text the text contains a short time zone ID string at the position. + * @param pos the position + * @param tzID receives the short zone ID + * @return a reference to tzID + */ + UnicodeString& parseShortZoneID(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; + + /** + * Parse an exemplar location string. + * @param text the text contains an exemplar location string at the position. + * @param pos the position. + * @param tzID receives the time zone ID + * @return a reference to tzID + */ + UnicodeString& parseExemplarLocation(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; +}; + +U_NAMESPACE_END + +#endif /* !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tznames.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tznames.h new file mode 100644 index 0000000000000000000000000000000000000000..2b494734b739aa5284753dc0a5733a7732fbc07e --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tznames.h @@ -0,0 +1,419 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2011-2016, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +*/ +#ifndef __TZNAMES_H +#define __TZNAMES_H + +/** + * \file + * \brief C++ API: TimeZoneNames + */ +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uloc.h" +#include "unicode/unistr.h" + +U_CDECL_BEGIN + +/** + * Constants for time zone display name types. + * @stable ICU 50 + */ +typedef enum UTimeZoneNameType { + /** + * Unknown display name type. + * @stable ICU 50 + */ + UTZNM_UNKNOWN = 0x00, + /** + * Long display name, such as "Eastern Time". + * @stable ICU 50 + */ + UTZNM_LONG_GENERIC = 0x01, + /** + * Long display name for standard time, such as "Eastern Standard Time". + * @stable ICU 50 + */ + UTZNM_LONG_STANDARD = 0x02, + /** + * Long display name for daylight saving time, such as "Eastern Daylight Time". + * @stable ICU 50 + */ + UTZNM_LONG_DAYLIGHT = 0x04, + /** + * Short display name, such as "ET". + * @stable ICU 50 + */ + UTZNM_SHORT_GENERIC = 0x08, + /** + * Short display name for standard time, such as "EST". + * @stable ICU 50 + */ + UTZNM_SHORT_STANDARD = 0x10, + /** + * Short display name for daylight saving time, such as "EDT". + * @stable ICU 50 + */ + UTZNM_SHORT_DAYLIGHT = 0x20, + /** + * Exemplar location name, such as "Los Angeles". + * @stable ICU 51 + */ + UTZNM_EXEMPLAR_LOCATION = 0x40 +} UTimeZoneNameType; + +U_CDECL_END + +U_NAMESPACE_BEGIN + +class UVector; +struct MatchInfo; + +/** + * TimeZoneNames is an abstract class representing the time zone display name data model defined + * by UTS#35 Unicode Locale Data Markup Language (LDML). + * The model defines meta zone, which is used for storing a set of display names. A meta zone can be shared + * by multiple time zones. Also a time zone may have multiple meta zone historic mappings. + *

+ * For example, people in the United States refer the zone used by the east part of North America as "Eastern Time". + * The tz database contains multiple time zones "America/New_York", "America/Detroit", "America/Montreal" and some + * others that belong to "Eastern Time". However, assigning different display names to these time zones does not make + * much sense for most of people. + *

+ * In CLDR (which uses LDML for representing locale data), the display name + * "Eastern Time" is stored as long generic display name of a meta zone identified by the ID "America_Eastern". + * Then, there is another table maintaining the historic mapping to meta zones for each time zone. The time zones in + * the above example ("America/New_York", "America/Detroit"...) are mapped to the meta zone "America_Eastern". + *

+ * Sometimes, a time zone is mapped to a different time zone in the past. For example, "America/Indiana/Knox" + * had been moving "Eastern Time" and "Central Time" back and forth. Therefore, it is necessary that time zone + * to meta zones mapping data are stored by date range. + * + *

Note: + * The methods in this class assume that time zone IDs are already canonicalized. For example, you may not get proper + * result returned by a method with time zone ID "America/Indiana/Indianapolis", because it's not a canonical time zone + * ID (the canonical time zone ID for the time zone is "America/Indianapolis". See + * {@link TimeZone#getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)} about ICU + * canonical time zone IDs. + * + *

+ * In CLDR, most of time zone display names except location names are provided through meta zones. But a time zone may + * have a specific name that is not shared with other time zones. + * + * For example, time zone "Europe/London" has English long name for standard time "Greenwich Mean Time", which is also + * shared with other time zones. However, the long name for daylight saving time is "British Summer Time", which is only + * used for "Europe/London". + * + *

+ * {@link #getTimeZoneDisplayName} is designed for accessing a name only used by a single time zone. + * But is not necessarily mean that a subclass implementation use the same model with CLDR. A subclass implementation + * may provide time zone names only through {@link #getTimeZoneDisplayName}, or only through {@link #getMetaZoneDisplayName}, + * or both. + * + *

+ * The default TimeZoneNames implementation returned by {@link #createInstance} + * uses the locale data imported from CLDR. In CLDR, set of meta zone IDs and mappings between zone IDs and meta zone + * IDs are shared by all locales. Therefore, the behavior of {@link #getAvailableMetaZoneIDs}, + * {@link #getMetaZoneID}, and {@link #getReferenceZoneID} won't be changed no matter + * what locale is used for getting an instance of TimeZoneNames. + * + * @stable ICU 50 + */ +class U_I18N_API TimeZoneNames : public UObject { +public: + /** + * Destructor. + * @stable ICU 50 + */ + virtual ~TimeZoneNames(); + + /** + * Return true if the given TimeZoneNames objects are semantically equal. + * @param other the object to be compared with. + * @return Return true if the given Format objects are semantically equal. + * @stable ICU 50 + */ + virtual bool operator==(const TimeZoneNames& other) const = 0; + + /** + * Return true if the given TimeZoneNames objects are not semantically + * equal. + * @param other the object to be compared with. + * @return Return true if the given Format objects are not semantically equal. + * @stable ICU 50 + */ + bool operator!=(const TimeZoneNames& other) const { return !operator==(other); } + + /** + * Clone this object polymorphically. The caller is responsible + * for deleting the result when done. + * @return A copy of the object + * @stable ICU 50 + */ + virtual TimeZoneNames* clone() const = 0; + + /** + * Returns an instance of TimeZoneNames for the specified locale. + * + * @param locale The locale. + * @param status Receives the status. + * @return An instance of TimeZoneNames + * @stable ICU 50 + */ + static TimeZoneNames* U_EXPORT2 createInstance(const Locale& locale, UErrorCode& status); + + /** + * Returns an instance of TimeZoneNames containing only short specific + * zone names (SHORT_STANDARD and SHORT_DAYLIGHT), + * compatible with the IANA tz database's zone abbreviations (not localized). + *
+ * Note: The input locale is used for resolving ambiguous names (e.g. "IST" is parsed + * as Israel Standard Time for Israel, while it is parsed as India Standard Time for + * all other regions). The zone names returned by this instance are not localized. + * @stable ICU 54 + */ + static TimeZoneNames* U_EXPORT2 createTZDBInstance(const Locale& locale, UErrorCode& status); + + /** + * Returns an enumeration of all available meta zone IDs. + * @param status Receives the status. + * @return an enumeration object, owned by the caller. + * @stable ICU 50 + */ + virtual StringEnumeration* getAvailableMetaZoneIDs(UErrorCode& status) const = 0; + + /** + * Returns an enumeration of all available meta zone IDs used by the given time zone. + * @param tzID The canonical time zone ID. + * @param status Receives the status. + * @return an enumeration object, owned by the caller. + * @stable ICU 50 + */ + virtual StringEnumeration* getAvailableMetaZoneIDs(const UnicodeString& tzID, UErrorCode& status) const = 0; + + /** + * Returns the meta zone ID for the given canonical time zone ID at the given date. + * @param tzID The canonical time zone ID. + * @param date The date. + * @param mzID Receives the meta zone ID for the given time zone ID at the given date. If the time zone does not have a + * corresponding meta zone at the given date or the implementation does not support meta zones, "bogus" state + * is set. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getMetaZoneID(const UnicodeString& tzID, UDate date, UnicodeString& mzID) const = 0; + + /** + * Returns the reference zone ID for the given meta zone ID for the region. + * + * Note: Each meta zone must have a reference zone associated with a special region "001" (world). + * Some meta zones may have region specific reference zone IDs other than the special region + * "001". When a meta zone does not have any region specific reference zone IDs, this method + * return the reference zone ID for the special region "001" (world). + * + * @param mzID The meta zone ID. + * @param region The region. + * @param tzID Receives the reference zone ID ("golden zone" in the LDML specification) for the given time zone ID for the + * region. If the meta zone is unknown or the implementation does not support meta zones, "bogus" state + * is set. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getReferenceZoneID(const UnicodeString& mzID, const char* region, UnicodeString& tzID) const = 0; + + /** + * Returns the display name of the meta zone. + * @param mzID The meta zone ID. + * @param type The display name type. See {@link #UTimeZoneNameType}. + * @param name Receives the display name of the meta zone. When this object does not have a localized display name for the given + * meta zone with the specified type or the implementation does not provide any display names associated + * with meta zones, "bogus" state is set. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getMetaZoneDisplayName(const UnicodeString& mzID, UTimeZoneNameType type, UnicodeString& name) const = 0; + + /** + * Returns the display name of the time zone. Unlike {@link #getDisplayName}, + * this method does not get a name from a meta zone used by the time zone. + * @param tzID The canonical time zone ID. + * @param type The display name type. See {@link #UTimeZoneNameType}. + * @param name Receives the display name for the time zone. When this object does not have a localized display name for the given + * time zone with the specified type, "bogus" state is set. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getTimeZoneDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UnicodeString& name) const = 0; + + /** + * Returns the exemplar location name for the given time zone. When this object does not have a localized location + * name, the default implementation may still returns a programmatically generated name with the logic described + * below. + *

    + *
  1. Check if the ID contains "/". If not, return null. + *
  2. Check if the ID does not start with "Etc/" or "SystemV/". If it does, return null. + *
  3. Extract a substring after the last occurrence of "/". + *
  4. Replace "_" with " ". + *
+ * For example, "New York" is returned for the time zone ID "America/New_York" when this object does not have the + * localized location name. + * + * @param tzID The canonical time zone ID + * @param name Receives the exemplar location name for the given time zone, or "bogus" state is set when a localized + * location name is not available and the fallback logic described above cannot extract location from the ID. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getExemplarLocationName(const UnicodeString& tzID, UnicodeString& name) const; + + /** + * Returns the display name of the time zone at the given date. + *

+ * Note: This method calls the subclass's {@link #getTimeZoneDisplayName} first. When the + * result is bogus, this method calls {@link #getMetaZoneID} to get the meta zone ID mapped from the + * time zone, then calls {@link #getMetaZoneDisplayName}. + * + * @param tzID The canonical time zone ID. + * @param type The display name type. See {@link #UTimeZoneNameType}. + * @param date The date. + * @param name Receives the display name for the time zone at the given date. When this object does not have a localized display + * name for the time zone with the specified type and date, "bogus" state is set. + * @return A reference to the result. + * @stable ICU 50 + */ + virtual UnicodeString& getDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UDate date, UnicodeString& name) const; + + /** + * @internal ICU internal only, for specific users only until proposed publicly. + */ + virtual void loadAllDisplayNames(UErrorCode& status); + + /** + * @internal ICU internal only, for specific users only until proposed publicly. + */ + virtual void getDisplayNames(const UnicodeString& tzID, const UTimeZoneNameType types[], int32_t numTypes, UDate date, UnicodeString dest[], UErrorCode& status) const; + + /** + * MatchInfoCollection represents a collection of time zone name matches used by + * {@link TimeZoneNames#find}. + * @internal + */ + class U_I18N_API MatchInfoCollection : public UMemory { + public: + /** + * Constructor. + * @internal + */ + MatchInfoCollection(); + /** + * Destructor. + * @internal + */ + virtual ~MatchInfoCollection(); + +#ifndef U_HIDE_INTERNAL_API + /** + * Adds a zone match. + * @param nameType The name type. + * @param matchLength The match length. + * @param tzID The time zone ID. + * @param status Receives the status + * @internal + */ + void addZone(UTimeZoneNameType nameType, int32_t matchLength, + const UnicodeString& tzID, UErrorCode& status); + + /** + * Adds a meata zone match. + * @param nameType The name type. + * @param matchLength The match length. + * @param mzID The metazone ID. + * @param status Receives the status + * @internal + */ + void addMetaZone(UTimeZoneNameType nameType, int32_t matchLength, + const UnicodeString& mzID, UErrorCode& status); + + /** + * Returns the number of entries available in this object. + * @return The number of entries. + * @internal + */ + int32_t size() const; + + /** + * Returns the time zone name type of a match at the specified index. + * @param idx The index + * @return The time zone name type. If the specified idx is out of range, + * it returns UTZNM_UNKNOWN. + * @see UTimeZoneNameType + * @internal + */ + UTimeZoneNameType getNameTypeAt(int32_t idx) const; + + /** + * Returns the match length of a match at the specified index. + * @param idx The index + * @return The match length. If the specified idx is out of range, + * it returns 0. + * @internal + */ + int32_t getMatchLengthAt(int32_t idx) const; + + /** + * Gets the zone ID of a match at the specified index. + * @param idx The index + * @param tzID Receives the zone ID. + * @return true if the zone ID was set to tzID. + * @internal + */ + UBool getTimeZoneIDAt(int32_t idx, UnicodeString& tzID) const; + + /** + * Gets the metazone ID of a match at the specified index. + * @param idx The index + * @param mzID Receives the metazone ID + * @return true if the meta zone ID was set to mzID. + * @internal + */ + UBool getMetaZoneIDAt(int32_t idx, UnicodeString& mzID) const; +#endif /* U_HIDE_INTERNAL_API */ + + private: + UVector* fMatches; // vector of MatchEntry + + UVector* matches(UErrorCode& status); + }; + + /** + * Finds time zone name prefix matches for the input text at the + * given offset and returns a collection of the matches. + * @param text The text. + * @param start The starting offset within the text. + * @param types The set of name types represented by bitwise flags of UTimeZoneNameType enums, + * or UTZNM_UNKNOWN for all name types. + * @param status Receives the status. + * @return A collection of matches (owned by the caller), or nullptr if no matches are found. + * @see UTimeZoneNameType + * @see MatchInfoCollection + * @internal + */ + virtual MatchInfoCollection* find(const UnicodeString& text, int32_t start, uint32_t types, UErrorCode& status) const = 0; +}; + +U_NAMESPACE_END + +#endif + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzrule.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzrule.h new file mode 100644 index 0000000000000000000000000000000000000000..9ec1e96179c9f49f41ac1b1caf39795eb3471014 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tzrule.h @@ -0,0 +1,820 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2008, International Business Machines Corporation and * +* others. All Rights Reserved. * +******************************************************************************* +*/ +#ifndef TZRULE_H +#define TZRULE_H + +/** + * \file + * \brief C++ API: Time zone rule classes + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" +#include "unicode/unistr.h" +#include "unicode/dtrule.h" + +U_NAMESPACE_BEGIN + +/** + * TimeZoneRule is a class representing a rule for time zone. + * TimeZoneRule has a set of time zone attributes, such as zone name, + * raw offset (UTC offset for standard time) and daylight saving time offset. + * + * @stable ICU 3.8 + */ +class U_I18N_API TimeZoneRule : public UObject { +public: + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~TimeZoneRule(); + + /** + * Clone this TimeZoneRule object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + virtual TimeZoneRule* clone() const = 0; + + /** + * Return true if the given TimeZoneRule objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically equal. + * @stable ICU 3.8 + */ + virtual bool operator==(const TimeZoneRule& that) const; + + /** + * Return true if the given TimeZoneRule objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically unequal. + * @stable ICU 3.8 + */ + virtual bool operator!=(const TimeZoneRule& that) const; + + /** + * Fills in "name" with the name of this time zone. + * @param name Receives the name of this time zone. + * @return A reference to "name" + * @stable ICU 3.8 + */ + UnicodeString& getName(UnicodeString& name) const; + + /** + * Gets the standard time offset. + * @return The standard time offset from UTC in milliseconds. + * @stable ICU 3.8 + */ + int32_t getRawOffset(void) const; + + /** + * Gets the amount of daylight saving delta time from the standard time. + * @return The amount of daylight saving offset used by this rule + * in milliseconds. + * @stable ICU 3.8 + */ + int32_t getDSTSavings(void) const; + + /** + * Returns if this rule represents the same rule and offsets as another. + * When two TimeZoneRule objects differ only its names, this method + * returns true. + * @param other The TimeZoneRule object to be compared with. + * @return true if the other TimeZoneRule is the same as this one. + * @stable ICU 3.8 + */ + virtual UBool isEquivalentTo(const TimeZoneRule& other) const; + + /** + * Gets the very first time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the very first time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0; + + /** + * Gets the final time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the final time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0; + + /** + * Gets the first time when this rule takes effect after the specified time. + * @param base The first start time after this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The first time when this rule takes effect after + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const = 0; + + /** + * Gets the most recent time when this rule takes effect before the specified time. + * @param base The most recent time before this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The most recent time when this rule takes effect before + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const = 0; + +protected: + + /** + * Constructs a TimeZoneRule with the name, the GMT offset of its + * standard time and the amount of daylight saving offset adjustment. + * @param name The time zone name. + * @param rawOffset The UTC offset of its standard time in milliseconds. + * @param dstSavings The amount of daylight saving offset adjustment in milliseconds. + * If this ia a rule for standard time, the value of this argument is 0. + * @stable ICU 3.8 + */ + TimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings); + + /** + * Copy constructor. + * @param source The TimeZoneRule object to be copied. + * @stable ICU 3.8 + */ + TimeZoneRule(const TimeZoneRule& source); + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + TimeZoneRule& operator=(const TimeZoneRule& right); + +private: + UnicodeString fName; // time name + int32_t fRawOffset; // UTC offset of the standard time in milliseconds + int32_t fDSTSavings; // DST saving amount in milliseconds +}; + +/** + * InitialTimeZoneRule represents a time zone rule + * representing a time zone effective from the beginning and + * has no actual start times. + * @stable ICU 3.8 + */ +class U_I18N_API InitialTimeZoneRule : public TimeZoneRule { +public: + /** + * Constructs an InitialTimeZoneRule with the name, the GMT offset of its + * standard time and the amount of daylight saving offset adjustment. + * @param name The time zone name. + * @param rawOffset The UTC offset of its standard time in milliseconds. + * @param dstSavings The amount of daylight saving offset adjustment in milliseconds. + * If this ia a rule for standard time, the value of this argument is 0. + * @stable ICU 3.8 + */ + InitialTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings); + + /** + * Copy constructor. + * @param source The InitialTimeZoneRule object to be copied. + * @stable ICU 3.8 + */ + InitialTimeZoneRule(const InitialTimeZoneRule& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~InitialTimeZoneRule(); + + /** + * Clone this InitialTimeZoneRule object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + virtual InitialTimeZoneRule* clone() const override; + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + InitialTimeZoneRule& operator=(const InitialTimeZoneRule& right); + + /** + * Return true if the given TimeZoneRule objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically equal. + * @stable ICU 3.8 + */ + virtual bool operator==(const TimeZoneRule& that) const override; + + /** + * Return true if the given TimeZoneRule objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically unequal. + * @stable ICU 3.8 + */ + virtual bool operator!=(const TimeZoneRule& that) const override; + + /** + * Returns if this rule represents the same rule and offsets as another. + * When two TimeZoneRule objects differ only its names, this method + * returns true. + * @param that The TimeZoneRule object to be compared with. + * @return true if the other TimeZoneRule is equivalent to this one. + * @stable ICU 3.8 + */ + virtual UBool isEquivalentTo(const TimeZoneRule& that) const override; + + /** + * Gets the very first time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the very first time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the final time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the final time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the first time when this rule takes effect after the specified time. + * @param base The first start time after this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The first time when this rule takes effect after + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + + /** + * Gets the most recent time when this rule takes effect before the specified time. + * @param base The most recent time before this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The most recent time when this rule takes effect before + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *

+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + +/** + * AnnualTimeZoneRule is a class used for representing a time zone + * rule which takes effect annually. The calendar system used for the rule is + * is based on Gregorian calendar + * + * @stable ICU 3.8 + */ +class U_I18N_API AnnualTimeZoneRule : public TimeZoneRule { +public: + /** + * The constant representing the maximum year used for designating + * a rule is permanent. + */ + static const int32_t MAX_YEAR; + + /** + * Constructs a AnnualTimeZoneRule with the name, the GMT offset of its + * standard time, the amount of daylight saving offset adjustment, the annual start + * time rule and the start/until years. The input DateTimeRule is copied by this + * constructor, so the caller remains responsible for deleting the object. + * @param name The time zone name. + * @param rawOffset The GMT offset of its standard time in milliseconds. + * @param dstSavings The amount of daylight saving offset adjustment in + * milliseconds. If this ia a rule for standard time, + * the value of this argument is 0. + * @param dateTimeRule The start date/time rule repeated annually. + * @param startYear The first year when this rule takes effect. + * @param endYear The last year when this rule takes effect. If this + * rule is effective forever in future, specify MAX_YEAR. + * @stable ICU 3.8 + */ + AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, + const DateTimeRule& dateTimeRule, int32_t startYear, int32_t endYear); + + /** + * Constructs a AnnualTimeZoneRule with the name, the GMT offset of its + * standard time, the amount of daylight saving offset adjustment, the annual start + * time rule and the start/until years. The input DateTimeRule object is adopted + * by this object, therefore, the caller must not delete the object. + * @param name The time zone name. + * @param rawOffset The GMT offset of its standard time in milliseconds. + * @param dstSavings The amount of daylight saving offset adjustment in + * milliseconds. If this ia a rule for standard time, + * the value of this argument is 0. + * @param dateTimeRule The start date/time rule repeated annually. + * @param startYear The first year when this rule takes effect. + * @param endYear The last year when this rule takes effect. If this + * rule is effective forever in future, specify MAX_YEAR. + * @stable ICU 3.8 + */ + AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, + DateTimeRule* dateTimeRule, int32_t startYear, int32_t endYear); + + /** + * Copy constructor. + * @param source The AnnualTimeZoneRule object to be copied. + * @stable ICU 3.8 + */ + AnnualTimeZoneRule(const AnnualTimeZoneRule& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~AnnualTimeZoneRule(); + + /** + * Clone this AnnualTimeZoneRule object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + virtual AnnualTimeZoneRule* clone() const override; + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + AnnualTimeZoneRule& operator=(const AnnualTimeZoneRule& right); + + /** + * Return true if the given TimeZoneRule objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically equal. + * @stable ICU 3.8 + */ + virtual bool operator==(const TimeZoneRule& that) const override; + + /** + * Return true if the given TimeZoneRule objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically unequal. + * @stable ICU 3.8 + */ + virtual bool operator!=(const TimeZoneRule& that) const override; + + /** + * Gets the start date/time rule used by this rule. + * @return The AnnualDateTimeRule which represents the start date/time + * rule used by this time zone rule. + * @stable ICU 3.8 + */ + const DateTimeRule* getRule(void) const; + + /** + * Gets the first year when this rule takes effect. + * @return The start year of this rule. The year is in Gregorian calendar + * with 0 == 1 BCE, -1 == 2 BCE, etc. + * @stable ICU 3.8 + */ + int32_t getStartYear(void) const; + + /** + * Gets the end year when this rule takes effect. + * @return The end year of this rule (inclusive). The year is in Gregorian calendar + * with 0 == 1 BCE, -1 == 2 BCE, etc. + * @stable ICU 3.8 + */ + int32_t getEndYear(void) const; + + /** + * Gets the time when this rule takes effect in the given year. + * @param year The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the start time in the year. + * @return true if this rule takes effect in the year and the result is set to + * "result". + * @stable ICU 3.8 + */ + UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; + + /** + * Returns if this rule represents the same rule and offsets as another. + * When two TimeZoneRule objects differ only its names, this method + * returns true. + * @param that The TimeZoneRule object to be compared with. + * @return true if the other TimeZoneRule is equivalent to this one. + * @stable ICU 3.8 + */ + virtual UBool isEquivalentTo(const TimeZoneRule& that) const override; + + /** + * Gets the very first time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the very first time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the final time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the final time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the first time when this rule takes effect after the specified time. + * @param base The first start time after this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The first time when this rule takes effect after + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + + /** + * Gets the most recent time when this rule takes effect before the specified time. + * @param base The most recent time before this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The most recent time when this rule takes effect before + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + + +private: + DateTimeRule* fDateTimeRule; + int32_t fStartYear; + int32_t fEndYear; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + +/** + * TimeArrayTimeZoneRule represents a time zone rule whose start times are + * defined by an array of milliseconds since the standard base time. + * + * @stable ICU 3.8 + */ +class U_I18N_API TimeArrayTimeZoneRule : public TimeZoneRule { +public: + /** + * Constructs a TimeArrayTimeZoneRule with the name, the GMT offset of its + * standard time, the amount of daylight saving offset adjustment and + * the array of times when this rule takes effect. + * @param name The time zone name. + * @param rawOffset The UTC offset of its standard time in milliseconds. + * @param dstSavings The amount of daylight saving offset adjustment in + * milliseconds. If this ia a rule for standard time, + * the value of this argument is 0. + * @param startTimes The array start times in milliseconds since the base time + * (January 1, 1970, 00:00:00). + * @param numStartTimes The number of elements in the parameter "startTimes" + * @param timeRuleType The time type of the start times, which is one of + * DataTimeRule::WALL_TIME, STANDARD_TIME + * and UTC_TIME. + * @stable ICU 3.8 + */ + TimeArrayTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, + const UDate* startTimes, int32_t numStartTimes, DateTimeRule::TimeRuleType timeRuleType); + + /** + * Copy constructor. + * @param source The TimeArrayTimeZoneRule object to be copied. + * @stable ICU 3.8 + */ + TimeArrayTimeZoneRule(const TimeArrayTimeZoneRule& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + virtual ~TimeArrayTimeZoneRule(); + + /** + * Clone this TimeArrayTimeZoneRule object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + virtual TimeArrayTimeZoneRule* clone() const override; + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + TimeArrayTimeZoneRule& operator=(const TimeArrayTimeZoneRule& right); + + /** + * Return true if the given TimeZoneRule objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically equal. + * @stable ICU 3.8 + */ + virtual bool operator==(const TimeZoneRule& that) const override; + + /** + * Return true if the given TimeZoneRule objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneRule objects are semantically unequal. + * @stable ICU 3.8 + */ + virtual bool operator!=(const TimeZoneRule& that) const override; + + /** + * Gets the time type of the start times used by this rule. The return value + * is either DateTimeRule::WALL_TIME or STANDARD_TIME + * or UTC_TIME. + * + * @return The time type used of the start times used by this rule. + * @stable ICU 3.8 + */ + DateTimeRule::TimeRuleType getTimeType(void) const; + + /** + * Gets a start time at the index stored in this rule. + * @param index The index of start times + * @param result Receives the start time at the index + * @return true if the index is within the valid range and + * and the result is set. When false, the output + * parameger "result" is unchanged. + * @stable ICU 3.8 + */ + UBool getStartTimeAt(int32_t index, UDate& result) const; + + /** + * Returns the number of start times stored in this rule + * @return The number of start times. + * @stable ICU 3.8 + */ + int32_t countStartTimes(void) const; + + /** + * Returns if this rule represents the same rule and offsets as another. + * When two TimeZoneRule objects differ only its names, this method + * returns true. + * @param that The TimeZoneRule object to be compared with. + * @return true if the other TimeZoneRule is equivalent to this one. + * @stable ICU 3.8 + */ + virtual UBool isEquivalentTo(const TimeZoneRule& that) const override; + + /** + * Gets the very first time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the very first time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the final time when this rule takes effect. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param result Receives the final time when this rule takes effect. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override; + + /** + * Gets the first time when this rule takes effect after the specified time. + * @param base The first start time after this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The first time when this rule takes effect after + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + + /** + * Gets the most recent time when this rule takes effect before the specified time. + * @param base The most recent time before this base time will be returned. + * @param prevRawOffset The standard time offset from UTC before this rule + * takes effect in milliseconds. + * @param prevDSTSavings The amount of daylight saving offset from the + * standard time. + * @param inclusive Whether the base time is inclusive or not. + * @param result Receives The most recent time when this rule takes effect before + * the specified base time. + * @return true if the start time is available. When false is returned, output parameter + * "result" is unchanged. + * @stable ICU 3.8 + */ + virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, + UBool inclusive, UDate& result) const override; + + +private: + enum { TIMEARRAY_STACK_BUFFER_SIZE = 32 }; + UBool initStartTimes(const UDate source[], int32_t size, UErrorCode& ec); + UDate getUTC(UDate time, int32_t raw, int32_t dst) const; + + DateTimeRule::TimeRuleType fTimeRuleType; + int32_t fNumStartTimes; + UDate* fStartTimes; + UDate fLocalStartTimes[TIMEARRAY_STACK_BUFFER_SIZE]; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // TZRULE_H + +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tztrans.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tztrans.h new file mode 100644 index 0000000000000000000000000000000000000000..5adbeb35e43a6652f4c84aa4e39e4167a0f1abec --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/tztrans.h @@ -0,0 +1,201 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2007-2008, International Business Machines Corporation and * +* others. All Rights Reserved. * +******************************************************************************* +*/ +#ifndef TZTRANS_H +#define TZTRANS_H + +/** + * \file + * \brief C++ API: Time zone transition + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uobject.h" + +U_NAMESPACE_BEGIN + +// Forward declaration +class TimeZoneRule; + +/** + * TimeZoneTransition is a class representing a time zone transition. + * An instance has a time of transition and rules for both before and after the transition. + * @stable ICU 3.8 + */ +class U_I18N_API TimeZoneTransition : public UObject { +public: + /** + * Constructs a TimeZoneTransition with the time and the rules before/after + * the transition. + * + * @param time The time of transition in milliseconds since the base time. + * @param from The time zone rule used before the transition. + * @param to The time zone rule used after the transition. + * @stable ICU 3.8 + */ + TimeZoneTransition(UDate time, const TimeZoneRule& from, const TimeZoneRule& to); + + /** + * Constructs an empty TimeZoneTransition + * @stable ICU 3.8 + */ + TimeZoneTransition(); + + /** + * Copy constructor. + * @param source The TimeZoneTransition object to be copied. + * @stable ICU 3.8 + */ + TimeZoneTransition(const TimeZoneTransition& source); + + /** + * Destructor. + * @stable ICU 3.8 + */ + ~TimeZoneTransition(); + + /** + * Clone this TimeZoneTransition object polymorphically. The caller owns the result and + * should delete it when done. + * @return A copy of the object. + * @stable ICU 3.8 + */ + TimeZoneTransition* clone() const; + + /** + * Assignment operator. + * @param right The object to be copied. + * @stable ICU 3.8 + */ + TimeZoneTransition& operator=(const TimeZoneTransition& right); + + /** + * Return true if the given TimeZoneTransition objects are semantically equal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneTransition objects are semantically equal. + * @stable ICU 3.8 + */ + bool operator==(const TimeZoneTransition& that) const; + + /** + * Return true if the given TimeZoneTransition objects are semantically unequal. Objects + * of different subclasses are considered unequal. + * @param that The object to be compared with. + * @return true if the given TimeZoneTransition objects are semantically unequal. + * @stable ICU 3.8 + */ + bool operator!=(const TimeZoneTransition& that) const; + + /** + * Returns the time of transition in milliseconds. + * @return The time of the transition in milliseconds since the 1970 Jan 1 epoch time. + * @stable ICU 3.8 + */ + UDate getTime(void) const; + + /** + * Sets the time of transition in milliseconds. + * @param time The time of the transition in milliseconds since the 1970 Jan 1 epoch time. + * @stable ICU 3.8 + */ + void setTime(UDate time); + + /** + * Returns the rule used before the transition. + * @return The time zone rule used after the transition. + * @stable ICU 3.8 + */ + const TimeZoneRule* getFrom(void) const; + + /** + * Sets the rule used before the transition. The caller remains + * responsible for deleting the TimeZoneRule object. + * @param from The time zone rule used before the transition. + * @stable ICU 3.8 + */ + void setFrom(const TimeZoneRule& from); + + /** + * Adopts the rule used before the transition. The caller must + * not delete the TimeZoneRule object passed in. + * @param from The time zone rule used before the transition. + * @stable ICU 3.8 + */ + void adoptFrom(TimeZoneRule* from); + + /** + * Sets the rule used after the transition. The caller remains + * responsible for deleting the TimeZoneRule object. + * @param to The time zone rule used after the transition. + * @stable ICU 3.8 + */ + void setTo(const TimeZoneRule& to); + + /** + * Adopts the rule used after the transition. The caller must + * not delete the TimeZoneRule object passed in. + * @param to The time zone rule used after the transition. + * @stable ICU 3.8 + */ + void adoptTo(TimeZoneRule* to); + + /** + * Returns the rule used after the transition. + * @return The time zone rule used after the transition. + * @stable ICU 3.8 + */ + const TimeZoneRule* getTo(void) const; + +private: + UDate fTime; + TimeZoneRule* fFrom; + TimeZoneRule* fTo; + +public: + /** + * Return the class ID for this class. This is useful only for comparing to + * a return value from getDynamicClassID(). For example: + *
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 3.8 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This + * method is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and clone() + * methods call this method. + * + * @return The class ID for this object. All objects of a + * given class have the same class ID. Objects of + * other classes have different class IDs. + * @stable ICU 3.8 + */ + virtual UClassID getDynamicClassID(void) const override; +}; + +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // TZTRANS_H + +//eof diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubidi.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubidi.h new file mode 100644 index 0000000000000000000000000000000000000000..536f4172bc202c30dd358fca58a3f84aba585f66 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubidi.h @@ -0,0 +1,2211 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1999-2013, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* file name: ubidi.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 1999jul27 +* created by: Markus W. Scherer, updated by Matitiahu Allouche +*/ + +#ifndef UBIDI_H +#define UBIDI_H + +#include "unicode/utypes.h" +#include "unicode/uchar.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + *\file + * \brief C API: Bidi algorithm + * + *

Bidi algorithm for ICU

+ * + * This is an implementation of the Unicode Bidirectional Algorithm. + * The algorithm is defined in the + * Unicode Standard Annex #9.

+ * + * Note: Libraries that perform a bidirectional algorithm and + * reorder strings accordingly are sometimes called "Storage Layout Engines". + * ICU's Bidi and shaping (u_shapeArabic()) APIs can be used at the core of such + * "Storage Layout Engines". + * + *

General remarks about the API:

+ * + * In functions with an error code parameter, + * the pErrorCode pointer must be valid + * and the value that it points to must not indicate a failure before + * the function call. Otherwise, the function returns immediately. + * After the function call, the value indicates success or failure.

+ * + * The "limit" of a sequence of characters is the position just after their + * last character, i.e., one more than that position.

+ * + * Some of the API functions provide access to "runs". + * Such a "run" is defined as a sequence of characters + * that are at the same embedding level + * after performing the Bidi algorithm.

+ * + * @author Markus W. Scherer + * @version 1.0 + * + * + *

Sample code for the ICU Bidi API

+ * + *
Rendering a paragraph with the ICU Bidi API
+ * + * This is (hypothetical) sample code that illustrates + * how the ICU Bidi API could be used to render a paragraph of text. + * Rendering code depends highly on the graphics system, + * therefore this sample code must make a lot of assumptions, + * which may or may not match any existing graphics system's properties. + * + *

The basic assumptions are:

+ *
    + *
  • Rendering is done from left to right on a horizontal line.
  • + *
  • A run of single-style, unidirectional text can be rendered at once.
  • + *
  • Such a run of text is passed to the graphics system with + * characters (code units) in logical order.
  • + *
  • The line-breaking algorithm is very complicated + * and Locale-dependent - + * and therefore its implementation omitted from this sample code.
  • + *
+ * + *
+ * \code
+ *#include 
+ *
+ *typedef enum {
+ *     styleNormal=0, styleSelected=1,
+ *     styleBold=2, styleItalics=4,
+ *     styleSuper=8, styleSub=16
+ *} Style;
+ *
+ *typedef struct { int32_t limit; Style style; } StyleRun;
+ *
+ *int getTextWidth(const UChar *text, int32_t start, int32_t limit,
+ *                  const StyleRun *styleRuns, int styleRunCount);
+ *
+ * // set *pLimit and *pStyleRunLimit for a line
+ * // from text[start] and from styleRuns[styleRunStart]
+ * // using ubidi_getLogicalRun(para, ...)
+ *void getLineBreak(const UChar *text, int32_t start, int32_t *pLimit,
+ *                  UBiDi *para,
+ *                  const StyleRun *styleRuns, int styleRunStart, int *pStyleRunLimit,
+ *                  int *pLineWidth);
+ *
+ * // render runs on a line sequentially, always from left to right
+ *
+ * // prepare rendering a new line
+ * void startLine(UBiDiDirection textDirection, int lineWidth);
+ *
+ * // render a run of text and advance to the right by the run width
+ * // the text[start..limit-1] is always in logical order
+ * void renderRun(const UChar *text, int32_t start, int32_t limit,
+ *               UBiDiDirection textDirection, Style style);
+ *
+ * // We could compute a cross-product
+ * // from the style runs with the directional runs
+ * // and then reorder it.
+ * // Instead, here we iterate over each run type
+ * // and render the intersections -
+ * // with shortcuts in simple (and common) cases.
+ * // renderParagraph() is the main function.
+ *
+ * // render a directional run with
+ * // (possibly) multiple style runs intersecting with it
+ * void renderDirectionalRun(const UChar *text,
+ *                           int32_t start, int32_t limit,
+ *                           UBiDiDirection direction,
+ *                           const StyleRun *styleRuns, int styleRunCount) {
+ *     int i;
+ *
+ *     // iterate over style runs
+ *     if(direction==UBIDI_LTR) {
+ *         int styleLimit;
+ *
+ *         for(i=0; ilimit) { styleLimit=limit; }
+ *                 renderRun(text, start, styleLimit,
+ *                           direction, styleRuns[i].style);
+ *                 if(styleLimit==limit) { break; }
+ *                 start=styleLimit;
+ *             }
+ *         }
+ *     } else {
+ *         int styleStart;
+ *
+ *         for(i=styleRunCount-1; i>=0; --i) {
+ *             if(i>0) {
+ *                 styleStart=styleRuns[i-1].limit;
+ *             } else {
+ *                 styleStart=0;
+ *             }
+ *             if(limit>=styleStart) {
+ *                 if(styleStart=length
+ *
+ *         width=getTextWidth(text, 0, length, styleRuns, styleRunCount);
+ *         if(width<=lineWidth) {
+ *             // everything fits onto one line
+ *
+ *            // prepare rendering a new line from either left or right
+ *             startLine(paraLevel, width);
+ *
+ *             renderLine(para, text, 0, length,
+ *                        styleRuns, styleRunCount, pErrorCode);
+ *         } else {
+ *             UBiDi *line;
+ *
+ *             // we need to render several lines
+ *             line=ubidi_openSized(length, 0, pErrorCode);
+ *             if(line!=NULL) {
+ *                 int32_t start=0, limit;
+ *                 int styleRunStart=0, styleRunLimit;
+ *
+ *                 for(;;) {
+ *                     limit=length;
+ *                     styleRunLimit=styleRunCount;
+ *                     getLineBreak(text, start, &limit, para,
+ *                                  styleRuns, styleRunStart, &styleRunLimit,
+ *                                 &width);
+ *                     ubidi_setLine(para, start, limit, line, pErrorCode);
+ *                     if(U_SUCCESS(*pErrorCode)) {
+ *                         // prepare rendering a new line
+ *                         // from either left or right
+ *                         startLine(paraLevel, width);
+ *
+ *                         renderLine(line, text, start, limit,
+ *                                    styleRuns+styleRunStart,
+ *                                    styleRunLimit-styleRunStart, pErrorCode);
+ *                     }
+ *                     if(limit==length) { break; }
+ *                     start=limit;
+ *                     styleRunStart=styleRunLimit-1;
+ *                     if(start>=styleRuns[styleRunStart].limit) {
+ *                         ++styleRunStart;
+ *                     }
+ *                 }
+ *
+ *                 ubidi_close(line);
+ *             }
+ *        }
+ *    }
+ *
+ *     ubidi_close(para);
+ *}
+ *\endcode
+ * 
+ */ + +/*DOCXX_TAG*/ +/*@{*/ + +/** + * UBiDiLevel is the type of the level values in this + * Bidi implementation. + * It holds an embedding level and indicates the visual direction + * by its bit 0 (even/odd value).

+ * + * It can also hold non-level values for the + * paraLevel and embeddingLevels + * arguments of ubidi_setPara(); there: + *

    + *
  • bit 7 of an embeddingLevels[] + * value indicates whether the using application is + * specifying the level of a character to override whatever the + * Bidi implementation would resolve it to.
  • + *
  • paraLevel can be set to the + * pseudo-level values UBIDI_DEFAULT_LTR + * and UBIDI_DEFAULT_RTL.
  • + *
+ * + * @see ubidi_setPara + * + *

The related constants are not real, valid level values. + * UBIDI_DEFAULT_XXX can be used to specify + * a default for the paragraph level for + * when the ubidi_setPara() function + * shall determine it but there is no + * strongly typed character in the input.

+ * + * Note that the value for UBIDI_DEFAULT_LTR is even + * and the one for UBIDI_DEFAULT_RTL is odd, + * just like with normal LTR and RTL level values - + * these special values are designed that way. Also, the implementation + * assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd. + * + * Note: The numeric values of the related constants will not change: + * They are tied to the use of 7-bit byte values (plus the override bit) + * and of the UBiDiLevel=uint8_t data type in this API. + * + * @see UBIDI_DEFAULT_LTR + * @see UBIDI_DEFAULT_RTL + * @see UBIDI_LEVEL_OVERRIDE + * @see UBIDI_MAX_EXPLICIT_LEVEL + * @stable ICU 2.0 + */ +typedef uint8_t UBiDiLevel; + +/** Paragraph level setting.

+ * + * Constant indicating that the base direction depends on the first strong + * directional character in the text according to the Unicode Bidirectional + * Algorithm. If no strong directional character is present, + * then set the paragraph level to 0 (left-to-right).

+ * + * If this value is used in conjunction with reordering modes + * UBIDI_REORDER_INVERSE_LIKE_DIRECT or + * UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the text to reorder + * is assumed to be visual LTR, and the text after reordering is required + * to be the corresponding logical string with appropriate contextual + * direction. The direction of the result string will be RTL if either + * the righmost or leftmost strong character of the source text is RTL + * or Arabic Letter, the direction will be LTR otherwise.

+ * + * If reordering option UBIDI_OPTION_INSERT_MARKS is set, an RLM may + * be added at the beginning of the result string to ensure round trip + * (that the result string, when reordered back to visual, will produce + * the original source text). + * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT + * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL + * @stable ICU 2.0 + */ +#define UBIDI_DEFAULT_LTR 0xfe + +/** Paragraph level setting.

+ * + * Constant indicating that the base direction depends on the first strong + * directional character in the text according to the Unicode Bidirectional + * Algorithm. If no strong directional character is present, + * then set the paragraph level to 1 (right-to-left).

+ * + * If this value is used in conjunction with reordering modes + * UBIDI_REORDER_INVERSE_LIKE_DIRECT or + * UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the text to reorder + * is assumed to be visual LTR, and the text after reordering is required + * to be the corresponding logical string with appropriate contextual + * direction. The direction of the result string will be RTL if either + * the righmost or leftmost strong character of the source text is RTL + * or Arabic Letter, or if the text contains no strong character; + * the direction will be LTR otherwise.

+ * + * If reordering option UBIDI_OPTION_INSERT_MARKS is set, an RLM may + * be added at the beginning of the result string to ensure round trip + * (that the result string, when reordered back to visual, will produce + * the original source text). + * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT + * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL + * @stable ICU 2.0 + */ +#define UBIDI_DEFAULT_RTL 0xff + +/** + * Maximum explicit embedding level. + * Same as the max_depth value in the + * Unicode Bidirectional Algorithm. + * (The maximum resolved level can be up to UBIDI_MAX_EXPLICIT_LEVEL+1). + * @stable ICU 2.0 + */ +#define UBIDI_MAX_EXPLICIT_LEVEL 125 + +/** Bit flag for level input. + * Overrides directional properties. + * @stable ICU 2.0 + */ +#define UBIDI_LEVEL_OVERRIDE 0x80 + +/** + * Special value which can be returned by the mapping functions when a logical + * index has no corresponding visual index or vice-versa. This may happen + * for the logical-to-visual mapping of a Bidi control when option + * #UBIDI_OPTION_REMOVE_CONTROLS is specified. This can also happen + * for the visual-to-logical mapping of a Bidi mark (LRM or RLM) inserted + * by option #UBIDI_OPTION_INSERT_MARKS. + * @see ubidi_getVisualIndex + * @see ubidi_getVisualMap + * @see ubidi_getLogicalIndex + * @see ubidi_getLogicalMap + * @stable ICU 3.6 + */ +#define UBIDI_MAP_NOWHERE (-1) + +/** + * UBiDiDirection values indicate the text direction. + * @stable ICU 2.0 + */ +enum UBiDiDirection { + /** Left-to-right text. This is a 0 value. + *

    + *
  • As return value for ubidi_getDirection(), it means + * that the source string contains no right-to-left characters, or + * that the source string is empty and the paragraph level is even. + *
  • As return value for ubidi_getBaseDirection(), it + * means that the first strong character of the source string has + * a left-to-right direction. + *
+ * @stable ICU 2.0 + */ + UBIDI_LTR, + /** Right-to-left text. This is a 1 value. + *
    + *
  • As return value for ubidi_getDirection(), it means + * that the source string contains no left-to-right characters, or + * that the source string is empty and the paragraph level is odd. + *
  • As return value for ubidi_getBaseDirection(), it + * means that the first strong character of the source string has + * a right-to-left direction. + *
+ * @stable ICU 2.0 + */ + UBIDI_RTL, + /** Mixed-directional text. + *

As return value for ubidi_getDirection(), it means + * that the source string contains both left-to-right and + * right-to-left characters. + * @stable ICU 2.0 + */ + UBIDI_MIXED, + /** No strongly directional text. + *

As return value for ubidi_getBaseDirection(), it means + * that the source string is missing or empty, or contains neither left-to-right + * nor right-to-left characters. + * @stable ICU 4.6 + */ + UBIDI_NEUTRAL +}; + +/** @stable ICU 2.0 */ +typedef enum UBiDiDirection UBiDiDirection; + +/** + * Forward declaration of the UBiDi structure for the declaration of + * the API functions. Its fields are implementation-specific.

+ * This structure holds information about a paragraph (or multiple paragraphs) + * of text with Bidi-algorithm-related details, or about one line of + * such a paragraph.

+ * Reordering can be done on a line, or on one or more paragraphs which are + * then interpreted each as one single line. + * @stable ICU 2.0 + */ +struct UBiDi; + +/** @stable ICU 2.0 */ +typedef struct UBiDi UBiDi; + +/** + * Allocate a UBiDi structure. + * Such an object is initially empty. It is assigned + * the Bidi properties of a piece of text containing one or more paragraphs + * by ubidi_setPara() + * or the Bidi properties of a line within a paragraph by + * ubidi_setLine().

+ * This object can be reused for as long as it is not deallocated + * by calling ubidi_close().

+ * ubidi_setPara() and ubidi_setLine() will allocate + * additional memory for internal structures as necessary. + * + * @return An empty UBiDi object. + * @stable ICU 2.0 + */ +U_CAPI UBiDi * U_EXPORT2 +ubidi_open(void); + +/** + * Allocate a UBiDi structure with preallocated memory + * for internal structures. + * This function provides a UBiDi object like ubidi_open() + * with no arguments, but it also preallocates memory for internal structures + * according to the sizings supplied by the caller.

+ * Subsequent functions will not allocate any more memory, and are thus + * guaranteed not to fail because of lack of memory.

+ * The preallocation can be limited to some of the internal memory + * by setting some values to 0 here. That means that if, e.g., + * maxRunCount cannot be reasonably predetermined and should not + * be set to maxLength (the only failproof value) to avoid + * wasting memory, then maxRunCount could be set to 0 here + * and the internal structures that are associated with it will be allocated + * on demand, just like with ubidi_open(). + * + * @param maxLength is the maximum text or line length that internal memory + * will be preallocated for. An attempt to associate this object with a + * longer text will fail, unless this value is 0, which leaves the allocation + * up to the implementation. + * + * @param maxRunCount is the maximum anticipated number of same-level runs + * that internal memory will be preallocated for. An attempt to access + * visual runs on an object that was not preallocated for as many runs + * as the text was actually resolved to will fail, + * unless this value is 0, which leaves the allocation up to the implementation.

+ * The number of runs depends on the actual text and maybe anywhere between + * 1 and maxLength. It is typically small. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return An empty UBiDi object with preallocated memory. + * @stable ICU 2.0 + */ +U_CAPI UBiDi * U_EXPORT2 +ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode); + +/** + * ubidi_close() must be called to free the memory + * associated with a UBiDi object.

+ * + * Important: + * A parent UBiDi object must not be destroyed or reused if + * it still has children. + * If a UBiDi object has become the child + * of another one (its parent) by calling + * ubidi_setLine(), then the child object must + * be destroyed (closed) or reused (by calling + * ubidi_setPara() or ubidi_setLine()) + * before the parent object. + * + * @param pBiDi is a UBiDi object. + * + * @see ubidi_setPara + * @see ubidi_setLine + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_close(UBiDi *pBiDi); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUBiDiPointer + * "Smart pointer" class, closes a UBiDi via ubidi_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUBiDiPointer, UBiDi, ubidi_close); + +U_NAMESPACE_END + +#endif + +/** + * Modify the operation of the Bidi algorithm such that it + * approximates an "inverse Bidi" algorithm. This function + * must be called before ubidi_setPara(). + * + *

The normal operation of the Bidi algorithm as described + * in the Unicode Technical Report is to take text stored in logical + * (keyboard, typing) order and to determine the reordering of it for visual + * rendering. + * Some legacy systems store text in visual order, and for operations + * with standard, Unicode-based algorithms, the text needs to be transformed + * to logical order. This is effectively the inverse algorithm of the + * described Bidi algorithm. Note that there is no standard algorithm for + * this "inverse Bidi" and that the current implementation provides only an + * approximation of "inverse Bidi".

+ * + *

With isInverse set to true, + * this function changes the behavior of some of the subsequent functions + * in a way that they can be used for the inverse Bidi algorithm. + * Specifically, runs of text with numeric characters will be treated in a + * special way and may need to be surrounded with LRM characters when they are + * written in reordered sequence.

+ * + *

Output runs should be retrieved using ubidi_getVisualRun(). + * Since the actual input for "inverse Bidi" is visually ordered text and + * ubidi_getVisualRun() gets the reordered runs, these are actually + * the runs of the logically ordered output.

+ * + *

Calling this function with argument isInverse set to + * true is equivalent to calling + * ubidi_setReorderingMode with argument + * reorderingMode + * set to #UBIDI_REORDER_INVERSE_NUMBERS_AS_L.
+ * Calling this function with argument isInverse set to + * false is equivalent to calling + * ubidi_setReorderingMode with argument + * reorderingMode + * set to #UBIDI_REORDER_DEFAULT. + * + * @param pBiDi is a UBiDi object. + * + * @param isInverse specifies "forward" or "inverse" Bidi operation. + * + * @see ubidi_setPara + * @see ubidi_writeReordered + * @see ubidi_setReorderingMode + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_setInverse(UBiDi *pBiDi, UBool isInverse); + +/** + * Is this Bidi object set to perform the inverse Bidi algorithm? + *

Note: calling this function after setting the reordering mode with + * ubidi_setReorderingMode will return true if the + * reordering mode was set to #UBIDI_REORDER_INVERSE_NUMBERS_AS_L, + * false for all other values.

+ * + * @param pBiDi is a UBiDi object. + * @return true if the Bidi object is set to perform the inverse Bidi algorithm + * by handling numbers as L. + * + * @see ubidi_setInverse + * @see ubidi_setReorderingMode + * @stable ICU 2.0 + */ + +U_CAPI UBool U_EXPORT2 +ubidi_isInverse(UBiDi *pBiDi); + +/** + * Specify whether block separators must be allocated level zero, + * so that successive paragraphs will progress from left to right. + * This function must be called before ubidi_setPara(). + * Paragraph separators (B) may appear in the text. Setting them to level zero + * means that all paragraph separators (including one possibly appearing + * in the last text position) are kept in the reordered text after the text + * that they follow in the source text. + * When this feature is not enabled, a paragraph separator at the last + * position of the text before reordering will go to the first position + * of the reordered text when the paragraph level is odd. + * + * @param pBiDi is a UBiDi object. + * + * @param orderParagraphsLTR specifies whether paragraph separators (B) must + * receive level 0, so that successive paragraphs progress from left to right. + * + * @see ubidi_setPara + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR); + +/** + * Is this Bidi object set to allocate level 0 to block separators so that + * successive paragraphs progress from left to right? + * + * @param pBiDi is a UBiDi object. + * @return true if the Bidi object is set to allocate level 0 to block + * separators. + * + * @see ubidi_orderParagraphsLTR + * @stable ICU 3.4 + */ +U_CAPI UBool U_EXPORT2 +ubidi_isOrderParagraphsLTR(UBiDi *pBiDi); + +/** + * UBiDiReorderingMode values indicate which variant of the Bidi + * algorithm to use. + * + * @see ubidi_setReorderingMode + * @stable ICU 3.6 + */ +typedef enum UBiDiReorderingMode { + /** Regular Logical to Visual Bidi algorithm according to Unicode. + * This is a 0 value. + * @stable ICU 3.6 */ + UBIDI_REORDER_DEFAULT = 0, + /** Logical to Visual algorithm which handles numbers in a way which + * mimics the behavior of Windows XP. + * @stable ICU 3.6 */ + UBIDI_REORDER_NUMBERS_SPECIAL, + /** Logical to Visual algorithm grouping numbers with adjacent R characters + * (reversible algorithm). + * @stable ICU 3.6 */ + UBIDI_REORDER_GROUP_NUMBERS_WITH_R, + /** Reorder runs only to transform a Logical LTR string to the Logical RTL + * string with the same display, or vice-versa.
+ * If this mode is set together with option + * #UBIDI_OPTION_INSERT_MARKS, some Bidi controls in the source + * text may be removed and other controls may be added to produce the + * minimum combination which has the required display. + * @stable ICU 3.6 */ + UBIDI_REORDER_RUNS_ONLY, + /** Visual to Logical algorithm which handles numbers like L + * (same algorithm as selected by ubidi_setInverse(true). + * @see ubidi_setInverse + * @stable ICU 3.6 */ + UBIDI_REORDER_INVERSE_NUMBERS_AS_L, + /** Visual to Logical algorithm equivalent to the regular Logical to Visual + * algorithm. + * @stable ICU 3.6 */ + UBIDI_REORDER_INVERSE_LIKE_DIRECT, + /** Inverse Bidi (Visual to Logical) algorithm for the + * UBIDI_REORDER_NUMBERS_SPECIAL Bidi algorithm. + * @stable ICU 3.6 */ + UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, +#ifndef U_HIDE_DEPRECATED_API + /** + * Number of values for reordering mode. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UBIDI_REORDER_COUNT +#endif // U_HIDE_DEPRECATED_API +} UBiDiReorderingMode; + +/** + * Modify the operation of the Bidi algorithm such that it implements some + * variant to the basic Bidi algorithm or approximates an "inverse Bidi" + * algorithm, depending on different values of the "reordering mode". + * This function must be called before ubidi_setPara(), and stays + * in effect until called again with a different argument. + * + *

The normal operation of the Bidi algorithm as described + * in the Unicode Standard Annex #9 is to take text stored in logical + * (keyboard, typing) order and to determine how to reorder it for visual + * rendering.

+ * + *

With the reordering mode set to a value other than + * #UBIDI_REORDER_DEFAULT, this function changes the behavior of + * some of the subsequent functions in a way such that they implement an + * inverse Bidi algorithm or some other algorithm variants.

+ * + *

Some legacy systems store text in visual order, and for operations + * with standard, Unicode-based algorithms, the text needs to be transformed + * into logical order. This is effectively the inverse algorithm of the + * described Bidi algorithm. Note that there is no standard algorithm for + * this "inverse Bidi", so a number of variants are implemented here.

+ * + *

In other cases, it may be desirable to emulate some variant of the + * Logical to Visual algorithm (e.g. one used in MS Windows), or perform a + * Logical to Logical transformation.

+ * + *
    + *
  • When the reordering mode is set to #UBIDI_REORDER_DEFAULT, + * the standard Bidi Logical to Visual algorithm is applied.
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_NUMBERS_SPECIAL, + * the algorithm used to perform Bidi transformations when calling + * ubidi_setPara should approximate the algorithm used in + * Microsoft Windows XP rather than strictly conform to the Unicode Bidi + * algorithm. + *
    + * The differences between the basic algorithm and the algorithm addressed + * by this option are as follows: + *
      + *
    • Within text at an even embedding level, the sequence "123AB" + * (where AB represent R or AL letters) is transformed to "123BA" by the + * Unicode algorithm and to "BA123" by the Windows algorithm.
    • + *
    • Arabic-Indic numbers (AN) are handled by the Windows algorithm just + * like regular numbers (EN).
    • + *
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_GROUP_NUMBERS_WITH_R, + * numbers located between LTR text and RTL text are associated with the RTL + * text. For instance, an LTR paragraph with content "abc 123 DEF" (where + * upper case letters represent RTL characters) will be transformed to + * "abc FED 123" (and not "abc 123 FED"), "DEF 123 abc" will be transformed + * to "123 FED abc" and "123 FED abc" will be transformed to "DEF 123 abc". + * This makes the algorithm reversible and makes it useful when round trip + * (from visual to logical and back to visual) must be achieved without + * adding LRM characters. However, this is a variation from the standard + * Unicode Bidi algorithm.
    + * The source text should not contain Bidi control characters other than LRM + * or RLM.
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_RUNS_ONLY, + * a "Logical to Logical" transformation must be performed: + *
      + *
    • If the default text level of the source text (argument paraLevel + * in ubidi_setPara) is even, the source text will be handled as + * LTR logical text and will be transformed to the RTL logical text which has + * the same LTR visual display.
    • + *
    • If the default level of the source text is odd, the source text + * will be handled as RTL logical text and will be transformed to the + * LTR logical text which has the same LTR visual display.
    • + *
    + * This mode may be needed when logical text which is basically Arabic or + * Hebrew, with possible included numbers or phrases in English, has to be + * displayed as if it had an even embedding level (this can happen if the + * displaying application treats all text as if it was basically LTR). + *
    + * This mode may also be needed in the reverse case, when logical text which is + * basically English, with possible included phrases in Arabic or Hebrew, has to + * be displayed as if it had an odd embedding level. + *
    + * Both cases could be handled by adding LRE or RLE at the head of the text, + * if the display subsystem supports these formatting controls. If it does not, + * the problem may be handled by transforming the source text in this mode + * before displaying it, so that it will be displayed properly.
    + * The source text should not contain Bidi control characters other than LRM + * or RLM.
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L, an "inverse Bidi" algorithm + * is applied. + * Runs of text with numeric characters will be treated like LTR letters and + * may need to be surrounded with LRM characters when they are written in + * reordered sequence (the option #UBIDI_INSERT_LRM_FOR_NUMERIC can + * be used with function ubidi_writeReordered to this end. This + * mode is equivalent to calling ubidi_setInverse() with + * argument isInverse set to true.
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_INVERSE_LIKE_DIRECT, the "direct" Logical to Visual + * Bidi algorithm is used as an approximation of an "inverse Bidi" algorithm. + * This mode is similar to mode #UBIDI_REORDER_INVERSE_NUMBERS_AS_L + * but is closer to the regular Bidi algorithm. + *
    + * For example, an LTR paragraph with the content "FED 123 456 CBA" (where + * upper case represents RTL characters) will be transformed to + * "ABC 456 123 DEF", as opposed to "DEF 123 456 ABC" + * with mode UBIDI_REORDER_INVERSE_NUMBERS_AS_L.
    + * When used in conjunction with option + * #UBIDI_OPTION_INSERT_MARKS, this mode generally + * adds Bidi marks to the output significantly more sparingly than mode + * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L with option + * #UBIDI_INSERT_LRM_FOR_NUMERIC in calls to + * ubidi_writeReordered.
  • + * + *
  • When the reordering mode is set to + * #UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the Logical to Visual + * Bidi algorithm used in Windows XP is used as an approximation of an "inverse Bidi" algorithm. + *
    + * For example, an LTR paragraph with the content "abc FED123" (where + * upper case represents RTL characters) will be transformed to "abc 123DEF."
  • + *
+ * + *

In all the reordering modes specifying an "inverse Bidi" algorithm + * (i.e. those with a name starting with UBIDI_REORDER_INVERSE), + * output runs should be retrieved using + * ubidi_getVisualRun(), and the output text with + * ubidi_writeReordered(). The caller should keep in mind that in + * "inverse Bidi" modes the input is actually visually ordered text and + * reordered output returned by ubidi_getVisualRun() or + * ubidi_writeReordered() are actually runs or character string + * of logically ordered output.
+ * For all the "inverse Bidi" modes, the source text should not contain + * Bidi control characters other than LRM or RLM.

+ * + *

Note that option #UBIDI_OUTPUT_REVERSE of + * ubidi_writeReordered has no useful meaning and should not be + * used in conjunction with any value of the reordering mode specifying + * "inverse Bidi" or with value UBIDI_REORDER_RUNS_ONLY. + * + * @param pBiDi is a UBiDi object. + * @param reorderingMode specifies the required variant of the Bidi algorithm. + * + * @see UBiDiReorderingMode + * @see ubidi_setInverse + * @see ubidi_setPara + * @see ubidi_writeReordered + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode); + +/** + * What is the requested reordering mode for a given Bidi object? + * + * @param pBiDi is a UBiDi object. + * @return the current reordering mode of the Bidi object + * @see ubidi_setReorderingMode + * @stable ICU 3.6 + */ +U_CAPI UBiDiReorderingMode U_EXPORT2 +ubidi_getReorderingMode(UBiDi *pBiDi); + +/** + * UBiDiReorderingOption values indicate which options are + * specified to affect the Bidi algorithm. + * + * @see ubidi_setReorderingOptions + * @stable ICU 3.6 + */ +typedef enum UBiDiReorderingOption { + /** + * option value for ubidi_setReorderingOptions: + * disable all the options which can be set with this function + * @see ubidi_setReorderingOptions + * @stable ICU 3.6 + */ + UBIDI_OPTION_DEFAULT = 0, + + /** + * option bit for ubidi_setReorderingOptions: + * insert Bidi marks (LRM or RLM) when needed to ensure correct result of + * a reordering to a Logical order + * + *

This option must be set or reset before calling + * ubidi_setPara.

+ * + *

This option is significant only with reordering modes which generate + * a result with Logical order, specifically:

+ *
    + *
  • #UBIDI_REORDER_RUNS_ONLY
  • + *
  • #UBIDI_REORDER_INVERSE_NUMBERS_AS_L
  • + *
  • #UBIDI_REORDER_INVERSE_LIKE_DIRECT
  • + *
  • #UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL
  • + *
+ * + *

If this option is set in conjunction with reordering mode + * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L or with calling + * ubidi_setInverse(true), it implies + * option #UBIDI_INSERT_LRM_FOR_NUMERIC + * in calls to function ubidi_writeReordered().

+ * + *

For other reordering modes, a minimum number of LRM or RLM characters + * will be added to the source text after reordering it so as to ensure + * round trip, i.e. when applying the inverse reordering mode on the + * resulting logical text with removal of Bidi marks + * (option #UBIDI_OPTION_REMOVE_CONTROLS set before calling + * ubidi_setPara() or option #UBIDI_REMOVE_BIDI_CONTROLS + * in ubidi_writeReordered), the result will be identical to the + * source text in the first transformation. + * + *

This option will be ignored if specified together with option + * #UBIDI_OPTION_REMOVE_CONTROLS. It inhibits option + * UBIDI_REMOVE_BIDI_CONTROLS in calls to function + * ubidi_writeReordered() and it implies option + * #UBIDI_INSERT_LRM_FOR_NUMERIC in calls to function + * ubidi_writeReordered() if the reordering mode is + * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L.

+ * + * @see ubidi_setReorderingMode + * @see ubidi_setReorderingOptions + * @stable ICU 3.6 + */ + UBIDI_OPTION_INSERT_MARKS = 1, + + /** + * option bit for ubidi_setReorderingOptions: + * remove Bidi control characters + * + *

This option must be set or reset before calling + * ubidi_setPara.

+ * + *

This option nullifies option #UBIDI_OPTION_INSERT_MARKS. + * It inhibits option #UBIDI_INSERT_LRM_FOR_NUMERIC in calls + * to function ubidi_writeReordered() and it implies option + * #UBIDI_REMOVE_BIDI_CONTROLS in calls to that function.

+ * + * @see ubidi_setReorderingMode + * @see ubidi_setReorderingOptions + * @stable ICU 3.6 + */ + UBIDI_OPTION_REMOVE_CONTROLS = 2, + + /** + * option bit for ubidi_setReorderingOptions: + * process the output as part of a stream to be continued + * + *

This option must be set or reset before calling + * ubidi_setPara.

+ * + *

This option specifies that the caller is interested in processing large + * text object in parts. + * The results of the successive calls are expected to be concatenated by the + * caller. Only the call for the last part will have this option bit off.

+ * + *

When this option bit is on, ubidi_setPara() may process + * less than the full source text in order to truncate the text at a meaningful + * boundary. The caller should call ubidi_getProcessedLength() + * immediately after calling ubidi_setPara() in order to + * determine how much of the source text has been processed. + * Source text beyond that length should be resubmitted in following calls to + * ubidi_setPara. The processed length may be less than + * the length of the source text if a character preceding the last character of + * the source text constitutes a reasonable boundary (like a block separator) + * for text to be continued.
+ * If the last character of the source text constitutes a reasonable + * boundary, the whole text will be processed at once.
+ * If nowhere in the source text there exists + * such a reasonable boundary, the processed length will be zero.
+ * The caller should check for such an occurrence and do one of the following: + *

  • submit a larger amount of text with a better chance to include + * a reasonable boundary.
  • + *
  • resubmit the same text after turning off option + * UBIDI_OPTION_STREAMING.
+ * In all cases, this option should be turned off before processing the last + * part of the text.

+ * + *

When the UBIDI_OPTION_STREAMING option is used, + * it is recommended to call ubidi_orderParagraphsLTR() with + * argument orderParagraphsLTR set to true before + * calling ubidi_setPara so that later paragraphs may be + * concatenated to previous paragraphs on the right.

+ * + * @see ubidi_setReorderingMode + * @see ubidi_setReorderingOptions + * @see ubidi_getProcessedLength + * @see ubidi_orderParagraphsLTR + * @stable ICU 3.6 + */ + UBIDI_OPTION_STREAMING = 4 +} UBiDiReorderingOption; + +/** + * Specify which of the reordering options + * should be applied during Bidi transformations. + * + * @param pBiDi is a UBiDi object. + * @param reorderingOptions is a combination of zero or more of the following + * options: + * #UBIDI_OPTION_DEFAULT, #UBIDI_OPTION_INSERT_MARKS, + * #UBIDI_OPTION_REMOVE_CONTROLS, #UBIDI_OPTION_STREAMING. + * + * @see ubidi_getReorderingOptions + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions); + +/** + * What are the reordering options applied to a given Bidi object? + * + * @param pBiDi is a UBiDi object. + * @return the current reordering options of the Bidi object + * @see ubidi_setReorderingOptions + * @stable ICU 3.6 + */ +U_CAPI uint32_t U_EXPORT2 +ubidi_getReorderingOptions(UBiDi *pBiDi); + +/** + * Set the context before a call to ubidi_setPara().

+ * + * ubidi_setPara() computes the left-right directionality for a given piece + * of text which is supplied as one of its arguments. Sometimes this piece + * of text (the "main text") should be considered in context, because text + * appearing before ("prologue") and/or after ("epilogue") the main text + * may affect the result of this computation.

+ * + * This function specifies the prologue and/or the epilogue for the next + * call to ubidi_setPara(). The characters specified as prologue and + * epilogue should not be modified by the calling program until the call + * to ubidi_setPara() has returned. If successive calls to ubidi_setPara() + * all need specification of a context, ubidi_setContext() must be called + * before each call to ubidi_setPara(). In other words, a context is not + * "remembered" after the following successful call to ubidi_setPara().

+ * + * If a call to ubidi_setPara() specifies UBIDI_DEFAULT_LTR or + * UBIDI_DEFAULT_RTL as paraLevel and is preceded by a call to + * ubidi_setContext() which specifies a prologue, the paragraph level will + * be computed taking in consideration the text in the prologue.

+ * + * When ubidi_setPara() is called without a previous call to + * ubidi_setContext, the main text is handled as if preceded and followed + * by strong directional characters at the current paragraph level. + * Calling ubidi_setContext() with specification of a prologue will change + * this behavior by handling the main text as if preceded by the last + * strong character appearing in the prologue, if any. + * Calling ubidi_setContext() with specification of an epilogue will change + * the behavior of ubidi_setPara() by handling the main text as if followed + * by the first strong character or digit appearing in the epilogue, if any.

+ * + * Note 1: if ubidi_setContext is called repeatedly without + * calling ubidi_setPara, the earlier calls have no effect, + * only the last call will be remembered for the next call to + * ubidi_setPara.

+ * + * Note 2: calling ubidi_setContext(pBiDi, NULL, 0, NULL, 0, &errorCode) + * cancels any previous setting of non-empty prologue or epilogue. + * The next call to ubidi_setPara() will process no + * prologue or epilogue.

+ * + * Note 3: users must be aware that even after setting the context + * before a call to ubidi_setPara() to perform e.g. a logical to visual + * transformation, the resulting string may not be identical to what it + * would have been if all the text, including prologue and epilogue, had + * been processed together.
+ * Example (upper case letters represent RTL characters):
+ *   prologue = "abc DE"
+ *   epilogue = none
+ *   main text = "FGH xyz"
+ *   paraLevel = UBIDI_LTR
+ *   display without prologue = "HGF xyz" + * ("HGF" is adjacent to "xyz")
+ *   display with prologue = "abc HGFED xyz" + * ("HGF" is not adjacent to "xyz")
+ * + * @param pBiDi is a paragraph UBiDi object. + * + * @param prologue is a pointer to the text which precedes the text that + * will be specified in a coming call to ubidi_setPara(). + * If there is no prologue to consider, then proLength + * must be zero and this pointer can be NULL. + * + * @param proLength is the length of the prologue; if proLength==-1 + * then the prologue must be zero-terminated. + * Otherwise proLength must be >= 0. If proLength==0, it means + * that there is no prologue to consider. + * + * @param epilogue is a pointer to the text which follows the text that + * will be specified in a coming call to ubidi_setPara(). + * If there is no epilogue to consider, then epiLength + * must be zero and this pointer can be NULL. + * + * @param epiLength is the length of the epilogue; if epiLength==-1 + * then the epilogue must be zero-terminated. + * Otherwise epiLength must be >= 0. If epiLength==0, it means + * that there is no epilogue to consider. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @see ubidi_setPara + * @stable ICU 4.8 + */ +U_CAPI void U_EXPORT2 +ubidi_setContext(UBiDi *pBiDi, + const UChar *prologue, int32_t proLength, + const UChar *epilogue, int32_t epiLength, + UErrorCode *pErrorCode); + +/** + * Perform the Unicode Bidi algorithm. It is defined in the + * Unicode Standard Annex #9, + * version 13, + * also described in The Unicode Standard, Version 4.0 .

+ * + * This function takes a piece of plain text containing one or more paragraphs, + * with or without externally specified embedding levels from styled + * text and computes the left-right-directionality of each character.

+ * + * If the entire text is all of the same directionality, then + * the function may not perform all the steps described by the algorithm, + * i.e., some levels may not be the same as if all steps were performed. + * This is not relevant for unidirectional text.
+ * For example, in pure LTR text with numbers the numbers would get + * a resolved level of 2 higher than the surrounding text according to + * the algorithm. This implementation may set all resolved levels to + * the same value in such a case.

+ * + * The text can be composed of multiple paragraphs. Occurrence of a block + * separator in the text terminates a paragraph, and whatever comes next starts + * a new paragraph. The exception to this rule is when a Carriage Return (CR) + * is followed by a Line Feed (LF). Both CR and LF are block separators, but + * in that case, the pair of characters is considered as terminating the + * preceding paragraph, and a new paragraph will be started by a character + * coming after the LF. + * + * @param pBiDi A UBiDi object allocated with ubidi_open() + * which will be set to contain the reordering information, + * especially the resolved levels for all the characters in text. + * + * @param text is a pointer to the text that the Bidi algorithm will be performed on. + * This pointer is stored in the UBiDi object and can be retrieved + * with ubidi_getText().
+ * Note: the text must be (at least) length long. + * + * @param length is the length of the text; if length==-1 then + * the text must be zero-terminated. + * + * @param paraLevel specifies the default level for the text; + * it is typically 0 (LTR) or 1 (RTL). + * If the function shall determine the paragraph level from the text, + * then paraLevel can be set to + * either #UBIDI_DEFAULT_LTR + * or #UBIDI_DEFAULT_RTL; if the text contains multiple + * paragraphs, the paragraph level shall be determined separately for + * each paragraph; if a paragraph does not include any strongly typed + * character, then the desired default is used (0 for LTR or 1 for RTL). + * Any other value between 0 and #UBIDI_MAX_EXPLICIT_LEVEL + * is also valid, with odd levels indicating RTL. + * + * @param embeddingLevels (in) may be used to preset the embedding and override levels, + * ignoring characters like LRE and PDF in the text. + * A level overrides the directional property of its corresponding + * (same index) character if the level has the + * #UBIDI_LEVEL_OVERRIDE bit set.

+ * Aside from that bit, it must be + * paraLevel<=embeddingLevels[]<=UBIDI_MAX_EXPLICIT_LEVEL, + * except that level 0 is always allowed. + * Level 0 for a paragraph separator prevents reordering of paragraphs; + * this only works reliably if #UBIDI_LEVEL_OVERRIDE + * is also set for paragraph separators. + * Level 0 for other characters is treated as a wildcard + * and is lifted up to the resolved level of the surrounding paragraph.

+ * Caution: A copy of this pointer, not of the levels, + * will be stored in the UBiDi object; + * the embeddingLevels array must not be + * deallocated before the UBiDi structure is destroyed or reused, + * and the embeddingLevels + * should not be modified to avoid unexpected results on subsequent Bidi operations. + * However, the ubidi_setPara() and + * ubidi_setLine() functions may modify some or all of the levels.

+ * After the UBiDi object is reused or destroyed, the caller + * must take care of the deallocation of the embeddingLevels array.

+ * Note: the embeddingLevels array must be + * at least length long. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pErrorCode must be a valid pointer to an error code value. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length, + UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels, + UErrorCode *pErrorCode); + +/** + * ubidi_setLine() sets a UBiDi to + * contain the reordering information, especially the resolved levels, + * for all the characters in a line of text. This line of text is + * specified by referring to a UBiDi object representing + * this information for a piece of text containing one or more paragraphs, + * and by specifying a range of indexes in this text.

+ * In the new line object, the indexes will range from 0 to limit-start-1.

+ * + * This is used after calling ubidi_setPara() + * for a piece of text, and after line-breaking on that text. + * It is not necessary if each paragraph is treated as a single line.

+ * + * After line-breaking, rules (L1) and (L2) for the treatment of + * trailing WS and for reordering are performed on + * a UBiDi object that represents a line.

+ * + * Important: pLineBiDi shares data with + * pParaBiDi. + * You must destroy or reuse pLineBiDi before pParaBiDi. + * In other words, you must destroy or reuse the UBiDi object for a line + * before the object for its parent paragraph.

+ * + * The text pointer that was stored in pParaBiDi is also copied, + * and start is added to it so that it points to the beginning of the + * line for this object. + * + * @param pParaBiDi is the parent paragraph object. It must have been set + * by a successful call to ubidi_setPara. + * + * @param start is the line's first index into the text. + * + * @param limit is just behind the line's last index into the text + * (its last index +1).
+ * It must be 0<=startcontaining paragraph limit. + * If the specified line crosses a paragraph boundary, the function + * will terminate with error code U_ILLEGAL_ARGUMENT_ERROR. + * + * @param pLineBiDi is the object that will now represent a line of the text. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @see ubidi_setPara + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_setLine(const UBiDi *pParaBiDi, + int32_t start, int32_t limit, + UBiDi *pLineBiDi, + UErrorCode *pErrorCode); + +/** + * Get the directionality of the text. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @return a value of UBIDI_LTR, UBIDI_RTL + * or UBIDI_MIXED + * that indicates if the entire text + * represented by this object is unidirectional, + * and which direction, or if it is mixed-directional. + * Note - The value UBIDI_NEUTRAL is never returned from this method. + * + * @see UBiDiDirection + * @stable ICU 2.0 + */ +U_CAPI UBiDiDirection U_EXPORT2 +ubidi_getDirection(const UBiDi *pBiDi); + +/** + * Gets the base direction of the text provided according + * to the Unicode Bidirectional Algorithm. The base direction + * is derived from the first character in the string with bidirectional + * character type L, R, or AL. If the first such character has type L, + * UBIDI_LTR is returned. If the first such character has + * type R or AL, UBIDI_RTL is returned. If the string does + * not contain any character of these types, then + * UBIDI_NEUTRAL is returned. + * + * This is a lightweight function for use when only the base direction + * is needed and no further bidi processing of the text is needed. + * + * @param text is a pointer to the text whose base + * direction is needed. + * Note: the text must be (at least) @c length long. + * + * @param length is the length of the text; + * if length==-1 then the text + * must be zero-terminated. + * + * @return UBIDI_LTR, UBIDI_RTL, + * UBIDI_NEUTRAL + * + * @see UBiDiDirection + * @stable ICU 4.6 + */ +U_CAPI UBiDiDirection U_EXPORT2 +ubidi_getBaseDirection(const UChar *text, int32_t length ); + +/** + * Get the pointer to the text. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @return The pointer to the text that the UBiDi object was created for. + * + * @see ubidi_setPara + * @see ubidi_setLine + * @stable ICU 2.0 + */ +U_CAPI const UChar * U_EXPORT2 +ubidi_getText(const UBiDi *pBiDi); + +/** + * Get the length of the text. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @return The length of the text that the UBiDi object was created for. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getLength(const UBiDi *pBiDi); + +/** + * Get the paragraph level of the text. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @return The paragraph level. If there are multiple paragraphs, their + * level may vary if the required paraLevel is UBIDI_DEFAULT_LTR or + * UBIDI_DEFAULT_RTL. In that case, the level of the first paragraph + * is returned. + * + * @see UBiDiLevel + * @see ubidi_getParagraph + * @see ubidi_getParagraphByIndex + * @stable ICU 2.0 + */ +U_CAPI UBiDiLevel U_EXPORT2 +ubidi_getParaLevel(const UBiDi *pBiDi); + +/** + * Get the number of paragraphs. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @return The number of paragraphs. + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_countParagraphs(UBiDi *pBiDi); + +/** + * Get a paragraph, given a position within the text. + * This function returns information about a paragraph.
+ * Note: if the paragraph index is known, it is more efficient to + * retrieve the paragraph information using ubidi_getParagraphByIndex().

+ * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param charIndex is the index of a character within the text, in the + * range [0..ubidi_getProcessedLength(pBiDi)-1]. + * + * @param pParaStart will receive the index of the first character of the + * paragraph in the text. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pParaLimit will receive the limit of the paragraph. + * The l-value that you point to here may be the + * same expression (variable) as the one for + * charIndex. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pParaLevel will receive the level of the paragraph. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The index of the paragraph containing the specified position. + * + * @see ubidi_getProcessedLength + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex, int32_t *pParaStart, + int32_t *pParaLimit, UBiDiLevel *pParaLevel, + UErrorCode *pErrorCode); + +/** + * Get a paragraph, given the index of this paragraph. + * + * This function returns information about a paragraph.

+ * + * @param pBiDi is the paragraph UBiDi object. + * + * @param paraIndex is the number of the paragraph, in the + * range [0..ubidi_countParagraphs(pBiDi)-1]. + * + * @param pParaStart will receive the index of the first character of the + * paragraph in the text. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pParaLimit will receive the limit of the paragraph. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pParaLevel will receive the level of the paragraph. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex, + int32_t *pParaStart, int32_t *pParaLimit, + UBiDiLevel *pParaLevel, UErrorCode *pErrorCode); + +/** + * Get the level for one character. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param charIndex the index of a character. It must be in the range + * [0..ubidi_getProcessedLength(pBiDi)]. + * + * @return The level for the character at charIndex (0 if charIndex is not + * in the valid range). + * + * @see UBiDiLevel + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI UBiDiLevel U_EXPORT2 +ubidi_getLevelAt(const UBiDi *pBiDi, int32_t charIndex); + +/** + * Get an array of levels for each character.

+ * + * Note that this function may allocate memory under some + * circumstances, unlike ubidi_getLevelAt(). + * + * @param pBiDi is the paragraph or line UBiDi object, whose + * text length must be strictly positive. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The levels array for the text, + * or NULL if an error occurs. + * + * @see UBiDiLevel + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI const UBiDiLevel * U_EXPORT2 +ubidi_getLevels(UBiDi *pBiDi, UErrorCode *pErrorCode); + +/** + * Get a logical run. + * This function returns information about a run and is used + * to retrieve runs in logical order.

+ * This is especially useful for line-breaking on a paragraph. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param logicalPosition is a logical position within the source text. + * + * @param pLogicalLimit will receive the limit of the corresponding run. + * The l-value that you point to here may be the + * same expression (variable) as the one for + * logicalPosition. + * This pointer can be NULL if this + * value is not necessary. + * + * @param pLevel will receive the level of the corresponding run. + * This pointer can be NULL if this + * value is not necessary. + * + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_getLogicalRun(const UBiDi *pBiDi, int32_t logicalPosition, + int32_t *pLogicalLimit, UBiDiLevel *pLevel); + +/** + * Get the number of runs. + * This function may invoke the actual reordering on the + * UBiDi object, after ubidi_setPara() + * may have resolved only the levels of the text. Therefore, + * ubidi_countRuns() may have to allocate memory, + * and may fail doing so. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The number of runs. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_countRuns(UBiDi *pBiDi, UErrorCode *pErrorCode); + +/** + * Get one run's logical start, length, and directionality, + * which can be 0 for LTR or 1 for RTL. + * In an RTL run, the character at the logical start is + * visually on the right of the displayed run. + * The length is the number of characters in the run.

+ * ubidi_countRuns() should be called + * before the runs are retrieved. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param runIndex is the number of the run in visual order, in the + * range [0..ubidi_countRuns(pBiDi)-1]. + * + * @param pLogicalStart is the first logical character index in the text. + * The pointer may be NULL if this index is not needed. + * + * @param pLength is the number of characters (at least one) in the run. + * The pointer may be NULL if this is not needed. + * + * @return the directionality of the run, + * UBIDI_LTR==0 or UBIDI_RTL==1, + * never UBIDI_MIXED, + * never UBIDI_NEUTRAL. + * + * @see ubidi_countRuns + * + * Example: + *

+ * \code
+ * int32_t i, count=ubidi_countRuns(pBiDi),
+ *         logicalStart, visualIndex=0, length;
+ * for(i=0; i0);
+ *     } else {
+ *         logicalStart+=length;  // logicalLimit
+ *         do { // RTL
+ *             show_char(text[--logicalStart], visualIndex++);
+ *         } while(--length>0);
+ *     }
+ * }
+ *\endcode
+ * 
+ * + * Note that in right-to-left runs, code like this places + * second surrogates before first ones (which is generally a bad idea) + * and combining characters before base characters. + *

+ * Use of ubidi_writeReordered(), optionally with the + * #UBIDI_KEEP_BASE_COMBINING option, can be considered in order + * to avoid these issues. + * @stable ICU 2.0 + */ +U_CAPI UBiDiDirection U_EXPORT2 +ubidi_getVisualRun(UBiDi *pBiDi, int32_t runIndex, + int32_t *pLogicalStart, int32_t *pLength); + +/** + * Get the visual position from a logical text position. + * If such a mapping is used many times on the same + * UBiDi object, then calling + * ubidi_getLogicalMap() is more efficient.

+ * + * The value returned may be #UBIDI_MAP_NOWHERE if there is no + * visual position because the corresponding text character is a Bidi control + * removed from output by the option #UBIDI_OPTION_REMOVE_CONTROLS. + *

+ * When the visual output is altered by using options of + * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, + * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, + * UBIDI_REMOVE_BIDI_CONTROLS, the visual position returned may not + * be correct. It is advised to use, when possible, reordering options + * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. + *

+ * Note that in right-to-left runs, this mapping places + * second surrogates before first ones (which is generally a bad idea) + * and combining characters before base characters. + * Use of ubidi_writeReordered(), optionally with the + * #UBIDI_KEEP_BASE_COMBINING option can be considered instead + * of using the mapping, in order to avoid these issues. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param logicalIndex is the index of a character in the text. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The visual position of this character. + * + * @see ubidi_getLogicalMap + * @see ubidi_getLogicalIndex + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getVisualIndex(UBiDi *pBiDi, int32_t logicalIndex, UErrorCode *pErrorCode); + +/** + * Get the logical text position from a visual position. + * If such a mapping is used many times on the same + * UBiDi object, then calling + * ubidi_getVisualMap() is more efficient.

+ * + * The value returned may be #UBIDI_MAP_NOWHERE if there is no + * logical position because the corresponding text character is a Bidi mark + * inserted in the output by option #UBIDI_OPTION_INSERT_MARKS. + *

+ * This is the inverse function to ubidi_getVisualIndex(). + *

+ * When the visual output is altered by using options of + * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, + * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, + * UBIDI_REMOVE_BIDI_CONTROLS, the logical position returned may not + * be correct. It is advised to use, when possible, reordering options + * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param visualIndex is the visual position of a character. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The index of this character in the text. + * + * @see ubidi_getVisualMap + * @see ubidi_getVisualIndex + * @see ubidi_getResultLength + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getLogicalIndex(UBiDi *pBiDi, int32_t visualIndex, UErrorCode *pErrorCode); + +/** + * Get a logical-to-visual index map (array) for the characters in the UBiDi + * (paragraph or line) object. + *

+ * Some values in the map may be #UBIDI_MAP_NOWHERE if the + * corresponding text characters are Bidi controls removed from the visual + * output by the option #UBIDI_OPTION_REMOVE_CONTROLS. + *

+ * When the visual output is altered by using options of + * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, + * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, + * UBIDI_REMOVE_BIDI_CONTROLS, the visual positions returned may not + * be correct. It is advised to use, when possible, reordering options + * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. + *

+ * Note that in right-to-left runs, this mapping places + * second surrogates before first ones (which is generally a bad idea) + * and combining characters before base characters. + * Use of ubidi_writeReordered(), optionally with the + * #UBIDI_KEEP_BASE_COMBINING option can be considered instead + * of using the mapping, in order to avoid these issues. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param indexMap is a pointer to an array of ubidi_getProcessedLength() + * indexes which will reflect the reordering of the characters. + * If option #UBIDI_OPTION_INSERT_MARKS is set, the number + * of elements allocated in indexMap must be no less than + * ubidi_getResultLength(). + * The array does not need to be initialized.

+ * The index map will result in indexMap[logicalIndex]==visualIndex. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @see ubidi_getVisualMap + * @see ubidi_getVisualIndex + * @see ubidi_getProcessedLength + * @see ubidi_getResultLength + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_getLogicalMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode); + +/** + * Get a visual-to-logical index map (array) for the characters in the UBiDi + * (paragraph or line) object. + *

+ * Some values in the map may be #UBIDI_MAP_NOWHERE if the + * corresponding text characters are Bidi marks inserted in the visual output + * by the option #UBIDI_OPTION_INSERT_MARKS. + *

+ * When the visual output is altered by using options of + * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, + * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, + * UBIDI_REMOVE_BIDI_CONTROLS, the logical positions returned may not + * be correct. It is advised to use, when possible, reordering options + * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. + * + * @param pBiDi is the paragraph or line UBiDi object. + * + * @param indexMap is a pointer to an array of ubidi_getResultLength() + * indexes which will reflect the reordering of the characters. + * If option #UBIDI_OPTION_REMOVE_CONTROLS is set, the number + * of elements allocated in indexMap must be no less than + * ubidi_getProcessedLength(). + * The array does not need to be initialized.

+ * The index map will result in indexMap[visualIndex]==logicalIndex. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @see ubidi_getLogicalMap + * @see ubidi_getLogicalIndex + * @see ubidi_getProcessedLength + * @see ubidi_getResultLength + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_getVisualMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode); + +/** + * This is a convenience function that does not use a UBiDi object. + * It is intended to be used for when an application has determined the levels + * of objects (character sequences) and just needs to have them reordered (L2). + * This is equivalent to using ubidi_getLogicalMap() on a + * UBiDi object. + * + * @param levels is an array with length levels that have been determined by + * the application. + * + * @param length is the number of levels in the array, or, semantically, + * the number of objects to be reordered. + * It must be length>0. + * + * @param indexMap is a pointer to an array of length + * indexes which will reflect the reordering of the characters. + * The array does not need to be initialized.

+ * The index map will result in indexMap[logicalIndex]==visualIndex. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_reorderLogical(const UBiDiLevel *levels, int32_t length, int32_t *indexMap); + +/** + * This is a convenience function that does not use a UBiDi object. + * It is intended to be used for when an application has determined the levels + * of objects (character sequences) and just needs to have them reordered (L2). + * This is equivalent to using ubidi_getVisualMap() on a + * UBiDi object. + * + * @param levels is an array with length levels that have been determined by + * the application. + * + * @param length is the number of levels in the array, or, semantically, + * the number of objects to be reordered. + * It must be length>0. + * + * @param indexMap is a pointer to an array of length + * indexes which will reflect the reordering of the characters. + * The array does not need to be initialized.

+ * The index map will result in indexMap[visualIndex]==logicalIndex. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_reorderVisual(const UBiDiLevel *levels, int32_t length, int32_t *indexMap); + +/** + * Invert an index map. + * The index mapping of the first map is inverted and written to + * the second one. + * + * @param srcMap is an array with length elements + * which defines the original mapping from a source array containing + * length elements to a destination array. + * Some elements of the source array may have no mapping in the + * destination array. In that case, their value will be + * the special value UBIDI_MAP_NOWHERE. + * All elements must be >=0 or equal to UBIDI_MAP_NOWHERE. + * Some elements may have a value >= length, if the + * destination array has more elements than the source array. + * There must be no duplicate indexes (two or more elements with the + * same value except UBIDI_MAP_NOWHERE). + * + * @param destMap is an array with a number of elements equal to 1 + the highest + * value in srcMap. + * destMap will be filled with the inverse mapping. + * If element with index i in srcMap has a value k different + * from UBIDI_MAP_NOWHERE, this means that element i of + * the source array maps to element k in the destination array. + * The inverse map will have value i in its k-th element. + * For all elements of the destination array which do not map to + * an element in the source array, the corresponding element in the + * inverse map will have a value equal to UBIDI_MAP_NOWHERE. + * + * @param length is the length of each array. + * @see UBIDI_MAP_NOWHERE + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubidi_invertMap(const int32_t *srcMap, int32_t *destMap, int32_t length); + +/** option flags for ubidi_writeReordered() */ + +/** + * option bit for ubidi_writeReordered(): + * keep combining characters after their base characters in RTL runs + * + * @see ubidi_writeReordered + * @stable ICU 2.0 + */ +#define UBIDI_KEEP_BASE_COMBINING 1 + +/** + * option bit for ubidi_writeReordered(): + * replace characters with the "mirrored" property in RTL runs + * by their mirror-image mappings + * + * @see ubidi_writeReordered + * @stable ICU 2.0 + */ +#define UBIDI_DO_MIRRORING 2 + +/** + * option bit for ubidi_writeReordered(): + * surround the run with LRMs if necessary; + * this is part of the approximate "inverse Bidi" algorithm + * + *

This option does not imply corresponding adjustment of the index + * mappings.

+ * + * @see ubidi_setInverse + * @see ubidi_writeReordered + * @stable ICU 2.0 + */ +#define UBIDI_INSERT_LRM_FOR_NUMERIC 4 + +/** + * option bit for ubidi_writeReordered(): + * remove Bidi control characters + * (this does not affect #UBIDI_INSERT_LRM_FOR_NUMERIC) + * + *

This option does not imply corresponding adjustment of the index + * mappings.

+ * + * @see ubidi_writeReordered + * @stable ICU 2.0 + */ +#define UBIDI_REMOVE_BIDI_CONTROLS 8 + +/** + * option bit for ubidi_writeReordered(): + * write the output in reverse order + * + *

This has the same effect as calling ubidi_writeReordered() + * first without this option, and then calling + * ubidi_writeReverse() without mirroring. + * Doing this in the same step is faster and avoids a temporary buffer. + * An example for using this option is output to a character terminal that + * is designed for RTL scripts and stores text in reverse order.

+ * + * @see ubidi_writeReordered + * @stable ICU 2.0 + */ +#define UBIDI_OUTPUT_REVERSE 16 + +/** + * Get the length of the source text processed by the last call to + * ubidi_setPara(). This length may be different from the length + * of the source text if option #UBIDI_OPTION_STREAMING + * has been set. + *
+ * Note that whenever the length of the text affects the execution or the + * result of a function, it is the processed length which must be considered, + * except for ubidi_setPara (which receives unprocessed source + * text) and ubidi_getLength (which returns the original length + * of the source text).
+ * In particular, the processed length is the one to consider in the following + * cases: + *
    + *
  • maximum value of the limit argument of + * ubidi_setLine
  • + *
  • maximum value of the charIndex argument of + * ubidi_getParagraph
  • + *
  • maximum value of the charIndex argument of + * ubidi_getLevelAt
  • + *
  • number of elements in the array returned by ubidi_getLevels
  • + *
  • maximum value of the logicalStart argument of + * ubidi_getLogicalRun
  • + *
  • maximum value of the logicalIndex argument of + * ubidi_getVisualIndex
  • + *
  • number of elements filled in the *indexMap argument of + * ubidi_getLogicalMap
  • + *
  • length of text processed by ubidi_writeReordered
  • + *
+ * + * @param pBiDi is the paragraph UBiDi object. + * + * @return The length of the part of the source text processed by + * the last call to ubidi_setPara. + * @see ubidi_setPara + * @see UBIDI_OPTION_STREAMING + * @stable ICU 3.6 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getProcessedLength(const UBiDi *pBiDi); + +/** + * Get the length of the reordered text resulting from the last call to + * ubidi_setPara(). This length may be different from the length + * of the source text if option #UBIDI_OPTION_INSERT_MARKS + * or option #UBIDI_OPTION_REMOVE_CONTROLS has been set. + *
+ * This resulting length is the one to consider in the following cases: + *
    + *
  • maximum value of the visualIndex argument of + * ubidi_getLogicalIndex
  • + *
  • number of elements of the *indexMap argument of + * ubidi_getVisualMap
  • + *
+ * Note that this length stays identical to the source text length if + * Bidi marks are inserted or removed using option bits of + * ubidi_writeReordered, or if option + * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L has been set. + * + * @param pBiDi is the paragraph UBiDi object. + * + * @return The length of the reordered text resulting from + * the last call to ubidi_setPara. + * @see ubidi_setPara + * @see UBIDI_OPTION_INSERT_MARKS + * @see UBIDI_OPTION_REMOVE_CONTROLS + * @stable ICU 3.6 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_getResultLength(const UBiDi *pBiDi); + +U_CDECL_BEGIN + +#ifndef U_HIDE_DEPRECATED_API +/** + * Value returned by UBiDiClassCallback callbacks when + * there is no need to override the standard Bidi class for a given code point. + * + * This constant is deprecated; use u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1 instead. + * + * @see UBiDiClassCallback + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ +#define U_BIDI_CLASS_DEFAULT U_CHAR_DIRECTION_COUNT +#endif // U_HIDE_DEPRECATED_API + +/** + * Callback type declaration for overriding default Bidi class values with + * custom ones. + *

Usually, the function pointer will be propagated to a UBiDi + * object by calling the ubidi_setClassCallback() function; + * then the callback will be invoked by the UBA implementation any time the + * class of a character is to be determined.

+ * + * @param context is a pointer to the callback private data. + * + * @param c is the code point to get a Bidi class for. + * + * @return The directional property / Bidi class for the given code point + * c if the default class has been overridden, or + * u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1 + * if the standard Bidi class value for c is to be used. + * @see ubidi_setClassCallback + * @see ubidi_getClassCallback + * @stable ICU 3.6 + */ +typedef UCharDirection U_CALLCONV +UBiDiClassCallback(const void *context, UChar32 c); + +U_CDECL_END + +/** + * Retrieve the Bidi class for a given code point. + *

If a #UBiDiClassCallback callback is defined and returns a + * value other than u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1, + * that value is used; otherwise the default class determination mechanism is invoked.

+ * + * @param pBiDi is the paragraph UBiDi object. + * + * @param c is the code point whose Bidi class must be retrieved. + * + * @return The Bidi class for character c based + * on the given pBiDi instance. + * @see UBiDiClassCallback + * @stable ICU 3.6 + */ +U_CAPI UCharDirection U_EXPORT2 +ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c); + +/** + * Set the callback function and callback data used by the UBA + * implementation for Bidi class determination. + *

This may be useful for assigning Bidi classes to PUA characters, or + * for special application needs. For instance, an application may want to + * handle all spaces like L or R characters (according to the base direction) + * when creating the visual ordering of logical lines which are part of a report + * organized in columns: there should not be interaction between adjacent + * cells.

+ * + * @param pBiDi is the paragraph UBiDi object. + * + * @param newFn is the new callback function pointer. + * + * @param newContext is the new callback context pointer. This can be NULL. + * + * @param oldFn fillin: Returns the old callback function pointer. This can be + * NULL. + * + * @param oldContext fillin: Returns the old callback's context. This can be + * NULL. + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @see ubidi_getClassCallback + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn, + const void *newContext, UBiDiClassCallback **oldFn, + const void **oldContext, UErrorCode *pErrorCode); + +/** + * Get the current callback function used for Bidi class determination. + * + * @param pBiDi is the paragraph UBiDi object. + * + * @param fn fillin: Returns the callback function pointer. + * + * @param context fillin: Returns the callback's private context. + * + * @see ubidi_setClassCallback + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context); + +/** + * Take a UBiDi object containing the reordering + * information for a piece of text (one or more paragraphs) set by + * ubidi_setPara() or for a line of text set by + * ubidi_setLine() and write a reordered string to the + * destination buffer. + * + * This function preserves the integrity of characters with multiple + * code units and (optionally) combining characters. + * Characters in RTL runs can be replaced by mirror-image characters + * in the destination buffer. Note that "real" mirroring has + * to be done in a rendering engine by glyph selection + * and that for many "mirrored" characters there are no + * Unicode characters as mirror-image equivalents. + * There are also options to insert or remove Bidi control + * characters; see the description of the destSize + * and options parameters and of the option bit flags. + * + * @param pBiDi A pointer to a UBiDi object that + * is set by ubidi_setPara() or + * ubidi_setLine() and contains the reordering + * information for the text that it was defined for, + * as well as a pointer to that text.

+ * The text was aliased (only the pointer was stored + * without copying the contents) and must not have been modified + * since the ubidi_setPara() call. + * + * @param dest A pointer to where the reordered text is to be copied. + * The source text and dest[destSize] + * must not overlap. + * + * @param destSize The size of the dest buffer, + * in number of UChars. + * If the UBIDI_INSERT_LRM_FOR_NUMERIC + * option is set, then the destination length could be + * as large as + * ubidi_getLength(pBiDi)+2*ubidi_countRuns(pBiDi). + * If the UBIDI_REMOVE_BIDI_CONTROLS option + * is set, then the destination length may be less than + * ubidi_getLength(pBiDi). + * If none of these options is set, then the destination length + * will be exactly ubidi_getProcessedLength(pBiDi). + * + * @param options A bit set of options for the reordering that control + * how the reordered text is written. + * The options include mirroring the characters on a code + * point basis and inserting LRM characters, which is used + * especially for transforming visually stored text + * to logically stored text (although this is still an + * imperfect implementation of an "inverse Bidi" algorithm + * because it uses the "forward Bidi" algorithm at its core). + * The available options are: + * #UBIDI_DO_MIRRORING, + * #UBIDI_INSERT_LRM_FOR_NUMERIC, + * #UBIDI_KEEP_BASE_COMBINING, + * #UBIDI_OUTPUT_REVERSE, + * #UBIDI_REMOVE_BIDI_CONTROLS + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The length of the output string. + * + * @see ubidi_getProcessedLength + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_writeReordered(UBiDi *pBiDi, + UChar *dest, int32_t destSize, + uint16_t options, + UErrorCode *pErrorCode); + +/** + * Reverse a Right-To-Left run of Unicode text. + * + * This function preserves the integrity of characters with multiple + * code units and (optionally) combining characters. + * Characters can be replaced by mirror-image characters + * in the destination buffer. Note that "real" mirroring has + * to be done in a rendering engine by glyph selection + * and that for many "mirrored" characters there are no + * Unicode characters as mirror-image equivalents. + * There are also options to insert or remove Bidi control + * characters. + * + * This function is the implementation for reversing RTL runs as part + * of ubidi_writeReordered(). For detailed descriptions + * of the parameters, see there. + * Since no Bidi controls are inserted here, the output string length + * will never exceed srcLength. + * + * @see ubidi_writeReordered + * + * @param src A pointer to the RTL run text. + * + * @param srcLength The length of the RTL run. + * + * @param dest A pointer to where the reordered text is to be copied. + * src[srcLength] and dest[destSize] + * must not overlap. + * + * @param destSize The size of the dest buffer, + * in number of UChars. + * If the UBIDI_REMOVE_BIDI_CONTROLS option + * is set, then the destination length may be less than + * srcLength. + * If this option is not set, then the destination length + * will be exactly srcLength. + * + * @param options A bit set of options for the reordering that control + * how the reordered text is written. + * See the options parameter in ubidi_writeReordered(). + * + * @param pErrorCode must be a valid pointer to an error code value. + * + * @return The length of the output string. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubidi_writeReverse(const UChar *src, int32_t srcLength, + UChar *dest, int32_t destSize, + uint16_t options, + UErrorCode *pErrorCode); + +/*#define BIDI_SAMPLE_CODE*/ +/*@}*/ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubiditransform.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubiditransform.h new file mode 100644 index 0000000000000000000000000000000000000000..24433aa8aca0fca2b69ac0eebcb6fd3956c26f61 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubiditransform.h @@ -0,0 +1,326 @@ +/* +****************************************************************************** +* +* © 2016 and later: Unicode, Inc. and others. +* License & terms of use: http://www.unicode.org/copyright.html +* +****************************************************************************** +* file name: ubiditransform.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2016jul24 +* created by: Lina Kemmel +* +*/ + +#ifndef UBIDITRANSFORM_H +#define UBIDITRANSFORM_H + +#include "unicode/utypes.h" +#include "unicode/ubidi.h" +#include "unicode/uchar.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Bidi Transformations + */ + +/** + * `UBiDiOrder` indicates the order of text. + * + * This bidi transformation engine supports all possible combinations (4 in + * total) of input and output text order: + * + * - : unless the output direction is RTL, this + * corresponds to a normal operation of the Bidi algorithm as described in the + * Unicode Technical Report and implemented by `UBiDi` when the + * reordering mode is set to `UBIDI_REORDER_DEFAULT`. Visual RTL + * mode is not supported by `UBiDi` and is accomplished through + * reversing a visual LTR string, + * + * - : unless the input direction is RTL, this + * corresponds to an "inverse bidi algorithm" in `UBiDi` with the + * reordering mode set to `UBIDI_REORDER_INVERSE_LIKE_DIRECT`. + * Visual RTL mode is not not supported by `UBiDi` and is + * accomplished through reversing a visual LTR string, + * + * - : if the input and output base directions + * mismatch, this corresponds to the `UBiDi` implementation with the + * reordering mode set to `UBIDI_REORDER_RUNS_ONLY`; and if the + * input and output base directions are identical, the transformation engine + * will only handle character mirroring and Arabic shaping operations without + * reordering, + * + * - : this reordering mode is not supported by + * the `UBiDi` engine; it implies character mirroring, Arabic + * shaping, and - if the input/output base directions mismatch - string + * reverse operations. + * @see ubidi_setInverse + * @see ubidi_setReorderingMode + * @see UBIDI_REORDER_DEFAULT + * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT + * @see UBIDI_REORDER_RUNS_ONLY + * @stable ICU 58 + */ +typedef enum { + /** 0: Constant indicating a logical order. + * This is the default for input text. + * @stable ICU 58 + */ + UBIDI_LOGICAL = 0, + /** 1: Constant indicating a visual order. + * This is a default for output text. + * @stable ICU 58 + */ + UBIDI_VISUAL +} UBiDiOrder; + +/** + * UBiDiMirroring indicates whether or not characters with the + * "mirrored" property in RTL runs should be replaced with their mirror-image + * counterparts. + * @see UBIDI_DO_MIRRORING + * @see ubidi_setReorderingOptions + * @see ubidi_writeReordered + * @see ubidi_writeReverse + * @stable ICU 58 + */ +typedef enum { + /** 0: Constant indicating that character mirroring should not be + * performed. + * This is the default. + * @stable ICU 58 + */ + UBIDI_MIRRORING_OFF = 0, + /** 1: Constant indicating that character mirroring should be performed. + * This corresponds to calling ubidi_writeReordered or + * ubidi_writeReverse with the + * UBIDI_DO_MIRRORING option bit set. + * @stable ICU 58 + */ + UBIDI_MIRRORING_ON +} UBiDiMirroring; + +/** + * Forward declaration of the UBiDiTransform structure that stores + * information used by the layout transformation engine. + * @stable ICU 58 + */ +typedef struct UBiDiTransform UBiDiTransform; + +/** + * Performs transformation of text from the bidi layout defined by the input + * ordering scheme to the bidi layout defined by the output ordering scheme, + * and applies character mirroring and Arabic shaping operations.

+ * In terms of UBiDi, such a transformation implies: + *

    + *
  • calling ubidi_setReorderingMode as needed (when the + * reordering mode is other than normal),
  • + *
  • calling ubidi_setInverse as needed (when text should be + * transformed from a visual to a logical form),
  • + *
  • resolving embedding levels of each character in the input text by + * calling ubidi_setPara,
  • + *
  • reordering the characters based on the computed embedding levels, also + * performing character mirroring as needed, and streaming the result to the + * output, by calling ubidi_writeReordered,
  • + *
  • performing Arabic digit and letter shaping on the output text by calling + * u_shapeArabic.
  • + *
+ * An "ordering scheme" encompasses the base direction and the order of text, + * and these characteristics must be defined by the caller for both input and + * output explicitly .

+ * There are 36 possible combinations of ordering schemes, + * which are partially supported by UBiDi already. Examples of the + * currently supported combinations: + *

    + *
  • : this is equivalent to calling + * ubidi_setPara with paraLevel == UBIDI_LTR,
  • + *
  • : this is equivalent to calling + * ubidi_setPara with paraLevel == UBIDI_RTL,
  • + *
  • : this is equivalent to + * calling ubidi_setPara with + * paraLevel == UBIDI_DEFAULT_LTR,
  • + *
  • : this is equivalent to + * calling ubidi_setPara with + * paraLevel == UBIDI_DEFAULT_RTL,
  • + *
  • : this is equivalent to + * calling ubidi_setInverse(UBiDi*, true) and then + * ubidi_setPara with paraLevel == UBIDI_LTR,
  • + *
  • : this is equivalent to + * calling ubidi_setInverse(UBiDi*, true) and then + * ubidi_setPara with paraLevel == UBIDI_RTL.
  • + *
+ * All combinations that involve the Visual RTL scheme are unsupported by + * UBiDi, for instance: + *
    + *
  • ,
  • + *
  • .
  • + *
+ *

Example of usage of the transformation engine:
+ *

+ * \code
+ * UChar text1[] = {'a', 'b', 'c', 0x0625, '1', 0};
+ * UChar text2[] = {'a', 'b', 'c', 0x0625, '1', 0};
+ * UErrorCode errorCode = U_ZERO_ERROR;
+ * // Run a transformation.
+ * ubiditransform_transform(pBidiTransform,
+ *          text1, -1, text2, -1,
+ *          UBIDI_LTR, UBIDI_VISUAL,
+ *          UBIDI_RTL, UBIDI_LOGICAL,
+ *          UBIDI_MIRRORING_OFF,
+ *          U_SHAPE_DIGITS_AN2EN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
+ *          &errorCode);
+ * // Do something with text2.
+ *  text2[4] = '2';
+ * // Run a reverse transformation.
+ * ubiditransform_transform(pBidiTransform,
+ *          text2, -1, text1, -1,
+ *          UBIDI_RTL, UBIDI_LOGICAL,
+ *          UBIDI_LTR, UBIDI_VISUAL,
+ *          UBIDI_MIRRORING_OFF,
+ *          U_SHAPE_DIGITS_EN2AN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
+ *          &errorCode);
+ *\endcode
+ * 
+ *

+ * + * @param pBiDiTransform A pointer to a UBiDiTransform object + * allocated with ubiditransform_open() or + * NULL.

+ * This object serves for one-time setup to amortize initialization + * overheads. Use of this object is not thread-safe. All other threads + * should allocate a new UBiDiTransform object by calling + * ubiditransform_open() before using it. Alternatively, + * a caller can set this parameter to NULL, in which case + * the object will be allocated by the engine on the fly.

+ * @param src A pointer to the text that the Bidi layout transformations will + * be performed on. + *

Note: the text must be (at least) + * srcLength long.

+ * @param srcLength The length of the text, in number of UChars. If + * length == -1 then the text must be zero-terminated. + * @param dest A pointer to where the processed text is to be copied. + * @param destSize The size of the dest buffer, in number of + * UChars. If the U_SHAPE_LETTERS_UNSHAPE option is set, + * then the destination length could be as large as + * srcLength * 2. Otherwise, the destination length will + * not exceed srcLength. If the caller reserves the last + * position for zero-termination, it should be excluded from + * destSize. + *

destSize == -1 is allowed and makes sense when + * dest was holds some meaningful value, e.g. that of + * src. In this case dest must be + * zero-terminated.

+ * @param inParaLevel A base embedding level of the input as defined in + * ubidi_setPara documentation for the + * paraLevel parameter. + * @param inOrder An order of the input, which can be one of the + * UBiDiOrder values. + * @param outParaLevel A base embedding level of the output as defined in + * ubidi_setPara documentation for the + * paraLevel parameter. + * @param outOrder An order of the output, which can be one of the + * UBiDiOrder values. + * @param doMirroring Indicates whether or not to perform character mirroring, + * and can accept one of the UBiDiMirroring values. + * @param shapingOptions Arabic digit and letter shaping options defined in the + * ushape.h documentation. + *

Note: Direction indicator options are computed by + * the transformation engine based on the effective ordering schemes, so + * user-defined direction indicators will be ignored.

+ * @param pErrorCode A pointer to an error code value. + * + * @return The destination length, i.e. the number of UChars written to + * dest. If the transformation fails, the return value + * will be 0 (and the error code will be written to + * pErrorCode). + * + * @see UBiDiLevel + * @see UBiDiOrder + * @see UBiDiMirroring + * @see ubidi_setPara + * @see u_shapeArabic + * @stable ICU 58 + */ +U_CAPI uint32_t U_EXPORT2 +ubiditransform_transform(UBiDiTransform *pBiDiTransform, + const UChar *src, int32_t srcLength, + UChar *dest, int32_t destSize, + UBiDiLevel inParaLevel, UBiDiOrder inOrder, + UBiDiLevel outParaLevel, UBiDiOrder outOrder, + UBiDiMirroring doMirroring, uint32_t shapingOptions, + UErrorCode *pErrorCode); + +/** + * Allocates a UBiDiTransform object. This object can be reused, + * e.g. with different ordering schemes, mirroring or shaping options.

+ * Note:The object can only be reused in the same thread. + * All other threads should allocate a new UBiDiTransform object + * before using it.

+ * Example of usage:

+ *

+ * \code
+ * UErrorCode errorCode = U_ZERO_ERROR;
+ * // Open a new UBiDiTransform.
+ * UBiDiTransform* transform = ubiditransform_open(&errorCode);
+ * // Run a transformation.
+ * ubiditransform_transform(transform,
+ *          text1, -1, text2, -1,
+ *          UBIDI_RTL, UBIDI_LOGICAL,
+ *          UBIDI_LTR, UBIDI_VISUAL,
+ *          UBIDI_MIRRORING_ON,
+ *          U_SHAPE_DIGITS_EN2AN,
+ *          &errorCode);
+ * // Do something with the output text and invoke another transformation using
+ * //   that text as input.
+ * ubiditransform_transform(transform,
+ *          text2, -1, text3, -1,
+ *          UBIDI_LTR, UBIDI_VISUAL,
+ *          UBIDI_RTL, UBIDI_VISUAL,
+ *          UBIDI_MIRRORING_ON,
+ *          0, &errorCode);
+ *\endcode
+ * 
+ *

+ * The UBiDiTransform object must be deallocated by calling + * ubiditransform_close(). + * + * @return An empty UBiDiTransform object. + * @stable ICU 58 + */ +U_CAPI UBiDiTransform* U_EXPORT2 +ubiditransform_open(UErrorCode *pErrorCode); + +/** + * Deallocates the given UBiDiTransform object. + * @stable ICU 58 + */ +U_CAPI void U_EXPORT2 +ubiditransform_close(UBiDiTransform *pBidiTransform); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUBiDiTransformPointer + * "Smart pointer" class, closes a UBiDiTransform via ubiditransform_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 58 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUBiDiTransformPointer, UBiDiTransform, ubiditransform_close); + +U_NAMESPACE_END + +#endif + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubrk.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubrk.h new file mode 100644 index 0000000000000000000000000000000000000000..2b3dc7aa576803ac5760aa186af3d632fcf65d2a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ubrk.h @@ -0,0 +1,647 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 1996-2015, International Business Machines Corporation and others. +* All Rights Reserved. +****************************************************************************** +*/ + +#ifndef UBRK_H +#define UBRK_H + +#include "unicode/utypes.h" +#include "unicode/uloc.h" +#include "unicode/utext.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * A text-break iterator. + * For usage in C programs. + */ +#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR +# define UBRK_TYPEDEF_UBREAK_ITERATOR + /** + * Opaque type representing an ICU Break iterator object. + * @stable ICU 2.0 + */ + typedef struct UBreakIterator UBreakIterator; +#endif + +#if !UCONFIG_NO_BREAK_ITERATION + +#include "unicode/parseerr.h" + +/** + * \file + * \brief C API: BreakIterator + * + *

BreakIterator C API

+ * + * The BreakIterator C API defines methods for finding the location + * of boundaries in text. Pointer to a UBreakIterator maintain a + * current position and scan over text returning the index of characters + * where boundaries occur. + *

+ * Line boundary analysis determines where a text string can be broken + * when line-wrapping. The mechanism correctly handles punctuation and + * hyphenated words. + *

+ * Note: The locale keyword "lb" can be used to modify line break + * behavior according to the CSS level 3 line-break options, see + * . For example: + * "ja@lb=strict", "zh@lb=loose". + *

+ * Sentence boundary analysis allows selection with correct + * interpretation of periods within numbers and abbreviations, and + * trailing punctuation marks such as quotation marks and parentheses. + *

+ * Note: The locale keyword "ss" can be used to enable use of + * segmentation suppression data (preventing breaks in English after + * abbreviations such as "Mr." or "Est.", for example), as follows: + * "en@ss=standard". + *

+ * Word boundary analysis is used by search and replace functions, as + * well as within text editing applications that allow the user to + * select words with a double click. Word selection provides correct + * interpretation of punctuation marks within and following + * words. Characters that are not part of a word, such as symbols or + * punctuation marks, have word-breaks on both sides. + *

+ * Character boundary analysis identifies the boundaries of + * "Extended Grapheme Clusters", which are groupings of codepoints + * that should be treated as character-like units for many text operations. + * Please see Unicode Standard Annex #29, Unicode Text Segmentation, + * http://www.unicode.org/reports/tr29/ for additional information + * on grapheme clusters and guidelines on their use. + *

+ * Title boundary analysis locates all positions, + * typically starts of words, that should be set to Title Case + * when title casing the text. + *

+ * The text boundary positions are found according to the rules + * described in Unicode Standard Annex #29, Text Boundaries, and + * Unicode Standard Annex #14, Line Breaking Properties. These + * are available at http://www.unicode.org/reports/tr14/ and + * http://www.unicode.org/reports/tr29/. + *

+ * In addition to the plain C API defined in this header file, an + * object oriented C++ API with equivalent functionality is defined in the + * file brkiter.h. + *

+ * Code snippets illustrating the use of the Break Iterator APIs + * are available in the ICU User Guide, + * https://unicode-org.github.io/icu/userguide/boundaryanalysis/ + * and in the sample program icu/source/samples/break/break.cpp + */ + +/** The possible types of text boundaries. @stable ICU 2.0 */ +typedef enum UBreakIteratorType { + /** Character breaks @stable ICU 2.0 */ + UBRK_CHARACTER = 0, + /** Word breaks @stable ICU 2.0 */ + UBRK_WORD = 1, + /** Line breaks @stable ICU 2.0 */ + UBRK_LINE = 2, + /** Sentence breaks @stable ICU 2.0 */ + UBRK_SENTENCE = 3, + +#ifndef U_HIDE_DEPRECATED_API + /** + * Title Case breaks + * The iterator created using this type locates title boundaries as described for + * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration, + * please use Word Boundary iterator. + * + * @deprecated ICU 2.8 Use the word break iterator for titlecasing for Unicode 4 and later. + */ + UBRK_TITLE = 4, + /** + * One more than the highest normal UBreakIteratorType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UBRK_COUNT = 5 +#endif // U_HIDE_DEPRECATED_API +} UBreakIteratorType; + +/** Value indicating all text boundaries have been returned. + * @stable ICU 2.0 + */ +#define UBRK_DONE ((int32_t) -1) + + +/** + * Enum constants for the word break tags returned by + * getRuleStatus(). A range of values is defined for each category of + * word, to allow for further subdivisions of a category in future releases. + * Applications should check for tag values falling within the range, rather + * than for single individual values. + * + * The numeric values of all of these constants are stable (will not change). + * + * @stable ICU 2.2 +*/ +typedef enum UWordBreak { + /** Tag value for "words" that do not fit into any of other categories. + * Includes spaces and most punctuation. */ + UBRK_WORD_NONE = 0, + /** Upper bound for tags for uncategorized words. */ + UBRK_WORD_NONE_LIMIT = 100, + /** Tag value for words that appear to be numbers, lower limit. */ + UBRK_WORD_NUMBER = 100, + /** Tag value for words that appear to be numbers, upper limit. */ + UBRK_WORD_NUMBER_LIMIT = 200, + /** Tag value for words that contain letters, excluding + * hiragana, katakana or ideographic characters, lower limit. */ + UBRK_WORD_LETTER = 200, + /** Tag value for words containing letters, upper limit */ + UBRK_WORD_LETTER_LIMIT = 300, + /** Tag value for words containing kana characters, lower limit */ + UBRK_WORD_KANA = 300, + /** Tag value for words containing kana characters, upper limit */ + UBRK_WORD_KANA_LIMIT = 400, + /** Tag value for words containing ideographic characters, lower limit */ + UBRK_WORD_IDEO = 400, + /** Tag value for words containing ideographic characters, upper limit */ + UBRK_WORD_IDEO_LIMIT = 500 +} UWordBreak; + +/** + * Enum constants for the line break tags returned by getRuleStatus(). + * A range of values is defined for each category of + * word, to allow for further subdivisions of a category in future releases. + * Applications should check for tag values falling within the range, rather + * than for single individual values. + * + * The numeric values of all of these constants are stable (will not change). + * + * @stable ICU 2.8 +*/ +typedef enum ULineBreakTag { + /** Tag value for soft line breaks, positions at which a line break + * is acceptable but not required */ + UBRK_LINE_SOFT = 0, + /** Upper bound for soft line breaks. */ + UBRK_LINE_SOFT_LIMIT = 100, + /** Tag value for a hard, or mandatory line break */ + UBRK_LINE_HARD = 100, + /** Upper bound for hard line breaks. */ + UBRK_LINE_HARD_LIMIT = 200 +} ULineBreakTag; + + + +/** + * Enum constants for the sentence break tags returned by getRuleStatus(). + * A range of values is defined for each category of + * sentence, to allow for further subdivisions of a category in future releases. + * Applications should check for tag values falling within the range, rather + * than for single individual values. + * + * The numeric values of all of these constants are stable (will not change). + * + * @stable ICU 2.8 +*/ +typedef enum USentenceBreakTag { + /** Tag value for for sentences ending with a sentence terminator + * ('.', '?', '!', etc.) character, possibly followed by a + * hard separator (CR, LF, PS, etc.) + */ + UBRK_SENTENCE_TERM = 0, + /** Upper bound for tags for sentences ended by sentence terminators. */ + UBRK_SENTENCE_TERM_LIMIT = 100, + /** Tag value for for sentences that do not contain an ending + * sentence terminator ('.', '?', '!', etc.) character, but + * are ended only by a hard separator (CR, LF, PS, etc.) or end of input. + */ + UBRK_SENTENCE_SEP = 100, + /** Upper bound for tags for sentences ended by a separator. */ + UBRK_SENTENCE_SEP_LIMIT = 200 + /** Tag value for a hard, or mandatory line break */ +} USentenceBreakTag; + + +/** + * Open a new UBreakIterator for locating text boundaries for a specified locale. + * A UBreakIterator may be used for detecting character, line, word, + * and sentence breaks in text. + * @param type The type of UBreakIterator to open: one of UBRK_CHARACTER, UBRK_WORD, + * UBRK_LINE, UBRK_SENTENCE + * @param locale The locale specifying the text-breaking conventions. Note that + * locale keys such as "lb" and "ss" may be used to modify text break behavior, + * see general discussion of BreakIterator C API. + * @param text The text to be iterated over. May be null, in which case ubrk_setText() is + * used to specify the text to be iterated. + * @param textLength The number of characters in text, or -1 if null-terminated. + * @param status A UErrorCode to receive any errors. + * @return A UBreakIterator for the specified locale. + * @see ubrk_openRules + * @stable ICU 2.0 + */ +U_CAPI UBreakIterator* U_EXPORT2 +ubrk_open(UBreakIteratorType type, + const char *locale, + const UChar *text, + int32_t textLength, + UErrorCode *status); + +/** + * Open a new UBreakIterator for locating text boundaries using specified breaking rules. + * The rule syntax is ... (TBD) + * @param rules A set of rules specifying the text breaking conventions. + * @param rulesLength The number of characters in rules, or -1 if null-terminated. + * @param text The text to be iterated over. May be null, in which case ubrk_setText() is + * used to specify the text to be iterated. + * @param textLength The number of characters in text, or -1 if null-terminated. + * @param parseErr Receives position and context information for any syntax errors + * detected while parsing the rules. + * @param status A UErrorCode to receive any errors. + * @return A UBreakIterator for the specified rules. + * @see ubrk_open + * @stable ICU 2.2 + */ +U_CAPI UBreakIterator* U_EXPORT2 +ubrk_openRules(const UChar *rules, + int32_t rulesLength, + const UChar *text, + int32_t textLength, + UParseError *parseErr, + UErrorCode *status); + +/** + * Open a new UBreakIterator for locating text boundaries using precompiled binary rules. + * Opening a UBreakIterator this way is substantially faster than using ubrk_openRules. + * Binary rules may be obtained using ubrk_getBinaryRules. The compiled rules are not + * compatible across different major versions of ICU, nor across platforms of different + * endianness or different base character set family (ASCII vs EBCDIC). + * @param binaryRules A set of compiled binary rules specifying the text breaking + * conventions. Ownership of the storage containing the compiled + * rules remains with the caller of this function. The compiled + * rules must not be modified or deleted during the life of the + * break iterator. + * @param rulesLength The length of binaryRules in bytes; must be >= 0. + * @param text The text to be iterated over. May be null, in which case + * ubrk_setText() is used to specify the text to be iterated. + * @param textLength The number of characters in text, or -1 if null-terminated. + * @param status Pointer to UErrorCode to receive any errors. + * @return UBreakIterator for the specified rules. + * @see ubrk_getBinaryRules + * @stable ICU 59 + */ +U_CAPI UBreakIterator* U_EXPORT2 +ubrk_openBinaryRules(const uint8_t *binaryRules, int32_t rulesLength, + const UChar * text, int32_t textLength, + UErrorCode * status); + +#ifndef U_HIDE_DEPRECATED_API + +/** + * Thread safe cloning operation + * @param bi iterator to be cloned + * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
+ * user allocated space for the new clone. If NULL new memory will be allocated. + * If buffer is not large enough, new memory will be allocated. + * Clients can use the U_BRK_SAFECLONE_BUFFERSIZE. + * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
+ * pointer to size of allocated space. + * If *pBufferSize == 0, a sufficient size for use in cloning will + * be returned ('pre-flighting') + * If *pBufferSize is not enough for a stack-based safe clone, + * new memory will be allocated. + * @param status to indicate whether the operation went on smoothly or there were errors + * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used + * if pBufferSize != NULL and any allocations were necessary + * @return pointer to the new clone + * @deprecated ICU 69 Use ubrk_clone() instead. + */ +U_DEPRECATED UBreakIterator * U_EXPORT2 +ubrk_safeClone( + const UBreakIterator *bi, + void *stackBuffer, + int32_t *pBufferSize, + UErrorCode *status); + +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Thread safe cloning operation. + * @param bi iterator to be cloned + * @param status to indicate whether the operation went on smoothly or there were errors + * @return pointer to the new clone + * @stable ICU 69 + */ +U_CAPI UBreakIterator * U_EXPORT2 +ubrk_clone(const UBreakIterator *bi, + UErrorCode *status); + +#ifndef U_HIDE_DEPRECATED_API + +/** + * A recommended size (in bytes) for the memory buffer to be passed to ubrk_saveClone(). + * @deprecated ICU 52. Do not rely on ubrk_safeClone() cloning into any provided buffer. + */ +#define U_BRK_SAFECLONE_BUFFERSIZE 1 + +#endif /* U_HIDE_DEPRECATED_API */ + +/** +* Close a UBreakIterator. +* Once closed, a UBreakIterator may no longer be used. +* @param bi The break iterator to close. + * @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +ubrk_close(UBreakIterator *bi); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUBreakIteratorPointer + * "Smart pointer" class, closes a UBreakIterator via ubrk_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUBreakIteratorPointer, UBreakIterator, ubrk_close); + +U_NAMESPACE_END + +#endif + +/** + * Sets an existing iterator to point to a new piece of text. + * The break iterator retains a pointer to the supplied text. + * The caller must not modify or delete the text while the BreakIterator + * retains the reference. + * + * @param bi The iterator to use + * @param text The text to be set + * @param textLength The length of the text + * @param status The error code + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ubrk_setText(UBreakIterator* bi, + const UChar* text, + int32_t textLength, + UErrorCode* status); + + +/** + * Sets an existing iterator to point to a new piece of text. + * + * All index positions returned by break iterator functions are + * native indices from the UText. For example, when breaking UTF-8 + * encoded text, the break positions returned by \ref ubrk_next, \ref ubrk_previous, etc. + * will be UTF-8 string indices, not UTF-16 positions. + * + * @param bi The iterator to use + * @param text The text to be set. + * This function makes a shallow clone of the supplied UText. This means + * that the caller is free to immediately close or otherwise reuse the + * UText that was passed as a parameter, but that the underlying text itself + * must not be altered while being referenced by the break iterator. + * @param status The error code + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ubrk_setUText(UBreakIterator* bi, + UText* text, + UErrorCode* status); + + + +/** + * Determine the most recently-returned text boundary. + * + * @param bi The break iterator to use. + * @return The character index most recently returned by \ref ubrk_next, \ref ubrk_previous, + * \ref ubrk_first, or \ref ubrk_last. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_current(const UBreakIterator *bi); + +/** + * Advance the iterator to the boundary following the current boundary. + * + * @param bi The break iterator to use. + * @return The character index of the next text boundary, or UBRK_DONE + * if all text boundaries have been returned. + * @see ubrk_previous + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_next(UBreakIterator *bi); + +/** + * Set the iterator position to the boundary preceding the current boundary. + * + * @param bi The break iterator to use. + * @return The character index of the preceding text boundary, or UBRK_DONE + * if all text boundaries have been returned. + * @see ubrk_next + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_previous(UBreakIterator *bi); + +/** + * Set the iterator position to zero, the start of the text being scanned. + * @param bi The break iterator to use. + * @return The new iterator position (zero). + * @see ubrk_last + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_first(UBreakIterator *bi); + +/** + * Set the iterator position to the index immediately beyond the last character in the text being scanned. + * This is not the same as the last character. + * @param bi The break iterator to use. + * @return The character offset immediately beyond the last character in the + * text being scanned. + * @see ubrk_first + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_last(UBreakIterator *bi); + +/** + * Set the iterator position to the first boundary preceding the specified offset. + * The new position is always smaller than offset, or UBRK_DONE. + * @param bi The break iterator to use. + * @param offset The offset to begin scanning. + * @return The text boundary preceding offset, or UBRK_DONE. + * @see ubrk_following + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_preceding(UBreakIterator *bi, + int32_t offset); + +/** + * Advance the iterator to the first boundary following the specified offset. + * The value returned is always greater than offset, or UBRK_DONE. + * @param bi The break iterator to use. + * @param offset The offset to begin scanning. + * @return The text boundary following offset, or UBRK_DONE. + * @see ubrk_preceding + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_following(UBreakIterator *bi, + int32_t offset); + +/** +* Get a locale for which text breaking information is available. +* A UBreakIterator in a locale returned by this function will perform the correct +* text breaking for the locale. +* @param index The index of the desired locale. +* @return A locale for which number text breaking information is available, or 0 if none. +* @see ubrk_countAvailable +* @stable ICU 2.0 +*/ +U_CAPI const char* U_EXPORT2 +ubrk_getAvailable(int32_t index); + +/** +* Determine how many locales have text breaking information available. +* This function is most useful as determining the loop ending condition for +* calls to \ref ubrk_getAvailable. +* @return The number of locales for which text breaking information is available. +* @see ubrk_getAvailable +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +ubrk_countAvailable(void); + + +/** +* Returns true if the specified position is a boundary position. As a side +* effect, leaves the iterator pointing to the first boundary position at +* or after "offset". +* @param bi The break iterator to use. +* @param offset the offset to check. +* @return True if "offset" is a boundary position. +* @stable ICU 2.0 +*/ +U_CAPI UBool U_EXPORT2 +ubrk_isBoundary(UBreakIterator *bi, int32_t offset); + +/** + * Return the status from the break rule that determined the most recently + * returned break position. The values appear in the rule source + * within brackets, {123}, for example. For rules that do not specify a + * status, a default value of 0 is returned. + *

+ * For word break iterators, the possible values are defined in enum UWordBreak. + * @stable ICU 2.2 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_getRuleStatus(UBreakIterator *bi); + +/** + * Get the statuses from the break rules that determined the most recently + * returned break position. The values appear in the rule source + * within brackets, {123}, for example. The default status value for rules + * that do not explicitly provide one is zero. + *

+ * For word break iterators, the possible values are defined in enum UWordBreak. + * @param bi The break iterator to use + * @param fillInVec an array to be filled in with the status values. + * @param capacity the length of the supplied vector. A length of zero causes + * the function to return the number of status values, in the + * normal way, without attempting to store any values. + * @param status receives error codes. + * @return The number of rule status values from rules that determined + * the most recent boundary returned by the break iterator. + * @stable ICU 3.0 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_getRuleStatusVec(UBreakIterator *bi, int32_t *fillInVec, int32_t capacity, UErrorCode *status); + +/** + * Return the locale of the break iterator. You can choose between the valid and + * the actual locale. + * @param bi break iterator + * @param type locale type (valid or actual) + * @param status error code + * @return locale string + * @stable ICU 2.8 + */ +U_CAPI const char* U_EXPORT2 +ubrk_getLocaleByType(const UBreakIterator *bi, ULocDataLocaleType type, UErrorCode* status); + +/** + * Set the subject text string upon which the break iterator is operating + * without changing any other aspect of the state. + * The new and previous text strings must have the same content. + * + * This function is intended for use in environments where ICU is operating on + * strings that may move around in memory. It provides a mechanism for notifying + * ICU that the string has been relocated, and providing a new UText to access the + * string in its new position. + * + * Note that the break iterator never copies the underlying text + * of a string being processed, but always operates directly on the original text + * provided by the user. Refreshing simply drops the references to the old text + * and replaces them with references to the new. + * + * Caution: this function is normally used only by very specialized + * system-level code. One example use case is with garbage collection + * that moves the text in memory. + * + * @param bi The break iterator. + * @param text The new (moved) text string. + * @param status Receives errors detected by this function. + * + * @stable ICU 49 + */ +U_CAPI void U_EXPORT2 +ubrk_refreshUText(UBreakIterator *bi, + UText *text, + UErrorCode *status); + + +/** + * Get a compiled binary version of the rules specifying the behavior of a UBreakIterator. + * The binary rules may be used with ubrk_openBinaryRules to open a new UBreakIterator + * more quickly than using ubrk_openRules. The compiled rules are not compatible across + * different major versions of ICU, nor across platforms of different endianness or + * different base character set family (ASCII vs EBCDIC). Supports preflighting (with + * binaryRules=NULL and rulesCapacity=0) to get the rules length without copying them to + * the binaryRules buffer. However, whether preflighting or not, if the actual length + * is greater than INT32_MAX, then the function returns 0 and sets *status to + * U_INDEX_OUTOFBOUNDS_ERROR. + + * @param bi The break iterator to use. + * @param binaryRules Buffer to receive the compiled binary rules; set to NULL for + * preflighting. + * @param rulesCapacity Capacity (in bytes) of the binaryRules buffer; set to 0 for + * preflighting. Must be >= 0. + * @param status Pointer to UErrorCode to receive any errors, such as + * U_BUFFER_OVERFLOW_ERROR, U_INDEX_OUTOFBOUNDS_ERROR, or + * U_ILLEGAL_ARGUMENT_ERROR. + * @return The actual byte length of the binary rules, if <= INT32_MAX; + * otherwise 0. If not preflighting and this is larger than + * rulesCapacity, *status will be set to an error. + * @see ubrk_openBinaryRules + * @stable ICU 59 + */ +U_CAPI int32_t U_EXPORT2 +ubrk_getBinaryRules(UBreakIterator *bi, + uint8_t * binaryRules, int32_t rulesCapacity, + UErrorCode * status); + +#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucal.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucal.h new file mode 100644 index 0000000000000000000000000000000000000000..f428dfcc616032f5320b6446cd8bd75a88c67478 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucal.h @@ -0,0 +1,1747 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 1996-2015, International Business Machines Corporation and + * others. All Rights Reserved. + ******************************************************************************* + */ + +#ifndef UCAL_H +#define UCAL_H + +#include "unicode/utypes.h" +#include "unicode/uenum.h" +#include "unicode/uloc.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +#if !UCONFIG_NO_FORMATTING + +/** + * \file + * \brief C API: Calendar + * + *

Calendar C API

+ * + * UCalendar C API is used for converting between a UDate object + * and a set of integer fields such as UCAL_YEAR, UCAL_MONTH, + * UCAL_DAY, UCAL_HOUR, and so on. + * (A UDate object represents a specific instant in + * time with millisecond precision. See UDate + * for information about the UDate .) + * + *

+ * Types of UCalendar interpret a UDate + * according to the rules of a specific calendar system. The C API + * provides the enum UCalendarType with UCAL_TRADITIONAL and + * UCAL_GREGORIAN. + *

+ * Like other locale-sensitive C API, calendar API provides a + * function, ucal_open(), which returns a pointer to + * UCalendar whose time fields have been initialized + * with the current date and time. We need to specify the type of + * calendar to be opened and the timezoneId. + * \htmlonly

\endhtmlonly + *
+ * \code
+ * UCalendar *caldef;
+ * UChar *tzId;
+ * UErrorCode status;
+ * tzId=(UChar*)malloc(sizeof(UChar) * (strlen("PST") +1) );
+ * u_uastrcpy(tzId, "PST");
+ * caldef=ucal_open(tzID, u_strlen(tzID), NULL, UCAL_TRADITIONAL, &status);
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * + *

+ * A UCalendar object can produce all the time field values + * needed to implement the date-time formatting for a particular language + * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). + * + *

+ * When computing a UDate from time fields, two special circumstances + * may arise: there may be insufficient information to compute the + * UDate (such as only year and month but no day in the month), + * or there may be inconsistent information (such as "Tuesday, July 15, 1996" + * -- July 15, 1996 is actually a Monday). + * + *

+ * Insufficient information. The calendar will use default + * information to specify the missing fields. This may vary by calendar; for + * the Gregorian calendar, the default for a field is the same as that of the + * start of the epoch: i.e., UCAL_YEAR = 1970, UCAL_MONTH = JANUARY, UCAL_DATE = 1, etc. + * + *

+ * Inconsistent information. If fields conflict, the calendar + * will give preference to fields set more recently. For example, when + * determining the day, the calendar will look for one of the following + * combinations of fields. The most recent combination, as determined by the + * most recently set single field, will be used. + * + * \htmlonly

\endhtmlonly + *
+ * \code
+ * UCAL_MONTH + UCAL_DAY_OF_MONTH
+ * UCAL_MONTH + UCAL_WEEK_OF_MONTH + UCAL_DAY_OF_WEEK
+ * UCAL_MONTH + UCAL_DAY_OF_WEEK_IN_MONTH + UCAL_DAY_OF_WEEK
+ * UCAL_DAY_OF_YEAR
+ * UCAL_DAY_OF_WEEK + UCAL_WEEK_OF_YEAR
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * + * For the time of day: + * + * \htmlonly
\endhtmlonly + *
+ * \code
+ * UCAL_HOUR_OF_DAY
+ * UCAL_AM_PM + UCAL_HOUR
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * + *

+ * Note: for some non-Gregorian calendars, different + * fields may be necessary for complete disambiguation. For example, a full + * specification of the historical Arabic astronomical calendar requires year, + * month, day-of-month and day-of-week in some cases. + * + *

+ * Note: There are certain possible ambiguities in + * interpretation of certain singular times, which are resolved in the + * following ways: + *

    + *
  1. 24:00:00 "belongs" to the following day. That is, + * 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970 + * + *
  2. Although historically not precise, midnight also belongs to "am", + * and noon belongs to "pm", so on the same day, + * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm + *
+ * + *

+ * The date or time format strings are not part of the definition of a + * calendar, as those must be modifiable or overridable by the user at + * runtime. Use {@link icu::DateFormat} + * to format dates. + * + *

+ * Calendar provides an API for field "rolling", where fields + * can be incremented or decremented, but wrap around. For example, rolling the + * month up in the date December 12, 1996 results in + * January 12, 1996. + * + *

+ * Calendar also provides a date arithmetic function for + * adding the specified (signed) amount of time to a particular time field. + * For example, subtracting 5 days from the date September 12, 1996 + * results in September 7, 1996. + * + *

+ * The Japanese calendar uses a combination of era name and year number. + * When an emperor of Japan abdicates and a new emperor ascends the throne, + * a new era is declared and year number is reset to 1. Even if the date of + * abdication is scheduled ahead of time, the new era name might not be + * announced until just before the date. In such case, ICU4C may include + * a start date of future era without actual era name, but not enabled + * by default. ICU4C users who want to test the behavior of the future era + * can enable the tentative era by: + *

    + *
  • Environment variable ICU_ENABLE_TENTATIVE_ERA=true.
  • + *
+ * + * @stable ICU 2.0 + */ + +/** + * The time zone ID reserved for unknown time zone. + * It behaves like the GMT/UTC time zone but has the special ID "Etc/Unknown". + * @stable ICU 4.8 + */ +#define UCAL_UNKNOWN_ZONE_ID "Etc/Unknown" + +/** A calendar. + * For usage in C programs. + * @stable ICU 2.0 + */ +typedef void* UCalendar; + +/** Possible types of UCalendars + * @stable ICU 2.0 + */ +enum UCalendarType { + /** + * Despite the name, UCAL_TRADITIONAL designates the locale's default calendar, + * which may be the Gregorian calendar or some other calendar. + * @stable ICU 2.0 + */ + UCAL_TRADITIONAL, + /** + * A better name for UCAL_TRADITIONAL. + * @stable ICU 4.2 + */ + UCAL_DEFAULT = UCAL_TRADITIONAL, + /** + * Unambiguously designates the Gregorian calendar for the locale. + * @stable ICU 2.0 + */ + UCAL_GREGORIAN +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarType UCalendarType; + +/** Possible fields in a UCalendar + * @stable ICU 2.0 + */ +enum UCalendarDateFields { + /** + * Field number indicating the era, e.g., AD or BC in the Gregorian (Julian) calendar. + * This is a calendar-specific value. + * @stable ICU 2.6 + */ + UCAL_ERA, + + /** + * Field number indicating the year. This is a calendar-specific value. + * @stable ICU 2.6 + */ + UCAL_YEAR, + + /** + * Field number indicating the month. This is a calendar-specific value. + * The first month of the year is + * JANUARY; the last depends on the number of months in a year. + * @see #UCAL_JANUARY + * @see #UCAL_FEBRUARY + * @see #UCAL_MARCH + * @see #UCAL_APRIL + * @see #UCAL_MAY + * @see #UCAL_JUNE + * @see #UCAL_JULY + * @see #UCAL_AUGUST + * @see #UCAL_SEPTEMBER + * @see #UCAL_OCTOBER + * @see #UCAL_NOVEMBER + * @see #UCAL_DECEMBER + * @see #UCAL_UNDECIMBER + * @stable ICU 2.6 + */ + UCAL_MONTH, + + /** + * Field number indicating the + * week number within the current year. The first week of the year, as + * defined by UCAL_FIRST_DAY_OF_WEEK and UCAL_MINIMAL_DAYS_IN_FIRST_WEEK + * attributes, has value 1. Subclasses define + * the value of UCAL_WEEK_OF_YEAR for days before the first week of + * the year. + * @see ucal_getAttribute + * @see ucal_setAttribute + * @stable ICU 2.6 + */ + UCAL_WEEK_OF_YEAR, + + /** + * Field number indicating the + * week number within the current month. The first week of the month, as + * defined by UCAL_FIRST_DAY_OF_WEEK and UCAL_MINIMAL_DAYS_IN_FIRST_WEEK + * attributes, has value 1. Subclasses define + * the value of WEEK_OF_MONTH for days before the first week of + * the month. + * @see ucal_getAttribute + * @see ucal_setAttribute + * @see #UCAL_FIRST_DAY_OF_WEEK + * @see #UCAL_MINIMAL_DAYS_IN_FIRST_WEEK + * @stable ICU 2.6 + */ + UCAL_WEEK_OF_MONTH, + + /** + * Field number indicating the + * day of the month. This is a synonym for DAY_OF_MONTH. + * The first day of the month has value 1. + * @see #UCAL_DAY_OF_MONTH + * @stable ICU 2.6 + */ + UCAL_DATE, + + /** + * Field number indicating the day + * number within the current year. The first day of the year has value 1. + * @stable ICU 2.6 + */ + UCAL_DAY_OF_YEAR, + + /** + * Field number indicating the day + * of the week. This field takes values SUNDAY, + * MONDAY, TUESDAY, WEDNESDAY, + * THURSDAY, FRIDAY, and SATURDAY. + * @see #UCAL_SUNDAY + * @see #UCAL_MONDAY + * @see #UCAL_TUESDAY + * @see #UCAL_WEDNESDAY + * @see #UCAL_THURSDAY + * @see #UCAL_FRIDAY + * @see #UCAL_SATURDAY + * @stable ICU 2.6 + */ + UCAL_DAY_OF_WEEK, + + /** + * Field number indicating the + * ordinal number of the day of the week within the current month. Together + * with the DAY_OF_WEEK field, this uniquely specifies a day + * within a month. Unlike WEEK_OF_MONTH and + * WEEK_OF_YEAR, this field's value does not depend on + * getFirstDayOfWeek() or + * getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 + * through 7 always correspond to DAY_OF_WEEK_IN_MONTH + * 1; 8 through 15 correspond to + * DAY_OF_WEEK_IN_MONTH 2, and so on. + * DAY_OF_WEEK_IN_MONTH 0 indicates the week before + * DAY_OF_WEEK_IN_MONTH 1. Negative values count back from the + * end of the month, so the last Sunday of a month is specified as + * DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1. Because + * negative values count backward they will usually be aligned differently + * within the month than positive values. For example, if a month has 31 + * days, DAY_OF_WEEK_IN_MONTH -1 will overlap + * DAY_OF_WEEK_IN_MONTH 5 and the end of 4. + * @see #UCAL_DAY_OF_WEEK + * @see #UCAL_WEEK_OF_MONTH + * @stable ICU 2.6 + */ + UCAL_DAY_OF_WEEK_IN_MONTH, + + /** + * Field number indicating + * whether the HOUR is before or after noon. + * E.g., at 10:04:15.250 PM the AM_PM is PM. + * @see #UCAL_AM + * @see #UCAL_PM + * @see #UCAL_HOUR + * @stable ICU 2.6 + */ + UCAL_AM_PM, + + /** + * Field number indicating the + * hour of the morning or afternoon. HOUR is used for the 12-hour + * clock. + * E.g., at 10:04:15.250 PM the HOUR is 10. + * @see #UCAL_AM_PM + * @see #UCAL_HOUR_OF_DAY + * @stable ICU 2.6 + */ + UCAL_HOUR, + + /** + * Field number indicating the + * hour of the day. HOUR_OF_DAY is used for the 24-hour clock. + * E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22. + * @see #UCAL_HOUR + * @stable ICU 2.6 + */ + UCAL_HOUR_OF_DAY, + + /** + * Field number indicating the + * minute within the hour. + * E.g., at 10:04:15.250 PM the UCAL_MINUTE is 4. + * @stable ICU 2.6 + */ + UCAL_MINUTE, + + /** + * Field number indicating the + * second within the minute. + * E.g., at 10:04:15.250 PM the UCAL_SECOND is 15. + * @stable ICU 2.6 + */ + UCAL_SECOND, + + /** + * Field number indicating the + * millisecond within the second. + * E.g., at 10:04:15.250 PM the UCAL_MILLISECOND is 250. + * @stable ICU 2.6 + */ + UCAL_MILLISECOND, + + /** + * Field number indicating the + * raw offset from GMT in milliseconds. + * @stable ICU 2.6 + */ + UCAL_ZONE_OFFSET, + + /** + * Field number indicating the + * daylight savings offset in milliseconds. + * @stable ICU 2.6 + */ + UCAL_DST_OFFSET, + + /** + * Field number + * indicating the extended year corresponding to the + * UCAL_WEEK_OF_YEAR field. This may be one greater or less + * than the value of UCAL_EXTENDED_YEAR. + * @stable ICU 2.6 + */ + UCAL_YEAR_WOY, + + /** + * Field number + * indicating the localized day of week. This will be a value from 1 + * to 7 inclusive, with 1 being the localized first day of the week. + * @stable ICU 2.6 + */ + UCAL_DOW_LOCAL, + + /** + * Year of this calendar system, encompassing all supra-year fields. For example, + * in Gregorian/Julian calendars, positive Extended Year values indicate years AD, + * 1 BC = 0 extended, 2 BC = -1 extended, and so on. + * @stable ICU 2.8 + */ + UCAL_EXTENDED_YEAR, + + /** + * Field number + * indicating the modified Julian day number. This is different from + * the conventional Julian day number in two regards. First, it + * demarcates days at local zone midnight, rather than noon GMT. + * Second, it is a local number; that is, it depends on the local time + * zone. It can be thought of as a single number that encompasses all + * the date-related fields. + * @stable ICU 2.8 + */ + UCAL_JULIAN_DAY, + + /** + * Ranges from 0 to 23:59:59.999 (regardless of DST). This field behaves exactly + * like a composite of all time-related fields, not including the zone fields. As such, + * it also reflects discontinuities of those fields on DST transition days. On a day + * of DST onset, it will jump forward. On a day of DST cessation, it will jump + * backward. This reflects the fact that it must be combined with the DST_OFFSET field + * to obtain a unique local time value. + * @stable ICU 2.8 + */ + UCAL_MILLISECONDS_IN_DAY, + + /** + * Whether or not the current month is a leap month (0 or 1). See the Chinese calendar for + * an example of this. + */ + UCAL_IS_LEAP_MONTH, + +#ifndef U_HIDE_DRAFT_API + /** + * Field number indicating the month. This is a calendar-specific value. + * Differ from UCAL_MONTH, this value is continuous and unique within a + * year and range from 0 to 11 or 0 to 12 depending on how many months in a + * year, the calendar system has leap month or not, and in leap year or not. + * It is the ordinal position of that month in the corresponding year of + * the calendar. For Chinese, Dangi, and Hebrew calendar, the range is + * 0 to 11 in non-leap years and 0 to 12 in leap years. For Coptic and Ethiopian + * calendar, the range is always 0 to 12. For other calendars supported by + * ICU now, the range is 0 to 11. When the number of months in a year of the + * identified calendar is variable, a different UCAL_ORDINAL_MONTH value can + * be used for dates that are part of the same named month in different years. + * For example, in the Hebrew calendar, "1 Nisan 5781" is associated with + * UCAL_ORDINAL_MONTH value 6 while "1 Nisan 5782" is associated with + * UCAL_ORDINAL_MONTH value 7 because 5782 is a leap year and Nisan follows + * the insertion of Adar I. In Chinese calendar, "Year 4664 Month 6 Day 2" + * is associated with UCAL_ORDINAL_MONTH value 5 while "Year 4665 Month 6 Day 2" + * is associated with UCAL_ORDINAL_MONTH value 6 because 4665 is a leap year + * and there is an extra "Leap Month 5" which associated with UCAL_ORDINAL_MONTH + * value 5 before "Month 6" of year 4664. + * + * @draft ICU 73 + */ + UCAL_ORDINAL_MONTH, +#endif // U_HIDE_DRAFT_API + + /* Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, + * it is needed for layout of Calendar, DateFormat, and other objects */ +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * One more than the highest normal UCalendarDateFields value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ +#ifdef U_HIDE_DRAFT_API + // Must include all fields that will be in structs + UCAL_FIELD_COUNT = UCAL_IS_LEAP_MONTH + 2, +#else // U_HIDE_DRAFT_API (for UCAL_ORDINAL_MONTH) + UCAL_FIELD_COUNT = UCAL_ORDINAL_MONTH + 1, +#endif // U_HIDE_DRAFT_API (for UCAL_ORDINAL_MONTH) + +#endif // U_FORCE_HIDE_DEPRECATED_API + + /** + * Field number indicating the + * day of the month. This is a synonym for UCAL_DATE. + * The first day of the month has value 1. + * @see #UCAL_DATE + * Synonym for UCAL_DATE + * @stable ICU 2.8 + **/ + UCAL_DAY_OF_MONTH=UCAL_DATE +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarDateFields UCalendarDateFields; + /** + * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients + * who create locale resources for the field of first-day-of-week should be aware of + * this. For instance, in US locale, first-day-of-week is set to 1, i.e., UCAL_SUNDAY. + */ +/** Possible days of the week in a UCalendar + * @stable ICU 2.0 + */ +enum UCalendarDaysOfWeek { + /** Sunday */ + UCAL_SUNDAY = 1, + /** Monday */ + UCAL_MONDAY, + /** Tuesday */ + UCAL_TUESDAY, + /** Wednesday */ + UCAL_WEDNESDAY, + /** Thursday */ + UCAL_THURSDAY, + /** Friday */ + UCAL_FRIDAY, + /** Saturday */ + UCAL_SATURDAY +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarDaysOfWeek UCalendarDaysOfWeek; + +/** Possible months in a UCalendar. Note: Calendar month is 0-based. + * @stable ICU 2.0 + */ +enum UCalendarMonths { + /** January */ + UCAL_JANUARY, + /** February */ + UCAL_FEBRUARY, + /** March */ + UCAL_MARCH, + /** April */ + UCAL_APRIL, + /** May */ + UCAL_MAY, + /** June */ + UCAL_JUNE, + /** July */ + UCAL_JULY, + /** August */ + UCAL_AUGUST, + /** September */ + UCAL_SEPTEMBER, + /** October */ + UCAL_OCTOBER, + /** November */ + UCAL_NOVEMBER, + /** December */ + UCAL_DECEMBER, + /** Value of the UCAL_MONTH field indicating the + * thirteenth month of the year. Although the Gregorian calendar + * does not use this value, lunar calendars do. + */ + UCAL_UNDECIMBER +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarMonths UCalendarMonths; + +/** Possible AM/PM values in a UCalendar + * @stable ICU 2.0 + */ +enum UCalendarAMPMs { + /** AM */ + UCAL_AM, + /** PM */ + UCAL_PM +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarAMPMs UCalendarAMPMs; + +/** + * System time zone type constants used by filtering zones + * in ucal_openTimeZoneIDEnumeration. + * @see ucal_openTimeZoneIDEnumeration + * @stable ICU 4.8 + */ +enum USystemTimeZoneType { + /** + * Any system zones. + * @stable ICU 4.8 + */ + UCAL_ZONE_TYPE_ANY, + /** + * Canonical system zones. + * @stable ICU 4.8 + */ + UCAL_ZONE_TYPE_CANONICAL, + /** + * Canonical system zones associated with actual locations. + * @stable ICU 4.8 + */ + UCAL_ZONE_TYPE_CANONICAL_LOCATION +}; + +/** @stable ICU 4.8 */ +typedef enum USystemTimeZoneType USystemTimeZoneType; + +/** + * Create an enumeration over system time zone IDs with the given + * filter conditions. + * @param zoneType The system time zone type. + * @param region The ISO 3166 two-letter country code or UN M.49 + * three-digit area code. When NULL, no filtering + * done by region. + * @param rawOffset An offset from GMT in milliseconds, ignoring the + * effect of daylight savings time, if any. When NULL, + * no filtering done by zone offset. + * @param ec A pointer to an UErrorCode to receive any errors + * @return an enumeration object that the caller must dispose of + * using enum_close(), or NULL upon failure. In case of failure, + * *ec will indicate the error. + * @stable ICU 4.8 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucal_openTimeZoneIDEnumeration(USystemTimeZoneType zoneType, const char* region, + const int32_t* rawOffset, UErrorCode* ec); + +/** + * Create an enumeration over all time zones. + * + * @param ec input/output error code + * + * @return an enumeration object that the caller must dispose of using + * uenum_close(), or NULL upon failure. In case of failure *ec will + * indicate the error. + * + * @stable ICU 2.6 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucal_openTimeZones(UErrorCode* ec); + +/** + * Create an enumeration over all time zones associated with the given + * country. Some zones are affiliated with no country (e.g., "UTC"); + * these may also be retrieved, as a group. + * + * @param country the ISO 3166 two-letter country code, or NULL to + * retrieve zones not affiliated with any country + * + * @param ec input/output error code + * + * @return an enumeration object that the caller must dispose of using + * uenum_close(), or NULL upon failure. In case of failure *ec will + * indicate the error. + * + * @stable ICU 2.6 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucal_openCountryTimeZones(const char* country, UErrorCode* ec); + +/** + * Return the default time zone. The default is determined initially + * by querying the host operating system. If the host system detection + * routines fail, or if they specify a TimeZone or TimeZone offset + * which is not recognized, then the special TimeZone "Etc/Unknown" + * is returned. + * + * The default may be changed with `ucal_setDefaultTimeZone()` or with + * the C++ TimeZone API, `TimeZone::adoptDefault(TimeZone*)`. + * + * @param result A buffer to receive the result, or NULL + * + * @param resultCapacity The capacity of the result buffer + * + * @param ec input/output error code + * + * @return The result string length, not including the terminating + * null + * + * @see #UCAL_UNKNOWN_ZONE_ID + * + * @stable ICU 2.6 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getDefaultTimeZone(UChar* result, int32_t resultCapacity, UErrorCode* ec); + +/** + * Set the default time zone. + * + * @param zoneID null-terminated time zone ID + * + * @param ec input/output error code + * + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +ucal_setDefaultTimeZone(const UChar* zoneID, UErrorCode* ec); + +/** + * Return the current host time zone. The host time zone is detected from + * the current host system configuration by querying the host operating + * system. If the host system detection routines fail, or if they specify + * a TimeZone or TimeZone offset which is not recognized, then the special + * TimeZone "Etc/Unknown" is returned. + * + * Note that host time zone and the ICU default time zone can be different. + * + * The ICU default time zone does not change once initialized unless modified + * by calling `ucal_setDefaultTimeZone()` or with the C++ TimeZone API, + * `TimeZone::adoptDefault(TimeZone*)`. + * + * If the host operating system configuration has changed since ICU has + * initialized then the returned value can be different than the ICU default + * time zone, even if the default has not changed. + * + *

This function is not thread safe.

+ * + * @param result A buffer to receive the result, or NULL + * @param resultCapacity The capacity of the result buffer + * @param ec input/output error code + * @return The result string length, not including the terminating + * null + * + * @see #UCAL_UNKNOWN_ZONE_ID + * + * @stable ICU 65 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getHostTimeZone(UChar *result, int32_t resultCapacity, UErrorCode *ec); + +/** + * Return the amount of time in milliseconds that the clock is + * advanced during daylight savings time for the given time zone, or + * zero if the time zone does not observe daylight savings time. + * + * @param zoneID null-terminated time zone ID + * + * @param ec input/output error code + * + * @return the number of milliseconds the time is advanced with + * respect to standard time when the daylight savings rules are in + * effect. This is always a non-negative number, most commonly either + * 3,600,000 (one hour) or zero. + * + * @stable ICU 2.6 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getDSTSavings(const UChar* zoneID, UErrorCode* ec); + +/** + * Get the current date and time. + * The value returned is represented as milliseconds from the epoch. + * @return The current date and time. + * @stable ICU 2.0 + */ +U_CAPI UDate U_EXPORT2 +ucal_getNow(void); + +/** + * Open a UCalendar. + * A UCalendar may be used to convert a millisecond value to a year, + * month, and day. + *

+ * Note: When unknown TimeZone ID is specified or if the TimeZone ID specified is "Etc/Unknown", + * the UCalendar returned by the function is initialized with GMT zone with TimeZone ID + * UCAL_UNKNOWN_ZONE_ID ("Etc/Unknown") without any errors/warnings. If you want + * to check if a TimeZone ID is valid prior to this function, use ucal_getCanonicalTimeZoneID. + * + * @param zoneID The desired TimeZone ID. If 0, use the default time zone. + * @param len The length of zoneID, or -1 if null-terminated. + * @param locale The desired locale + * @param type The type of UCalendar to open. This can be UCAL_GREGORIAN to open the Gregorian + * calendar for the locale, or UCAL_DEFAULT to open the default calendar for the locale (the + * default calendar may also be Gregorian). To open a specific non-Gregorian calendar for the + * locale, use uloc_setKeywordValue to set the value of the calendar keyword for the locale + * and then pass the locale to ucal_open with UCAL_DEFAULT as the type. + * @param status A pointer to an UErrorCode to receive any errors + * @return A pointer to a UCalendar, or 0 if an error occurred. + * @see #UCAL_UNKNOWN_ZONE_ID + * @stable ICU 2.0 + */ +U_CAPI UCalendar* U_EXPORT2 +ucal_open(const UChar* zoneID, + int32_t len, + const char* locale, + UCalendarType type, + UErrorCode* status); + +/** + * Close a UCalendar. + * Once closed, a UCalendar may no longer be used. + * @param cal The UCalendar to close. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_close(UCalendar *cal); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUCalendarPointer + * "Smart pointer" class, closes a UCalendar via ucal_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUCalendarPointer, UCalendar, ucal_close); + +U_NAMESPACE_END + +#endif + +/** + * Open a copy of a UCalendar. + * This function performs a deep copy. + * @param cal The calendar to copy + * @param status A pointer to an UErrorCode to receive any errors. + * @return A pointer to a UCalendar identical to cal. + * @stable ICU 4.0 + */ +U_CAPI UCalendar* U_EXPORT2 +ucal_clone(const UCalendar* cal, + UErrorCode* status); + +/** + * Set the TimeZone used by a UCalendar. + * A UCalendar uses a timezone for converting from Greenwich time to local time. + * @param cal The UCalendar to set. + * @param zoneID The desired TimeZone ID. If 0, use the default time zone. + * @param len The length of zoneID, or -1 if null-terminated. + * @param status A pointer to an UErrorCode to receive any errors. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_setTimeZone(UCalendar* cal, + const UChar* zoneID, + int32_t len, + UErrorCode* status); + +/** + * Get the ID of the UCalendar's time zone. + * + * @param cal The UCalendar to query. + * @param result Receives the UCalendar's time zone ID. + * @param resultLength The maximum size of result. + * @param status Receives the status. + * @return The total buffer size needed; if greater than resultLength, the output was truncated. + * @stable ICU 51 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getTimeZoneID(const UCalendar *cal, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** + * Possible formats for a UCalendar's display name + * @stable ICU 2.0 + */ +enum UCalendarDisplayNameType { + /** Standard display name */ + UCAL_STANDARD, + /** Short standard display name */ + UCAL_SHORT_STANDARD, + /** Daylight savings display name */ + UCAL_DST, + /** Short daylight savings display name */ + UCAL_SHORT_DST +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarDisplayNameType UCalendarDisplayNameType; + +/** + * Get the display name for a UCalendar's TimeZone. + * A display name is suitable for presentation to a user. + * @param cal The UCalendar to query. + * @param type The desired display name format; one of UCAL_STANDARD, UCAL_SHORT_STANDARD, + * UCAL_DST, UCAL_SHORT_DST + * @param locale The desired locale for the display name. + * @param result A pointer to a buffer to receive the formatted number. + * @param resultLength The maximum size of result. + * @param status A pointer to an UErrorCode to receive any errors + * @return The total buffer size needed; if greater than resultLength, the output was truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getTimeZoneDisplayName(const UCalendar* cal, + UCalendarDisplayNameType type, + const char* locale, + UChar* result, + int32_t resultLength, + UErrorCode* status); + +/** + * Determine if a UCalendar is currently in daylight savings time. + * Daylight savings time is not used in all parts of the world. + * @param cal The UCalendar to query. + * @param status A pointer to an UErrorCode to receive any errors + * @return true if cal is currently in daylight savings time, false otherwise + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucal_inDaylightTime(const UCalendar* cal, + UErrorCode* status ); + +/** + * Sets the GregorianCalendar change date. This is the point when the switch from + * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October + * 15, 1582. Previous to this time and date will be Julian dates. + * + * This function works only for Gregorian calendars. If the UCalendar is not + * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR + * error code is set. + * + * @param cal The calendar object. + * @param date The given Gregorian cutover date. + * @param pErrorCode Pointer to a standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * + * @see GregorianCalendar::setGregorianChange + * @see ucal_getGregorianChange + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ucal_setGregorianChange(UCalendar *cal, UDate date, UErrorCode *pErrorCode); + +/** + * Gets the Gregorian Calendar change date. This is the point when the switch from + * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October + * 15, 1582. Previous to this time and date will be Julian dates. + * + * This function works only for Gregorian calendars. If the UCalendar is not + * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR + * error code is set. + * + * @param cal The calendar object. + * @param pErrorCode Pointer to a standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return The Gregorian cutover time for this calendar. + * + * @see GregorianCalendar::getGregorianChange + * @see ucal_setGregorianChange + * @stable ICU 3.6 + */ +U_CAPI UDate U_EXPORT2 +ucal_getGregorianChange(const UCalendar *cal, UErrorCode *pErrorCode); + +/** + * Types of UCalendar attributes + * @stable ICU 2.0 + */ +enum UCalendarAttribute { + /** + * Lenient parsing + * @stable ICU 2.0 + */ + UCAL_LENIENT, + /** + * First day of week + * @stable ICU 2.0 + */ + UCAL_FIRST_DAY_OF_WEEK, + /** + * Minimum number of days in first week + * @stable ICU 2.0 + */ + UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, + /** + * The behavior for handling wall time repeating multiple times + * at negative time zone offset transitions + * @stable ICU 49 + */ + UCAL_REPEATED_WALL_TIME, + /** + * The behavior for handling skipped wall time at positive time + * zone offset transitions. + * @stable ICU 49 + */ + UCAL_SKIPPED_WALL_TIME +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarAttribute UCalendarAttribute; + +/** + * Options for handling ambiguous wall time at time zone + * offset transitions. + * @stable ICU 49 + */ +enum UCalendarWallTimeOption { + /** + * An ambiguous wall time to be interpreted as the latest. + * This option is valid for UCAL_REPEATED_WALL_TIME and + * UCAL_SKIPPED_WALL_TIME. + * @stable ICU 49 + */ + UCAL_WALLTIME_LAST, + /** + * An ambiguous wall time to be interpreted as the earliest. + * This option is valid for UCAL_REPEATED_WALL_TIME and + * UCAL_SKIPPED_WALL_TIME. + * @stable ICU 49 + */ + UCAL_WALLTIME_FIRST, + /** + * An ambiguous wall time to be interpreted as the next valid + * wall time. This option is valid for UCAL_SKIPPED_WALL_TIME. + * @stable ICU 49 + */ + UCAL_WALLTIME_NEXT_VALID +}; +/** @stable ICU 49 */ +typedef enum UCalendarWallTimeOption UCalendarWallTimeOption; + +/** + * Get a numeric attribute associated with a UCalendar. + * Numeric attributes include the first day of the week, or the minimal numbers + * of days in the first week of the month. + * @param cal The UCalendar to query. + * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK, + * UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME + * @return The value of attr. + * @see ucal_setAttribute + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getAttribute(const UCalendar* cal, + UCalendarAttribute attr); + +/** + * Set a numeric attribute associated with a UCalendar. + * Numeric attributes include the first day of the week, or the minimal numbers + * of days in the first week of the month. + * @param cal The UCalendar to set. + * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK, + * UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME + * @param newValue The new value of attr. + * @see ucal_getAttribute + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_setAttribute(UCalendar* cal, + UCalendarAttribute attr, + int32_t newValue); + +/** + * Get a locale for which calendars are available. + * A UCalendar in a locale returned by this function will contain the correct + * day and month names for the locale. + * @param localeIndex The index of the desired locale. + * @return A locale for which calendars are available, or 0 if none. + * @see ucal_countAvailable + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +ucal_getAvailable(int32_t localeIndex); + +/** + * Determine how many locales have calendars available. + * This function is most useful as determining the loop ending condition for + * calls to \ref ucal_getAvailable. + * @return The number of locales for which calendars are available. + * @see ucal_getAvailable + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_countAvailable(void); + +/** + * Get a UCalendar's current time in millis. + * The time is represented as milliseconds from the epoch. + * @param cal The UCalendar to query. + * @param status A pointer to an UErrorCode to receive any errors + * @return The calendar's current time in millis. + * @see ucal_setMillis + * @see ucal_setDate + * @see ucal_setDateTime + * @stable ICU 2.0 + */ +U_CAPI UDate U_EXPORT2 +ucal_getMillis(const UCalendar* cal, + UErrorCode* status); + +/** + * Set a UCalendar's current time in millis. + * The time is represented as milliseconds from the epoch. + * @param cal The UCalendar to set. + * @param dateTime The desired date and time. + * @param status A pointer to an UErrorCode to receive any errors + * @see ucal_getMillis + * @see ucal_setDate + * @see ucal_setDateTime + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_setMillis(UCalendar* cal, + UDate dateTime, + UErrorCode* status ); + +/** + * Set a UCalendar's current date. + * The date is represented as a series of 32-bit integers. + * @param cal The UCalendar to set. + * @param year The desired year. + * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY, + * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER + * @param date The desired day of the month. + * @param status A pointer to an UErrorCode to receive any errors + * @see ucal_getMillis + * @see ucal_setMillis + * @see ucal_setDateTime + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_setDate(UCalendar* cal, + int32_t year, + int32_t month, + int32_t date, + UErrorCode* status); + +/** + * Set a UCalendar's current date. + * The date is represented as a series of 32-bit integers. + * @param cal The UCalendar to set. + * @param year The desired year. + * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY, + * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER + * @param date The desired day of the month. + * @param hour The desired hour of day. + * @param minute The desired minute. + * @param second The desirec second. + * @param status A pointer to an UErrorCode to receive any errors + * @see ucal_getMillis + * @see ucal_setMillis + * @see ucal_setDate + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_setDateTime(UCalendar* cal, + int32_t year, + int32_t month, + int32_t date, + int32_t hour, + int32_t minute, + int32_t second, + UErrorCode* status); + +/** + * Returns true if two UCalendars are equivalent. Equivalent + * UCalendars will behave identically, but they may be set to + * different times. + * @param cal1 The first of the UCalendars to compare. + * @param cal2 The second of the UCalendars to compare. + * @return true if cal1 and cal2 are equivalent, false otherwise. + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucal_equivalentTo(const UCalendar* cal1, + const UCalendar* cal2); + +/** + * Add a specified signed amount to a particular field in a UCalendar. + * This can modify more significant fields in the calendar. + * Adding a positive value always means moving forward in time, so for the Gregorian calendar, + * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces + * the numeric value of the field itself). + * @param cal The UCalendar to which to add. + * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param amount The signed amount to add to field. If the amount causes the value + * to exceed to maximum or minimum values for that field, other fields are modified + * to preserve the magnitude of the change. + * @param status A pointer to an UErrorCode to receive any errors + * @see ucal_roll + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_add(UCalendar* cal, + UCalendarDateFields field, + int32_t amount, + UErrorCode* status); + +/** + * Add a specified signed amount to a particular field in a UCalendar. + * This will not modify more significant fields in the calendar. + * Rolling by a positive value always means moving forward in time (unless the limit of the + * field is reached, in which case it may pin or wrap), so for Gregorian calendar, + * starting with 100 BC and rolling the year by +1 results in 99 BC. + * When eras have a definite beginning and end (as in the Chinese calendar, or as in most eras in the + * Japanese calendar) then rolling the year past either limit of the era will cause the year to wrap around. + * When eras only have a limit at one end, then attempting to roll the year past that limit will result in + * pinning the year at that limit. Note that for most calendars in which era 0 years move forward in time + * (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to result in negative years for + * era 0 (that is the only way to represent years before the calendar epoch). + * @param cal The UCalendar to which to add. + * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param amount The signed amount to add to field. If the amount causes the value + * to exceed to maximum or minimum values for that field, the field is pinned to a permissible + * value. + * @param status A pointer to an UErrorCode to receive any errors + * @see ucal_add + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_roll(UCalendar* cal, + UCalendarDateFields field, + int32_t amount, + UErrorCode* status); + +/** + * Get the current value of a field from a UCalendar. + * All fields are represented as 32-bit integers. + * @param cal The UCalendar to query. + * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param status A pointer to an UErrorCode to receive any errors + * @return The value of the desired field. + * @see ucal_set + * @see ucal_isSet + * @see ucal_clearField + * @see ucal_clear + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_get(const UCalendar* cal, + UCalendarDateFields field, + UErrorCode* status ); + +/** + * Set the value of a field in a UCalendar. + * All fields are represented as 32-bit integers. + * @param cal The UCalendar to set. + * @param field The field to set; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param value The desired value of field. + * @see ucal_get + * @see ucal_isSet + * @see ucal_clearField + * @see ucal_clear + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_set(UCalendar* cal, + UCalendarDateFields field, + int32_t value); + +/** + * Determine if a field in a UCalendar is set. + * All fields are represented as 32-bit integers. + * @param cal The UCalendar to query. + * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @return true if field is set, false otherwise. + * @see ucal_get + * @see ucal_set + * @see ucal_clearField + * @see ucal_clear + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucal_isSet(const UCalendar* cal, + UCalendarDateFields field); + +/** + * Clear a field in a UCalendar. + * All fields are represented as 32-bit integers. + * @param cal The UCalendar containing the field to clear. + * @param field The field to clear; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @see ucal_get + * @see ucal_set + * @see ucal_isSet + * @see ucal_clear + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_clearField(UCalendar* cal, + UCalendarDateFields field); + +/** + * Clear all fields in a UCalendar. + * All fields are represented as 32-bit integers. + * @param calendar The UCalendar to clear. + * @see ucal_get + * @see ucal_set + * @see ucal_isSet + * @see ucal_clearField + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucal_clear(UCalendar* calendar); + +/** + * Possible limit values for a UCalendar + * @stable ICU 2.0 + */ +enum UCalendarLimitType { + /** Minimum value */ + UCAL_MINIMUM, + /** Maximum value */ + UCAL_MAXIMUM, + /** Greatest minimum value */ + UCAL_GREATEST_MINIMUM, + /** Least maximum value */ + UCAL_LEAST_MAXIMUM, + /** Actual minimum value */ + UCAL_ACTUAL_MINIMUM, + /** Actual maximum value */ + UCAL_ACTUAL_MAXIMUM +}; + +/** @stable ICU 2.0 */ +typedef enum UCalendarLimitType UCalendarLimitType; + +/** + * Determine a limit for a field in a UCalendar. + * A limit is a maximum or minimum value for a field. + * @param cal The UCalendar to query. + * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param type The desired critical point; one of UCAL_MINIMUM, UCAL_MAXIMUM, UCAL_GREATEST_MINIMUM, + * UCAL_LEAST_MAXIMUM, UCAL_ACTUAL_MINIMUM, UCAL_ACTUAL_MAXIMUM + * @param status A pointer to an UErrorCode to receive any errors. + * @return The requested value. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getLimit(const UCalendar* cal, + UCalendarDateFields field, + UCalendarLimitType type, + UErrorCode* status); + +/** Get the locale for this calendar object. You can choose between valid and actual locale. + * @param cal The calendar object + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale name + * @stable ICU 2.8 + */ +U_CAPI const char * U_EXPORT2 +ucal_getLocaleByType(const UCalendar *cal, ULocDataLocaleType type, UErrorCode* status); + +/** + * Returns the timezone data version currently used by ICU. + * @param status error code for the operation + * @return the version string, such as "2007f" + * @stable ICU 3.8 + */ +U_CAPI const char * U_EXPORT2 +ucal_getTZDataVersion(UErrorCode* status); + +/** + * Returns the canonical system timezone ID or the normalized + * custom time zone ID for the given time zone ID. + * @param id The input timezone ID to be canonicalized. + * @param len The length of id, or -1 if null-terminated. + * @param result The buffer receives the canonical system timezone ID + * or the custom timezone ID in normalized format. + * @param resultCapacity The capacity of the result buffer. + * @param isSystemID Receives if the given ID is a known system + * timezone ID. + * @param status Receives the status. When the given timezone ID + * is neither a known system time zone ID nor a + * valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR + * is set. + * @return The result string length, not including the terminating + * null. + * @stable ICU 4.0 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getCanonicalTimeZoneID(const UChar* id, int32_t len, + UChar* result, int32_t resultCapacity, UBool *isSystemID, UErrorCode* status); +/** + * Get the resource keyword value string designating the calendar type for the UCalendar. + * @param cal The UCalendar to query. + * @param status The error code for the operation. + * @return The resource keyword value string. + * @stable ICU 4.2 + */ +U_CAPI const char * U_EXPORT2 +ucal_getType(const UCalendar *cal, UErrorCode* status); + +/** + * Given a key and a locale, returns an array of string values in a preferred + * order that would make a difference. These are all and only those values where + * the open (creation) of the service with the locale formed from the input locale + * plus input keyword and that value has different behavior than creation with the + * input locale alone. + * @param key one of the keys supported by this service. For now, only + * "calendar" is supported. + * @param locale the locale + * @param commonlyUsed if set to true it will return only commonly used values + * with the given locale in preferred order. Otherwise, + * it will return all the available values for the locale. + * @param status error status + * @return a string enumeration over keyword values for the given key and the locale. + * @stable ICU 4.2 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucal_getKeywordValuesForLocale(const char* key, + const char* locale, + UBool commonlyUsed, + UErrorCode* status); + + +/** Weekday types, as returned by ucal_getDayOfWeekType(). + * @stable ICU 4.4 + */ +enum UCalendarWeekdayType { + /** + * Designates a full weekday (no part of the day is included in the weekend). + * @stable ICU 4.4 + */ + UCAL_WEEKDAY, + /** + * Designates a full weekend day (the entire day is included in the weekend). + * @stable ICU 4.4 + */ + UCAL_WEEKEND, + /** + * Designates a day that starts as a weekday and transitions to the weekend. + * Call ucal_getWeekendTransition() to get the time of transition. + * @stable ICU 4.4 + */ + UCAL_WEEKEND_ONSET, + /** + * Designates a day that starts as the weekend and transitions to a weekday. + * Call ucal_getWeekendTransition() to get the time of transition. + * @stable ICU 4.4 + */ + UCAL_WEEKEND_CEASE +}; + +/** @stable ICU 4.4 */ +typedef enum UCalendarWeekdayType UCalendarWeekdayType; + +/** + * Returns whether the given day of the week is a weekday, a weekend day, + * or a day that transitions from one to the other, for the locale and + * calendar system associated with this UCalendar (the locale's region is + * often the most determinant factor). If a transition occurs at midnight, + * then the days before and after the transition will have the + * type UCAL_WEEKDAY or UCAL_WEEKEND. If a transition occurs at a time + * other than midnight, then the day of the transition will have + * the type UCAL_WEEKEND_ONSET or UCAL_WEEKEND_CEASE. In this case, the + * function ucal_getWeekendTransition() will return the point of + * transition. + * @param cal The UCalendar to query. + * @param dayOfWeek The day of the week whose type is desired (UCAL_SUNDAY..UCAL_SATURDAY). + * @param status The error code for the operation. + * @return The UCalendarWeekdayType for the day of the week. + * @stable ICU 4.4 + */ +U_CAPI UCalendarWeekdayType U_EXPORT2 +ucal_getDayOfWeekType(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode* status); + +/** + * Returns the time during the day at which the weekend begins or ends in + * this calendar system. If ucal_getDayOfWeekType() returns UCAL_WEEKEND_ONSET + * for the specified dayOfWeek, return the time at which the weekend begins. + * If ucal_getDayOfWeekType() returns UCAL_WEEKEND_CEASE for the specified dayOfWeek, + * return the time at which the weekend ends. If ucal_getDayOfWeekType() returns + * some other UCalendarWeekdayType for the specified dayOfWeek, is it an error condition + * (U_ILLEGAL_ARGUMENT_ERROR). + * @param cal The UCalendar to query. + * @param dayOfWeek The day of the week for which the weekend transition time is + * desired (UCAL_SUNDAY..UCAL_SATURDAY). + * @param status The error code for the operation. + * @return The milliseconds after midnight at which the weekend begins or ends. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getWeekendTransition(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode *status); + +/** + * Returns true if the given UDate is in the weekend in + * this calendar system. + * @param cal The UCalendar to query. + * @param date The UDate in question. + * @param status The error code for the operation. + * @return true if the given UDate is in the weekend in + * this calendar system, false otherwise. + * @stable ICU 4.4 + */ +U_CAPI UBool U_EXPORT2 +ucal_isWeekend(const UCalendar *cal, UDate date, UErrorCode *status); + +/** + * Return the difference between the target time and the time this calendar object is currently set to. + * If the target time is after the current calendar setting, the the returned value will be positive. + * The field parameter specifies the units of the return value. For example, if field is UCAL_MONTH + * and ucal_getFieldDifference returns 3, then the target time is 3 to less than 4 months after the + * current calendar setting. + * + * As a side effect of this call, this calendar is advanced toward target by the given amount. That is, + * calling this function has the side effect of calling ucal_add on this calendar with the specified + * field and an amount equal to the return value from this function. + * + * A typical way of using this function is to call it first with the largest field of interest, then + * with progressively smaller fields. + * + * @param cal The UCalendar to compare and update. + * @param target The target date to compare to the current calendar setting. + * @param field The field to compare; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, + * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, + * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, + * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. + * @param status A pointer to an UErrorCode to receive any errors + * @return The date difference for the specified field. + * @stable ICU 4.8 + */ +U_CAPI int32_t U_EXPORT2 +ucal_getFieldDifference(UCalendar* cal, + UDate target, + UCalendarDateFields field, + UErrorCode* status); + +/** + * Time zone transition types for ucal_getTimeZoneTransitionDate + * @stable ICU 50 + */ +enum UTimeZoneTransitionType { + /** + * Get the next transition after the current date, + * i.e. excludes the current date + * @stable ICU 50 + */ + UCAL_TZ_TRANSITION_NEXT, + /** + * Get the next transition on or after the current date, + * i.e. may include the current date + * @stable ICU 50 + */ + UCAL_TZ_TRANSITION_NEXT_INCLUSIVE, + /** + * Get the previous transition before the current date, + * i.e. excludes the current date + * @stable ICU 50 + */ + UCAL_TZ_TRANSITION_PREVIOUS, + /** + * Get the previous transition on or before the current date, + * i.e. may include the current date + * @stable ICU 50 + */ + UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE +}; + +typedef enum UTimeZoneTransitionType UTimeZoneTransitionType; /**< @stable ICU 50 */ + +/** +* Get the UDate for the next/previous time zone transition relative to +* the calendar's current date, in the time zone to which the calendar +* is currently set. If there is no known time zone transition of the +* requested type relative to the calendar's date, the function returns +* false. +* @param cal The UCalendar to query. +* @param type The type of transition desired. +* @param transition A pointer to a UDate to be set to the transition time. +* If the function returns false, the value set is unspecified. +* @param status A pointer to a UErrorCode to receive any errors. +* @return true if a valid transition time is set in *transition, false +* otherwise. +* @stable ICU 50 +*/ +U_CAPI UBool U_EXPORT2 +ucal_getTimeZoneTransitionDate(const UCalendar* cal, UTimeZoneTransitionType type, + UDate* transition, UErrorCode* status); + +/** +* Converts a system time zone ID to an equivalent Windows time zone ID. For example, +* Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles". +* +*

There are system time zones that cannot be mapped to Windows zones. When the input +* system time zone ID is unknown or unmappable to a Windows time zone, then this +* function returns 0 as the result length, but the operation itself remains successful +* (no error status set on return). +* +*

This implementation utilizes +* Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, +* please read the ICU user guide section +* Updating the Time Zone Data. +* +* @param id A system time zone ID. +* @param len The length of id, or -1 if null-terminated. +* @param winid A buffer to receive a Windows time zone ID. +* @param winidCapacity The capacity of the result buffer winid. +* @param status Receives the status. +* @return The result string length, not including the terminating null. +* @see ucal_getTimeZoneIDForWindowsID +* +* @stable ICU 52 +*/ +U_CAPI int32_t U_EXPORT2 +ucal_getWindowsTimeZoneID(const UChar* id, int32_t len, + UChar* winid, int32_t winidCapacity, UErrorCode* status); + +/** +* Converts a Windows time zone ID to an equivalent system time zone ID +* for a region. For example, system time zone ID "America/Los_Angeles" is returned +* for input Windows ID "Pacific Standard Time" and region "US" (or null), +* "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and +* region "CA". +* +*

Not all Windows time zones can be mapped to system time zones. When the input +* Windows time zone ID is unknown or unmappable to a system time zone, then this +* function returns 0 as the result length, but the operation itself remains successful +* (no error status set on return). +* +*

This implementation utilizes +* Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, +* please read the ICU user guide section +* Updating the Time Zone Data. +* +* @param winid A Windows time zone ID. +* @param len The length of winid, or -1 if null-terminated. +* @param region A null-terminated region code, or NULL if no regional preference. +* @param id A buffer to receive a system time zone ID. +* @param idCapacity The capacity of the result buffer id. +* @param status Receives the status. +* @return The result string length, not including the terminating null. +* @see ucal_getWindowsTimeZoneID +* +* @stable ICU 52 +*/ +U_CAPI int32_t U_EXPORT2 +ucal_getTimeZoneIDForWindowsID(const UChar* winid, int32_t len, const char* region, + UChar* id, int32_t idCapacity, UErrorCode* status); + +/** + * Options used by ucal_getTimeZoneOffsetFromLocal and BasicTimeZone::getOffsetFromLocal() + * to specify how to interpret an input time when it does not exist, or when it is ambiguous, + * around a time zone transition. + * @stable ICU 69 + */ +enum UTimeZoneLocalOption { + /** + * An input time is always interpreted as local time before + * a time zone transition. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_FORMER = 0x04, + /** + * An input time is always interpreted as local time after + * a time zone transition. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_LATTER = 0x0C, + /** + * An input time is interpreted as standard time when local + * time is switched to/from daylight saving time. When both + * sides of a time zone transition are standard time, + * or daylight saving time, the local time before the + * transition is used. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_STANDARD_FORMER = UCAL_TZ_LOCAL_FORMER | 0x01, + /** + * An input time is interpreted as standard time when local + * time is switched to/from daylight saving time. When both + * sides of a time zone transition are standard time, + * or daylight saving time, the local time after the + * transition is used. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_STANDARD_LATTER = UCAL_TZ_LOCAL_LATTER | 0x01, + /** + * An input time is interpreted as daylight saving time when + * local time is switched to/from standard time. When both + * sides of a time zone transition are standard time, + * or daylight saving time, the local time before the + * transition is used. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_DAYLIGHT_FORMER = UCAL_TZ_LOCAL_FORMER | 0x03, + /** + * An input time is interpreted as daylight saving time when + * local time is switched to/from standard time. When both + * sides of a time zone transition are standard time, + * or daylight saving time, the local time after the + * transition is used. + * @stable ICU 69 + */ + UCAL_TZ_LOCAL_DAYLIGHT_LATTER = UCAL_TZ_LOCAL_LATTER | 0x03, +}; +typedef enum UTimeZoneLocalOption UTimeZoneLocalOption; /**< @stable ICU 69 */ + +/** +* Returns the time zone raw and GMT offset for the given moment +* in time. Upon return, local-millis = GMT-millis + rawOffset + +* dstOffset. All computations are performed in the proleptic +* Gregorian calendar. +* +* @param cal The UCalendar which specify the local date and time value to query. +* @param nonExistingTimeOpt The option to indicate how to interpret the date and +* time in the calendar represent a local time that skipped at a positive time +* zone transitions (e.g. when the daylight saving time starts or the time zone +* offset is increased due to a time zone rule change). +* @param duplicatedTimeOpt The option to indicate how to interpret the date and +* time in the calendar represent a local time that repeating multiple times at a +* negative time zone transition (e.g. when the daylight saving time ends or the +* time zone offset is decreased due to a time zone rule change) +* @param rawOffset output parameter to receive the raw offset, that +* is, the offset not including DST adjustments. +* If the status is set to one of the error code, the value set is unspecified. +* @param dstOffset output parameter to receive the DST offset, +* that is, the offset to be added to `rawOffset' to obtain the +* total offset between local and GMT time. If DST is not in +* effect, this value is zero; otherwise it is a positive value, +* typically one hour. +* If the status is set to one of the error code, the value set is unspecified. +* @param status A pointer to a UErrorCode to receive any errors. +* @stable ICU 69 +*/ +U_CAPI void U_EXPORT2 +ucal_getTimeZoneOffsetFromLocal( + const UCalendar* cal, + UTimeZoneLocalOption nonExistingTimeOpt, + UTimeZoneLocalOption duplicatedTimeOpt, + int32_t* rawOffset, int32_t* dstOffset, UErrorCode* status); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucasemap.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucasemap.h new file mode 100644 index 0000000000000000000000000000000000000000..d1c1b483ab337ec83bda8855775eee45d8e940ff --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucasemap.h @@ -0,0 +1,388 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2005-2012, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: ucasemap.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2005may06 +* created by: Markus W. Scherer +* +* Case mapping service object and functions using it. +*/ + +#ifndef __UCASEMAP_H__ +#define __UCASEMAP_H__ + +#include "unicode/utypes.h" +#include "unicode/stringoptions.h" +#include "unicode/ustring.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Unicode case mapping functions using a UCaseMap service object. + * + * The service object takes care of memory allocations, data loading, and setup + * for the attributes, as usual. + * + * Currently, the functionality provided here does not overlap with uchar.h + * and ustring.h, except for ucasemap_toTitle(). + * + * ucasemap_utf8XYZ() functions operate directly on UTF-8 strings. + */ + +/** + * UCaseMap is an opaque service object for newer ICU case mapping functions. + * Older functions did not use a service object. + * @stable ICU 3.4 + */ +struct UCaseMap; +typedef struct UCaseMap UCaseMap; /**< C typedef for struct UCaseMap. @stable ICU 3.4 */ + +/** + * Open a UCaseMap service object for a locale and a set of options. + * The locale ID and options are preprocessed so that functions using the + * service object need not process them in each call. + * + * @param locale ICU locale ID, used for language-dependent + * upper-/lower-/title-casing according to the Unicode standard. + * Usual semantics: ""=root, NULL=default locale, etc. + * @param options Options bit set, used for case folding and string comparisons. + * Same flags as for u_foldCase(), u_strFoldCase(), + * u_strCaseCompare(), etc. + * Use 0 or U_FOLD_CASE_DEFAULT for default behavior. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return Pointer to a UCaseMap service object, if successful. + * + * @see U_FOLD_CASE_DEFAULT + * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I + * @see U_TITLECASE_NO_LOWERCASE + * @see U_TITLECASE_NO_BREAK_ADJUSTMENT + * @stable ICU 3.4 + */ +U_CAPI UCaseMap * U_EXPORT2 +ucasemap_open(const char *locale, uint32_t options, UErrorCode *pErrorCode); + +/** + * Close a UCaseMap service object. + * @param csm Object to be closed. + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ucasemap_close(UCaseMap *csm); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUCaseMapPointer + * "Smart pointer" class, closes a UCaseMap via ucasemap_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUCaseMapPointer, UCaseMap, ucasemap_close); + +U_NAMESPACE_END + +#endif + +/** + * Get the locale ID that is used for language-dependent case mappings. + * @param csm UCaseMap service object. + * @return locale ID + * @stable ICU 3.4 + */ +U_CAPI const char * U_EXPORT2 +ucasemap_getLocale(const UCaseMap *csm); + +/** + * Get the options bit set that is used for case folding and string comparisons. + * @param csm UCaseMap service object. + * @return options bit set + * @stable ICU 3.4 + */ +U_CAPI uint32_t U_EXPORT2 +ucasemap_getOptions(const UCaseMap *csm); + +/** + * Set the locale ID that is used for language-dependent case mappings. + * + * @param csm UCaseMap service object. + * @param locale Locale ID, see ucasemap_open(). + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * + * @see ucasemap_open + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ucasemap_setLocale(UCaseMap *csm, const char *locale, UErrorCode *pErrorCode); + +/** + * Set the options bit set that is used for case folding and string comparisons. + * + * @param csm UCaseMap service object. + * @param options Options bit set, see ucasemap_open(). + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * + * @see ucasemap_open + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ucasemap_setOptions(UCaseMap *csm, uint32_t options, UErrorCode *pErrorCode); + +#if !UCONFIG_NO_BREAK_ITERATION + +/** + * Get the break iterator that is used for titlecasing. + * Do not modify the returned break iterator. + * @param csm UCaseMap service object. + * @return titlecasing break iterator + * @stable ICU 3.8 + */ +U_CAPI const UBreakIterator * U_EXPORT2 +ucasemap_getBreakIterator(const UCaseMap *csm); + +/** + * Set the break iterator that is used for titlecasing. + * The UCaseMap service object releases a previously set break iterator + * and "adopts" this new one, taking ownership of it. + * It will be released in a subsequent call to ucasemap_setBreakIterator() + * or ucasemap_close(). + * + * Break iterator operations are not thread-safe. Therefore, titlecasing + * functions use non-const UCaseMap objects. It is not possible to titlecase + * strings concurrently using the same UCaseMap. + * + * @param csm UCaseMap service object. + * @param iterToAdopt Break iterator to be adopted for titlecasing. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * + * @see ucasemap_toTitle + * @see ucasemap_utf8ToTitle + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +ucasemap_setBreakIterator(UCaseMap *csm, UBreakIterator *iterToAdopt, UErrorCode *pErrorCode); + +/** + * Titlecase a UTF-16 string. This function is almost a duplicate of u_strToTitle(), + * except that it takes ucasemap_setOptions() into account and has performance + * advantages from being able to use a UCaseMap object for multiple case mapping + * operations, saving setup time. + * + * Casing is locale-dependent and context-sensitive. + * Titlecasing uses a break iterator to find the first characters of words + * that are to be titlecased. It titlecases those characters and lowercases + * all others. (This can be modified with ucasemap_setOptions().) + * + * Note: This function takes a non-const UCaseMap pointer because it will + * open a default break iterator if no break iterator was set yet, + * and effectively call ucasemap_setBreakIterator(); + * also because the break iterator is stateful and will be modified during + * the iteration. + * + * The titlecase break iterator can be provided to customize for arbitrary + * styles, using rules and dictionaries beyond the standard iterators. + * The standard titlecase iterator for the root locale implements the + * algorithm of Unicode TR 21. + * + * This function uses only the setText(), first() and next() methods of the + * provided break iterator. + * + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param csm UCaseMap service object. This pointer is non-const! + * See the note above for details. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of UChars). If it is 0, then + * dest may be NULL and the function will only return the length of the result + * without writing any of the result string. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * + * @see u_strToTitle + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +ucasemap_toTitle(UCaseMap *csm, + UChar *dest, int32_t destCapacity, + const UChar *src, int32_t srcLength, + UErrorCode *pErrorCode); + +#endif // UCONFIG_NO_BREAK_ITERATION + +/** + * Lowercase the characters in a UTF-8 string. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param csm UCaseMap service object. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be NULL and the function will only return the length of the result + * without writing any of the result string. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * + * @see u_strToLower + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ucasemap_utf8ToLower(const UCaseMap *csm, + char *dest, int32_t destCapacity, + const char *src, int32_t srcLength, + UErrorCode *pErrorCode); + +/** + * Uppercase the characters in a UTF-8 string. + * Casing is locale-dependent and context-sensitive. + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param csm UCaseMap service object. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be NULL and the function will only return the length of the result + * without writing any of the result string. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * + * @see u_strToUpper + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ucasemap_utf8ToUpper(const UCaseMap *csm, + char *dest, int32_t destCapacity, + const char *src, int32_t srcLength, + UErrorCode *pErrorCode); + +#if !UCONFIG_NO_BREAK_ITERATION + +/** + * Titlecase a UTF-8 string. + * Casing is locale-dependent and context-sensitive. + * Titlecasing uses a break iterator to find the first characters of words + * that are to be titlecased. It titlecases those characters and lowercases + * all others. (This can be modified with ucasemap_setOptions().) + * + * Note: This function takes a non-const UCaseMap pointer because it will + * open a default break iterator if no break iterator was set yet, + * and effectively call ucasemap_setBreakIterator(); + * also because the break iterator is stateful and will be modified during + * the iteration. + * + * The titlecase break iterator can be provided to customize for arbitrary + * styles, using rules and dictionaries beyond the standard iterators. + * The standard titlecase iterator for the root locale implements the + * algorithm of Unicode TR 21. + * + * This function uses only the setUText(), first(), next() and close() methods of the + * provided break iterator. + * + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param csm UCaseMap service object. This pointer is non-const! + * See the note above for details. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be NULL and the function will only return the length of the result + * without writing any of the result string. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * + * @see u_strToTitle + * @see U_TITLECASE_NO_LOWERCASE + * @see U_TITLECASE_NO_BREAK_ADJUSTMENT + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +ucasemap_utf8ToTitle(UCaseMap *csm, + char *dest, int32_t destCapacity, + const char *src, int32_t srcLength, + UErrorCode *pErrorCode); + +#endif + +/** + * Case-folds the characters in a UTF-8 string. + * + * Case-folding is locale-independent and not context-sensitive, + * but there is an option for whether to include or exclude mappings for dotted I + * and dotless i that are marked with 'T' in CaseFolding.txt. + * + * The result may be longer or shorter than the original. + * The source string and the destination buffer must not overlap. + * + * @param csm UCaseMap service object. + * @param dest A buffer for the result string. The result will be NUL-terminated if + * the buffer is large enough. + * The contents is undefined in case of failure. + * @param destCapacity The size of the buffer (number of bytes). If it is 0, then + * dest may be NULL and the function will only return the length of the result + * without writing any of the result string. + * @param src The original string. + * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * + * @see u_strFoldCase + * @see ucasemap_setOptions + * @see U_FOLD_CASE_DEFAULT + * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +ucasemap_utf8FoldCase(const UCaseMap *csm, + char *dest, int32_t destCapacity, + const char *src, int32_t srcLength, + UErrorCode *pErrorCode); + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucat.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucat.h new file mode 100644 index 0000000000000000000000000000000000000000..93850348fff318448ccaff3f451fa6ec724463a8 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucat.h @@ -0,0 +1,160 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2003-2004, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* Author: Alan Liu +* Created: March 19 2003 +* Since: ICU 2.6 +********************************************************************** +*/ +#ifndef UCAT_H +#define UCAT_H + +#include "unicode/utypes.h" +#include "unicode/ures.h" + +/** + * \file + * \brief C API: Message Catalog Wrappers + * + * This C API provides look-alike functions that deliberately resemble + * the POSIX catopen, catclose, and catgets functions. The underlying + * implementation is in terms of ICU resource bundles, rather than + * POSIX message catalogs. + * + * The ICU resource bundles obey standard ICU inheritance policies. + * To facilitate this, sets and messages are flattened into one tier. + * This is done by creating resource bundle keys of the form + * <set_num>%<msg_num> where set_num is the set number and msg_num is + * the message number, formatted as decimal strings. + * + * Example: Consider a message catalog containing two sets: + * + * Set 1: Message 4 = "Good morning." + * Message 5 = "Good afternoon." + * Message 7 = "Good evening." + * Message 8 = "Good night." + * Set 4: Message 14 = "Please " + * Message 19 = "Thank you." + * Message 20 = "Sincerely," + * + * The ICU resource bundle source file would, assuming it is named + * "greet.txt", would look like this: + * + * greet + * { + * 1%4 { "Good morning." } + * 1%5 { "Good afternoon." } + * 1%7 { "Good evening." } + * 1%8 { "Good night." } + * + * 4%14 { "Please " } + * 4%19 { "Thank you." } + * 4%20 { "Sincerely," } + * } + * + * The catgets function is commonly used in combination with functions + * like printf and strftime. ICU components like message format can + * be used instead, although they use a different format syntax. + * There is an ICU package, icuio, that provides some of + * the POSIX-style formatting API. + */ + +U_CDECL_BEGIN + +/** + * An ICU message catalog descriptor, analogous to nl_catd. + * + * @stable ICU 2.6 + */ +typedef UResourceBundle* u_nl_catd; + +/** + * Open and return an ICU message catalog descriptor. The descriptor + * may be passed to u_catgets() to retrieve localized strings. + * + * @param name string containing the full path pointing to the + * directory where the resources reside followed by the package name + * e.g. "/usr/resource/my_app/resources/guimessages" on a Unix system. + * If NULL, ICU default data files will be used. + * + * Unlike POSIX, environment variables are not interpolated within the + * name. + * + * @param locale the locale for which we want to open the resource. If + * NULL, the default ICU locale will be used (see uloc_getDefault). If + * strlen(locale) == 0, the root locale will be used. + * + * @param ec input/output error code. Upon output, + * U_USING_FALLBACK_WARNING indicates that a fallback locale was + * used. For example, 'de_CH' was requested, but nothing was found + * there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that the + * default locale data or root locale data was used; neither the + * requested locale nor any of its fallback locales were found. + * + * @return a message catalog descriptor that may be passed to + * u_catgets(). If the ec parameter indicates success, then the caller + * is responsible for calling u_catclose() to close the message + * catalog. If the ec parameter indicates failure, then NULL will be + * returned. + * + * @stable ICU 2.6 + */ +U_CAPI u_nl_catd U_EXPORT2 +u_catopen(const char* name, const char* locale, UErrorCode* ec); + +/** + * Close an ICU message catalog, given its descriptor. + * + * @param catd a message catalog descriptor to be closed. May be NULL, + * in which case no action is taken. + * + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +u_catclose(u_nl_catd catd); + +/** + * Retrieve a localized string from an ICU message catalog. + * + * @param catd a message catalog descriptor returned by u_catopen. + * + * @param set_num the message catalog set number. Sets need not be + * numbered consecutively. + * + * @param msg_num the message catalog message number within the + * set. Messages need not be numbered consecutively. + * + * @param s the default string. This is returned if the string + * specified by the set_num and msg_num is not found. It must be + * zero-terminated. + * + * @param len fill-in parameter to receive the length of the result. + * May be NULL, in which case it is ignored. + * + * @param ec input/output error code. May be U_USING_FALLBACK_WARNING + * or U_USING_DEFAULT_WARNING. U_MISSING_RESOURCE_ERROR indicates that + * the set_num/msg_num tuple does not specify a valid message string + * in this catalog. + * + * @return a pointer to a zero-terminated UChar array which lives in + * an internal buffer area, typically a memory mapped/DLL file. The + * caller must NOT delete this pointer. If the call is unsuccessful + * for any reason, then s is returned. This includes the situation in + * which ec indicates a failing error code upon entry to this + * function. + * + * @stable ICU 2.6 + */ +U_CAPI const UChar* U_EXPORT2 +u_catgets(u_nl_catd catd, int32_t set_num, int32_t msg_num, + const UChar* s, + int32_t* len, UErrorCode* ec); + +U_CDECL_END + +#endif /*UCAT_H*/ +/*eof*/ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchar.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchar.h new file mode 100644 index 0000000000000000000000000000000000000000..4f82a9fb5838dac4e7a4f6c9d53df4dd68931051 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchar.h @@ -0,0 +1,4169 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* +* File UCHAR.H +* +* Modification History: +* +* Date Name Description +* 04/02/97 aliu Creation. +* 03/29/99 helena Updated for C APIs. +* 4/15/99 Madhu Updated for C Implementation and Javadoc +* 5/20/99 Madhu Added the function u_getVersion() +* 8/19/1999 srl Upgraded scripts to Unicode 3.0 +* 8/27/1999 schererm UCharDirection constants: U_... +* 11/11/1999 weiv added u_isalnum(), cleaned comments +* 01/11/2000 helena Renamed u_getVersion to u_getUnicodeVersion(). +****************************************************************************** +*/ + +#ifndef UCHAR_H +#define UCHAR_H + +#include "unicode/utypes.h" +#include "unicode/stringoptions.h" +#include "unicode/ucpmap.h" + +#if !defined(USET_DEFINED) && !defined(U_IN_DOXYGEN) + +#define USET_DEFINED + +/** + * USet is the C API type corresponding to C++ class UnicodeSet. + * It is forward-declared here to avoid including unicode/uset.h file if related + * APIs are not used. + * + * @see ucnv_getUnicodeSet + * @stable ICU 2.4 + */ +typedef struct USet USet; + +#endif + + +U_CDECL_BEGIN + +/*==========================================================================*/ +/* Unicode version number */ +/*==========================================================================*/ +/** + * Unicode version number, default for the current ICU version. + * The actual Unicode Character Database (UCD) data is stored in uprops.dat + * and may be generated from UCD files from a different Unicode version. + * Call u_getUnicodeVersion to get the actual Unicode version of the data. + * + * @see u_getUnicodeVersion + * @stable ICU 2.0 + */ +#define U_UNICODE_VERSION "15.0" + +/** + * \file + * \brief C API: Unicode Properties + * + * This C API provides low-level access to the Unicode Character Database. + * In addition to raw property values, some convenience functions calculate + * derived properties, for example for Java-style programming. + * + * Unicode assigns each code point (not just assigned character) values for + * many properties. + * Most of them are simple boolean flags, or constants from a small enumerated list. + * For some properties, values are strings or other relatively more complex types. + * + * For more information see + * "About the Unicode Character Database" (http://www.unicode.org/ucd/) + * and the ICU User Guide chapter on Properties (https://unicode-org.github.io/icu/userguide/strings/properties). + * + * Many properties are accessible via generic functions that take a UProperty selector. + * - u_hasBinaryProperty() returns a binary value (true/false) per property and code point. + * - u_getIntPropertyValue() returns an integer value per property and code point. + * For each supported enumerated or catalog property, there is + * an enum type for all of the property's values, and + * u_getIntPropertyValue() returns the numeric values of those constants. + * - u_getBinaryPropertySet() returns a set for each ICU-supported binary property with + * all code points for which the property is true. + * - u_getIntPropertyMap() returns a map for each + * ICU-supported enumerated/catalog/int-valued property which + * maps all Unicode code points to their values for that property. + * + * Many functions are designed to match java.lang.Character functions. + * See the individual function documentation, + * and see the JDK 1.4 java.lang.Character documentation + * at http://java.sun.com/j2se/1.4/docs/api/java/lang/Character.html + * + * There are also functions that provide easy migration from C/POSIX functions + * like isblank(). Their use is generally discouraged because the C/POSIX + * standards do not define their semantics beyond the ASCII range, which means + * that different implementations exhibit very different behavior. + * Instead, Unicode properties should be used directly. + * + * There are also only a few, broad C/POSIX character classes, and they tend + * to be used for conflicting purposes. For example, the "isalpha()" class + * is sometimes used to determine word boundaries, while a more sophisticated + * approach would at least distinguish initial letters from continuation + * characters (the latter including combining marks). + * (In ICU, BreakIterator is the most sophisticated API for word boundaries.) + * Another example: There is no "istitle()" class for titlecase characters. + * + * ICU 3.4 and later provides API access for all twelve C/POSIX character classes. + * ICU implements them according to the Standard Recommendations in + * Annex C: Compatibility Properties of UTS #18 Unicode Regular Expressions + * (http://www.unicode.org/reports/tr18/#Compatibility_Properties). + * + * API access for C/POSIX character classes is as follows: + * - alpha: u_isUAlphabetic(c) or u_hasBinaryProperty(c, UCHAR_ALPHABETIC) + * - lower: u_isULowercase(c) or u_hasBinaryProperty(c, UCHAR_LOWERCASE) + * - upper: u_isUUppercase(c) or u_hasBinaryProperty(c, UCHAR_UPPERCASE) + * - punct: u_ispunct(c) + * - digit: u_isdigit(c) or u_charType(c)==U_DECIMAL_DIGIT_NUMBER + * - xdigit: u_isxdigit(c) or u_hasBinaryProperty(c, UCHAR_POSIX_XDIGIT) + * - alnum: u_hasBinaryProperty(c, UCHAR_POSIX_ALNUM) + * - space: u_isUWhiteSpace(c) or u_hasBinaryProperty(c, UCHAR_WHITE_SPACE) + * - blank: u_isblank(c) or u_hasBinaryProperty(c, UCHAR_POSIX_BLANK) + * - cntrl: u_charType(c)==U_CONTROL_CHAR + * - graph: u_hasBinaryProperty(c, UCHAR_POSIX_GRAPH) + * - print: u_hasBinaryProperty(c, UCHAR_POSIX_PRINT) + * + * Note: Some of the u_isxyz() functions in uchar.h predate, and do not match, + * the Standard Recommendations in UTS #18. Instead, they match Java + * functions according to their API documentation. + * + * \htmlonly + * The C/POSIX character classes are also available in UnicodeSet patterns, + * using patterns like [:graph:] or \p{graph}. + * \endhtmlonly + * + * Note: There are several ICU whitespace functions. + * Comparison: + * - u_isUWhiteSpace=UCHAR_WHITE_SPACE: Unicode White_Space property; + * most of general categories "Z" (separators) + most whitespace ISO controls + * (including no-break spaces, but excluding IS1..IS4) + * - u_isWhitespace: Java isWhitespace; Z + whitespace ISO controls but excluding no-break spaces + * - u_isJavaSpaceChar: Java isSpaceChar; just Z (including no-break spaces) + * - u_isspace: Z + whitespace ISO controls (including no-break spaces) + * - u_isblank: "horizontal spaces" = TAB + Zs + */ + +/** + * Constants. + */ + +/** The lowest Unicode code point value. Code points are non-negative. @stable ICU 2.0 */ +#define UCHAR_MIN_VALUE 0 + +/** + * The highest Unicode code point value (scalar value) according to + * The Unicode Standard. This is a 21-bit value (20.1 bits, rounded up). + * For a single character, UChar32 is a simple type that can hold any code point value. + * + * @see UChar32 + * @stable ICU 2.0 + */ +#define UCHAR_MAX_VALUE 0x10ffff + +/** + * Get a single-bit bit set (a flag) from a bit number 0..31. + * @stable ICU 2.1 + */ +#define U_MASK(x) ((uint32_t)1<<(x)) + +/** + * Selection constants for Unicode properties. + * These constants are used in functions like u_hasBinaryProperty to select + * one of the Unicode properties. + * + * The properties APIs are intended to reflect Unicode properties as defined + * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). + * + * For details about the properties see + * UAX #44: Unicode Character Database (http://www.unicode.org/reports/tr44/). + * + * Important: If ICU is built with UCD files from Unicode versions below, e.g., 3.2, + * then properties marked with "new in Unicode 3.2" are not or not fully available. + * Check u_getUnicodeVersion to be sure. + * + * @see u_hasBinaryProperty + * @see u_getIntPropertyValue + * @see u_getUnicodeVersion + * @stable ICU 2.1 + */ +typedef enum UProperty { + /* + * Note: UProperty constants are parsed by preparseucd.py. + * It matches lines like + * UCHAR_=, + */ + + /* Note: Place UCHAR_ALPHABETIC before UCHAR_BINARY_START so that + debuggers display UCHAR_ALPHABETIC as the symbolic name for 0, + rather than UCHAR_BINARY_START. Likewise for other *_START + identifiers. */ + + /** Binary property Alphabetic. Same as u_isUAlphabetic, different from u_isalpha. + Lu+Ll+Lt+Lm+Lo+Nl+Other_Alphabetic @stable ICU 2.1 */ + UCHAR_ALPHABETIC=0, + /** First constant for binary Unicode properties. @stable ICU 2.1 */ + UCHAR_BINARY_START=UCHAR_ALPHABETIC, + /** Binary property ASCII_Hex_Digit. 0-9 A-F a-f @stable ICU 2.1 */ + UCHAR_ASCII_HEX_DIGIT=1, + /** Binary property Bidi_Control. + Format controls which have specific functions + in the Bidi Algorithm. @stable ICU 2.1 */ + UCHAR_BIDI_CONTROL=2, + /** Binary property Bidi_Mirrored. + Characters that may change display in RTL text. + Same as u_isMirrored. + See Bidi Algorithm, UTR 9. @stable ICU 2.1 */ + UCHAR_BIDI_MIRRORED=3, + /** Binary property Dash. Variations of dashes. @stable ICU 2.1 */ + UCHAR_DASH=4, + /** Binary property Default_Ignorable_Code_Point (new in Unicode 3.2). + Ignorable in most processing. + <2060..206F, FFF0..FFFB, E0000..E0FFF>+Other_Default_Ignorable_Code_Point+(Cf+Cc+Cs-White_Space) @stable ICU 2.1 */ + UCHAR_DEFAULT_IGNORABLE_CODE_POINT=5, + /** Binary property Deprecated (new in Unicode 3.2). + The usage of deprecated characters is strongly discouraged. @stable ICU 2.1 */ + UCHAR_DEPRECATED=6, + /** Binary property Diacritic. Characters that linguistically modify + the meaning of another character to which they apply. @stable ICU 2.1 */ + UCHAR_DIACRITIC=7, + /** Binary property Extender. + Extend the value or shape of a preceding alphabetic character, + e.g., length and iteration marks. @stable ICU 2.1 */ + UCHAR_EXTENDER=8, + /** Binary property Full_Composition_Exclusion. + CompositionExclusions.txt+Singleton Decompositions+ + Non-Starter Decompositions. @stable ICU 2.1 */ + UCHAR_FULL_COMPOSITION_EXCLUSION=9, + /** Binary property Grapheme_Base (new in Unicode 3.2). + For programmatic determination of grapheme cluster boundaries. + [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-Grapheme_Extend-CGJ @stable ICU 2.1 */ + UCHAR_GRAPHEME_BASE=10, + /** Binary property Grapheme_Extend (new in Unicode 3.2). + For programmatic determination of grapheme cluster boundaries. + Me+Mn+Mc+Other_Grapheme_Extend-Grapheme_Link-CGJ @stable ICU 2.1 */ + UCHAR_GRAPHEME_EXTEND=11, + /** Binary property Grapheme_Link (new in Unicode 3.2). + For programmatic determination of grapheme cluster boundaries. @stable ICU 2.1 */ + UCHAR_GRAPHEME_LINK=12, + /** Binary property Hex_Digit. + Characters commonly used for hexadecimal numbers. @stable ICU 2.1 */ + UCHAR_HEX_DIGIT=13, + /** Binary property Hyphen. Dashes used to mark connections + between pieces of words, plus the Katakana middle dot. @stable ICU 2.1 */ + UCHAR_HYPHEN=14, + /** Binary property ID_Continue. + Characters that can continue an identifier. + DerivedCoreProperties.txt also says "NOTE: Cf characters should be filtered out." + ID_Start+Mn+Mc+Nd+Pc @stable ICU 2.1 */ + UCHAR_ID_CONTINUE=15, + /** Binary property ID_Start. + Characters that can start an identifier. + Lu+Ll+Lt+Lm+Lo+Nl @stable ICU 2.1 */ + UCHAR_ID_START=16, + /** Binary property Ideographic. + CJKV ideographs. @stable ICU 2.1 */ + UCHAR_IDEOGRAPHIC=17, + /** Binary property IDS_Binary_Operator (new in Unicode 3.2). + For programmatic determination of + Ideographic Description Sequences. @stable ICU 2.1 */ + UCHAR_IDS_BINARY_OPERATOR=18, + /** Binary property IDS_Trinary_Operator (new in Unicode 3.2). + For programmatic determination of + Ideographic Description Sequences. @stable ICU 2.1 */ + UCHAR_IDS_TRINARY_OPERATOR=19, + /** Binary property Join_Control. + Format controls for cursive joining and ligation. @stable ICU 2.1 */ + UCHAR_JOIN_CONTROL=20, + /** Binary property Logical_Order_Exception (new in Unicode 3.2). + Characters that do not use logical order and + require special handling in most processing. @stable ICU 2.1 */ + UCHAR_LOGICAL_ORDER_EXCEPTION=21, + /** Binary property Lowercase. Same as u_isULowercase, different from u_islower. + Ll+Other_Lowercase @stable ICU 2.1 */ + UCHAR_LOWERCASE=22, + /** Binary property Math. Sm+Other_Math @stable ICU 2.1 */ + UCHAR_MATH=23, + /** Binary property Noncharacter_Code_Point. + Code points that are explicitly defined as illegal + for the encoding of characters. @stable ICU 2.1 */ + UCHAR_NONCHARACTER_CODE_POINT=24, + /** Binary property Quotation_Mark. @stable ICU 2.1 */ + UCHAR_QUOTATION_MARK=25, + /** Binary property Radical (new in Unicode 3.2). + For programmatic determination of + Ideographic Description Sequences. @stable ICU 2.1 */ + UCHAR_RADICAL=26, + /** Binary property Soft_Dotted (new in Unicode 3.2). + Characters with a "soft dot", like i or j. + An accent placed on these characters causes + the dot to disappear. @stable ICU 2.1 */ + UCHAR_SOFT_DOTTED=27, + /** Binary property Terminal_Punctuation. + Punctuation characters that generally mark + the end of textual units. @stable ICU 2.1 */ + UCHAR_TERMINAL_PUNCTUATION=28, + /** Binary property Unified_Ideograph (new in Unicode 3.2). + For programmatic determination of + Ideographic Description Sequences. @stable ICU 2.1 */ + UCHAR_UNIFIED_IDEOGRAPH=29, + /** Binary property Uppercase. Same as u_isUUppercase, different from u_isupper. + Lu+Other_Uppercase @stable ICU 2.1 */ + UCHAR_UPPERCASE=30, + /** Binary property White_Space. + Same as u_isUWhiteSpace, different from u_isspace and u_isWhitespace. + Space characters+TAB+CR+LF-ZWSP-ZWNBSP @stable ICU 2.1 */ + UCHAR_WHITE_SPACE=31, + /** Binary property XID_Continue. + ID_Continue modified to allow closure under + normalization forms NFKC and NFKD. @stable ICU 2.1 */ + UCHAR_XID_CONTINUE=32, + /** Binary property XID_Start. ID_Start modified to allow + closure under normalization forms NFKC and NFKD. @stable ICU 2.1 */ + UCHAR_XID_START=33, + /** Binary property Case_Sensitive. Either the source of a case + mapping or _in_ the target of a case mapping. Not the same as + the general category Cased_Letter. @stable ICU 2.6 */ + UCHAR_CASE_SENSITIVE=34, + /** Binary property STerm (new in Unicode 4.0.1). + Sentence Terminal. Used in UAX #29: Text Boundaries + (http://www.unicode.org/reports/tr29/) + @stable ICU 3.0 */ + UCHAR_S_TERM=35, + /** Binary property Variation_Selector (new in Unicode 4.0.1). + Indicates all those characters that qualify as Variation Selectors. + For details on the behavior of these characters, + see StandardizedVariants.html and 15.6 Variation Selectors. + @stable ICU 3.0 */ + UCHAR_VARIATION_SELECTOR=36, + /** Binary property NFD_Inert. + ICU-specific property for characters that are inert under NFD, + i.e., they do not interact with adjacent characters. + See the documentation for the Normalizer2 class and the + Normalizer2::isInert() method. + @stable ICU 3.0 */ + UCHAR_NFD_INERT=37, + /** Binary property NFKD_Inert. + ICU-specific property for characters that are inert under NFKD, + i.e., they do not interact with adjacent characters. + See the documentation for the Normalizer2 class and the + Normalizer2::isInert() method. + @stable ICU 3.0 */ + UCHAR_NFKD_INERT=38, + /** Binary property NFC_Inert. + ICU-specific property for characters that are inert under NFC, + i.e., they do not interact with adjacent characters. + See the documentation for the Normalizer2 class and the + Normalizer2::isInert() method. + @stable ICU 3.0 */ + UCHAR_NFC_INERT=39, + /** Binary property NFKC_Inert. + ICU-specific property for characters that are inert under NFKC, + i.e., they do not interact with adjacent characters. + See the documentation for the Normalizer2 class and the + Normalizer2::isInert() method. + @stable ICU 3.0 */ + UCHAR_NFKC_INERT=40, + /** Binary Property Segment_Starter. + ICU-specific property for characters that are starters in terms of + Unicode normalization and combining character sequences. + They have ccc=0 and do not occur in non-initial position of the + canonical decomposition of any character + (like a-umlaut in NFD and a Jamo T in an NFD(Hangul LVT)). + ICU uses this property for segmenting a string for generating a set of + canonically equivalent strings, e.g. for canonical closure while + processing collation tailoring rules. + @stable ICU 3.0 */ + UCHAR_SEGMENT_STARTER=41, + /** Binary property Pattern_Syntax (new in Unicode 4.1). + See UAX #31 Identifier and Pattern Syntax + (http://www.unicode.org/reports/tr31/) + @stable ICU 3.4 */ + UCHAR_PATTERN_SYNTAX=42, + /** Binary property Pattern_White_Space (new in Unicode 4.1). + See UAX #31 Identifier and Pattern Syntax + (http://www.unicode.org/reports/tr31/) + @stable ICU 3.4 */ + UCHAR_PATTERN_WHITE_SPACE=43, + /** Binary property alnum (a C/POSIX character class). + Implemented according to the UTS #18 Annex C Standard Recommendation. + See the uchar.h file documentation. + @stable ICU 3.4 */ + UCHAR_POSIX_ALNUM=44, + /** Binary property blank (a C/POSIX character class). + Implemented according to the UTS #18 Annex C Standard Recommendation. + See the uchar.h file documentation. + @stable ICU 3.4 */ + UCHAR_POSIX_BLANK=45, + /** Binary property graph (a C/POSIX character class). + Implemented according to the UTS #18 Annex C Standard Recommendation. + See the uchar.h file documentation. + @stable ICU 3.4 */ + UCHAR_POSIX_GRAPH=46, + /** Binary property print (a C/POSIX character class). + Implemented according to the UTS #18 Annex C Standard Recommendation. + See the uchar.h file documentation. + @stable ICU 3.4 */ + UCHAR_POSIX_PRINT=47, + /** Binary property xdigit (a C/POSIX character class). + Implemented according to the UTS #18 Annex C Standard Recommendation. + See the uchar.h file documentation. + @stable ICU 3.4 */ + UCHAR_POSIX_XDIGIT=48, + /** Binary property Cased. For Lowercase, Uppercase and Titlecase characters. @stable ICU 4.4 */ + UCHAR_CASED=49, + /** Binary property Case_Ignorable. Used in context-sensitive case mappings. @stable ICU 4.4 */ + UCHAR_CASE_IGNORABLE=50, + /** Binary property Changes_When_Lowercased. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_LOWERCASED=51, + /** Binary property Changes_When_Uppercased. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_UPPERCASED=52, + /** Binary property Changes_When_Titlecased. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_TITLECASED=53, + /** Binary property Changes_When_Casefolded. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_CASEFOLDED=54, + /** Binary property Changes_When_Casemapped. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_CASEMAPPED=55, + /** Binary property Changes_When_NFKC_Casefolded. @stable ICU 4.4 */ + UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED=56, + /** + * Binary property Emoji. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 57 + */ + UCHAR_EMOJI=57, + /** + * Binary property Emoji_Presentation. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 57 + */ + UCHAR_EMOJI_PRESENTATION=58, + /** + * Binary property Emoji_Modifier. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 57 + */ + UCHAR_EMOJI_MODIFIER=59, + /** + * Binary property Emoji_Modifier_Base. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 57 + */ + UCHAR_EMOJI_MODIFIER_BASE=60, + /** + * Binary property Emoji_Component. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 60 + */ + UCHAR_EMOJI_COMPONENT=61, + /** + * Binary property Regional_Indicator. + * @stable ICU 60 + */ + UCHAR_REGIONAL_INDICATOR=62, + /** + * Binary property Prepended_Concatenation_Mark. + * @stable ICU 60 + */ + UCHAR_PREPENDED_CONCATENATION_MARK=63, + /** + * Binary property Extended_Pictographic. + * See http://www.unicode.org/reports/tr51/#Emoji_Properties + * + * @stable ICU 62 + */ + UCHAR_EXTENDED_PICTOGRAPHIC=64, + /** + * Binary property of strings Basic_Emoji. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_BASIC_EMOJI=65, + /** + * Binary property of strings Emoji_Keycap_Sequence. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_EMOJI_KEYCAP_SEQUENCE=66, + /** + * Binary property of strings RGI_Emoji_Modifier_Sequence. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE=67, + /** + * Binary property of strings RGI_Emoji_Flag_Sequence. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_RGI_EMOJI_FLAG_SEQUENCE=68, + /** + * Binary property of strings RGI_Emoji_Tag_Sequence. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_RGI_EMOJI_TAG_SEQUENCE=69, + /** + * Binary property of strings RGI_Emoji_ZWJ_Sequence. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_RGI_EMOJI_ZWJ_SEQUENCE=70, + /** + * Binary property of strings RGI_Emoji. + * See https://www.unicode.org/reports/tr51/#Emoji_Sets + * + * @stable ICU 70 + */ + UCHAR_RGI_EMOJI=71, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for binary Unicode properties. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_BINARY_LIMIT=72, +#endif // U_HIDE_DEPRECATED_API + + /** Enumerated property Bidi_Class. + Same as u_charDirection, returns UCharDirection values. @stable ICU 2.2 */ + UCHAR_BIDI_CLASS=0x1000, + /** First constant for enumerated/integer Unicode properties. @stable ICU 2.2 */ + UCHAR_INT_START=UCHAR_BIDI_CLASS, + /** Enumerated property Block. + Same as ublock_getCode, returns UBlockCode values. @stable ICU 2.2 */ + UCHAR_BLOCK=0x1001, + /** Enumerated property Canonical_Combining_Class. + Same as u_getCombiningClass, returns 8-bit numeric values. @stable ICU 2.2 */ + UCHAR_CANONICAL_COMBINING_CLASS=0x1002, + /** Enumerated property Decomposition_Type. + Returns UDecompositionType values. @stable ICU 2.2 */ + UCHAR_DECOMPOSITION_TYPE=0x1003, + /** Enumerated property East_Asian_Width. + See http://www.unicode.org/reports/tr11/ + Returns UEastAsianWidth values. @stable ICU 2.2 */ + UCHAR_EAST_ASIAN_WIDTH=0x1004, + /** Enumerated property General_Category. + Same as u_charType, returns UCharCategory values. @stable ICU 2.2 */ + UCHAR_GENERAL_CATEGORY=0x1005, + /** Enumerated property Joining_Group. + Returns UJoiningGroup values. @stable ICU 2.2 */ + UCHAR_JOINING_GROUP=0x1006, + /** Enumerated property Joining_Type. + Returns UJoiningType values. @stable ICU 2.2 */ + UCHAR_JOINING_TYPE=0x1007, + /** Enumerated property Line_Break. + Returns ULineBreak values. @stable ICU 2.2 */ + UCHAR_LINE_BREAK=0x1008, + /** Enumerated property Numeric_Type. + Returns UNumericType values. @stable ICU 2.2 */ + UCHAR_NUMERIC_TYPE=0x1009, + /** Enumerated property Script. + Same as uscript_getScript, returns UScriptCode values. @stable ICU 2.2 */ + UCHAR_SCRIPT=0x100A, + /** Enumerated property Hangul_Syllable_Type, new in Unicode 4. + Returns UHangulSyllableType values. @stable ICU 2.6 */ + UCHAR_HANGUL_SYLLABLE_TYPE=0x100B, + /** Enumerated property NFD_Quick_Check. + Returns UNormalizationCheckResult values. @stable ICU 3.0 */ + UCHAR_NFD_QUICK_CHECK=0x100C, + /** Enumerated property NFKD_Quick_Check. + Returns UNormalizationCheckResult values. @stable ICU 3.0 */ + UCHAR_NFKD_QUICK_CHECK=0x100D, + /** Enumerated property NFC_Quick_Check. + Returns UNormalizationCheckResult values. @stable ICU 3.0 */ + UCHAR_NFC_QUICK_CHECK=0x100E, + /** Enumerated property NFKC_Quick_Check. + Returns UNormalizationCheckResult values. @stable ICU 3.0 */ + UCHAR_NFKC_QUICK_CHECK=0x100F, + /** Enumerated property Lead_Canonical_Combining_Class. + ICU-specific property for the ccc of the first code point + of the decomposition, or lccc(c)=ccc(NFD(c)[0]). + Useful for checking for canonically ordered text; + see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD . + Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */ + UCHAR_LEAD_CANONICAL_COMBINING_CLASS=0x1010, + /** Enumerated property Trail_Canonical_Combining_Class. + ICU-specific property for the ccc of the last code point + of the decomposition, or tccc(c)=ccc(NFD(c)[last]). + Useful for checking for canonically ordered text; + see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD . + Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */ + UCHAR_TRAIL_CANONICAL_COMBINING_CLASS=0x1011, + /** Enumerated property Grapheme_Cluster_Break (new in Unicode 4.1). + Used in UAX #29: Text Boundaries + (http://www.unicode.org/reports/tr29/) + Returns UGraphemeClusterBreak values. @stable ICU 3.4 */ + UCHAR_GRAPHEME_CLUSTER_BREAK=0x1012, + /** Enumerated property Sentence_Break (new in Unicode 4.1). + Used in UAX #29: Text Boundaries + (http://www.unicode.org/reports/tr29/) + Returns USentenceBreak values. @stable ICU 3.4 */ + UCHAR_SENTENCE_BREAK=0x1013, + /** Enumerated property Word_Break (new in Unicode 4.1). + Used in UAX #29: Text Boundaries + (http://www.unicode.org/reports/tr29/) + Returns UWordBreakValues values. @stable ICU 3.4 */ + UCHAR_WORD_BREAK=0x1014, + /** Enumerated property Bidi_Paired_Bracket_Type (new in Unicode 6.3). + Used in UAX #9: Unicode Bidirectional Algorithm + (http://www.unicode.org/reports/tr9/) + Returns UBidiPairedBracketType values. @stable ICU 52 */ + UCHAR_BIDI_PAIRED_BRACKET_TYPE=0x1015, + /** + * Enumerated property Indic_Positional_Category. + * New in Unicode 6.0 as provisional property Indic_Matra_Category; + * renamed and changed to informative in Unicode 8.0. + * See http://www.unicode.org/reports/tr44/#IndicPositionalCategory.txt + * @stable ICU 63 + */ + UCHAR_INDIC_POSITIONAL_CATEGORY=0x1016, + /** + * Enumerated property Indic_Syllabic_Category. + * New in Unicode 6.0 as provisional; informative since Unicode 8.0. + * See http://www.unicode.org/reports/tr44/#IndicSyllabicCategory.txt + * @stable ICU 63 + */ + UCHAR_INDIC_SYLLABIC_CATEGORY=0x1017, + /** + * Enumerated property Vertical_Orientation. + * Used for UAX #50 Unicode Vertical Text Layout (https://www.unicode.org/reports/tr50/). + * New as a UCD property in Unicode 10.0. + * @stable ICU 63 + */ + UCHAR_VERTICAL_ORIENTATION=0x1018, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for enumerated/integer Unicode properties. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_INT_LIMIT=0x1019, +#endif // U_HIDE_DEPRECATED_API + + /** Bitmask property General_Category_Mask. + This is the General_Category property returned as a bit mask. + When used in u_getIntPropertyValue(c), same as U_MASK(u_charType(c)), + returns bit masks for UCharCategory values where exactly one bit is set. + When used with u_getPropertyValueName() and u_getPropertyValueEnum(), + a multi-bit mask is used for sets of categories like "Letters". + Mask values should be cast to uint32_t. + @stable ICU 2.4 */ + UCHAR_GENERAL_CATEGORY_MASK=0x2000, + /** First constant for bit-mask Unicode properties. @stable ICU 2.4 */ + UCHAR_MASK_START=UCHAR_GENERAL_CATEGORY_MASK, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for bit-mask Unicode properties. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_MASK_LIMIT=0x2001, +#endif // U_HIDE_DEPRECATED_API + + /** Double property Numeric_Value. + Corresponds to u_getNumericValue. @stable ICU 2.4 */ + UCHAR_NUMERIC_VALUE=0x3000, + /** First constant for double Unicode properties. @stable ICU 2.4 */ + UCHAR_DOUBLE_START=UCHAR_NUMERIC_VALUE, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for double Unicode properties. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_DOUBLE_LIMIT=0x3001, +#endif // U_HIDE_DEPRECATED_API + + /** String property Age. + Corresponds to u_charAge. @stable ICU 2.4 */ + UCHAR_AGE=0x4000, + /** First constant for string Unicode properties. @stable ICU 2.4 */ + UCHAR_STRING_START=UCHAR_AGE, + /** String property Bidi_Mirroring_Glyph. + Corresponds to u_charMirror. @stable ICU 2.4 */ + UCHAR_BIDI_MIRRORING_GLYPH=0x4001, + /** String property Case_Folding. + Corresponds to u_strFoldCase in ustring.h. @stable ICU 2.4 */ + UCHAR_CASE_FOLDING=0x4002, +#ifndef U_HIDE_DEPRECATED_API + /** Deprecated string property ISO_Comment. + Corresponds to u_getISOComment. @deprecated ICU 49 */ + UCHAR_ISO_COMMENT=0x4003, +#endif /* U_HIDE_DEPRECATED_API */ + /** String property Lowercase_Mapping. + Corresponds to u_strToLower in ustring.h. @stable ICU 2.4 */ + UCHAR_LOWERCASE_MAPPING=0x4004, + /** String property Name. + Corresponds to u_charName. @stable ICU 2.4 */ + UCHAR_NAME=0x4005, + /** String property Simple_Case_Folding. + Corresponds to u_foldCase. @stable ICU 2.4 */ + UCHAR_SIMPLE_CASE_FOLDING=0x4006, + /** String property Simple_Lowercase_Mapping. + Corresponds to u_tolower. @stable ICU 2.4 */ + UCHAR_SIMPLE_LOWERCASE_MAPPING=0x4007, + /** String property Simple_Titlecase_Mapping. + Corresponds to u_totitle. @stable ICU 2.4 */ + UCHAR_SIMPLE_TITLECASE_MAPPING=0x4008, + /** String property Simple_Uppercase_Mapping. + Corresponds to u_toupper. @stable ICU 2.4 */ + UCHAR_SIMPLE_UPPERCASE_MAPPING=0x4009, + /** String property Titlecase_Mapping. + Corresponds to u_strToTitle in ustring.h. @stable ICU 2.4 */ + UCHAR_TITLECASE_MAPPING=0x400A, +#ifndef U_HIDE_DEPRECATED_API + /** String property Unicode_1_Name. + This property is of little practical value. + Beginning with ICU 49, ICU APIs return an empty string for this property. + Corresponds to u_charName(U_UNICODE_10_CHAR_NAME). @deprecated ICU 49 */ + UCHAR_UNICODE_1_NAME=0x400B, +#endif /* U_HIDE_DEPRECATED_API */ + /** String property Uppercase_Mapping. + Corresponds to u_strToUpper in ustring.h. @stable ICU 2.4 */ + UCHAR_UPPERCASE_MAPPING=0x400C, + /** String property Bidi_Paired_Bracket (new in Unicode 6.3). + Corresponds to u_getBidiPairedBracket. @stable ICU 52 */ + UCHAR_BIDI_PAIRED_BRACKET=0x400D, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for string Unicode properties. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_STRING_LIMIT=0x400E, +#endif // U_HIDE_DEPRECATED_API + + /** Miscellaneous property Script_Extensions (new in Unicode 6.0). + Some characters are commonly used in multiple scripts. + For more information, see UAX #24: http://www.unicode.org/reports/tr24/. + Corresponds to uscript_hasScript and uscript_getScriptExtensions in uscript.h. + @stable ICU 4.6 */ + UCHAR_SCRIPT_EXTENSIONS=0x7000, + /** First constant for Unicode properties with unusual value types. @stable ICU 4.6 */ + UCHAR_OTHER_PROPERTY_START=UCHAR_SCRIPT_EXTENSIONS, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the last constant for Unicode properties with unusual value types. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCHAR_OTHER_PROPERTY_LIMIT=0x7001, +#endif // U_HIDE_DEPRECATED_API + + /** Represents a nonexistent or invalid property or property value. @stable ICU 2.4 */ + UCHAR_INVALID_CODE = -1 +} UProperty; + +/** + * Data for enumerated Unicode general category types. + * See http://www.unicode.org/Public/UNIDATA/UnicodeData.html . + * @stable ICU 2.0 + */ +typedef enum UCharCategory +{ + /* + * Note: UCharCategory constants and their API comments are parsed by preparseucd.py. + * It matches pairs of lines like + * / ** comment... * / + * U_<[A-Z_]+> = , + */ + + /** Non-category for unassigned and non-character code points. @stable ICU 2.0 */ + U_UNASSIGNED = 0, + /** Cn "Other, Not Assigned (no characters in [UnicodeData.txt] have this property)" (same as U_UNASSIGNED!) @stable ICU 2.0 */ + U_GENERAL_OTHER_TYPES = 0, + /** Lu @stable ICU 2.0 */ + U_UPPERCASE_LETTER = 1, + /** Ll @stable ICU 2.0 */ + U_LOWERCASE_LETTER = 2, + /** Lt @stable ICU 2.0 */ + U_TITLECASE_LETTER = 3, + /** Lm @stable ICU 2.0 */ + U_MODIFIER_LETTER = 4, + /** Lo @stable ICU 2.0 */ + U_OTHER_LETTER = 5, + /** Mn @stable ICU 2.0 */ + U_NON_SPACING_MARK = 6, + /** Me @stable ICU 2.0 */ + U_ENCLOSING_MARK = 7, + /** Mc @stable ICU 2.0 */ + U_COMBINING_SPACING_MARK = 8, + /** Nd @stable ICU 2.0 */ + U_DECIMAL_DIGIT_NUMBER = 9, + /** Nl @stable ICU 2.0 */ + U_LETTER_NUMBER = 10, + /** No @stable ICU 2.0 */ + U_OTHER_NUMBER = 11, + /** Zs @stable ICU 2.0 */ + U_SPACE_SEPARATOR = 12, + /** Zl @stable ICU 2.0 */ + U_LINE_SEPARATOR = 13, + /** Zp @stable ICU 2.0 */ + U_PARAGRAPH_SEPARATOR = 14, + /** Cc @stable ICU 2.0 */ + U_CONTROL_CHAR = 15, + /** Cf @stable ICU 2.0 */ + U_FORMAT_CHAR = 16, + /** Co @stable ICU 2.0 */ + U_PRIVATE_USE_CHAR = 17, + /** Cs @stable ICU 2.0 */ + U_SURROGATE = 18, + /** Pd @stable ICU 2.0 */ + U_DASH_PUNCTUATION = 19, + /** Ps @stable ICU 2.0 */ + U_START_PUNCTUATION = 20, + /** Pe @stable ICU 2.0 */ + U_END_PUNCTUATION = 21, + /** Pc @stable ICU 2.0 */ + U_CONNECTOR_PUNCTUATION = 22, + /** Po @stable ICU 2.0 */ + U_OTHER_PUNCTUATION = 23, + /** Sm @stable ICU 2.0 */ + U_MATH_SYMBOL = 24, + /** Sc @stable ICU 2.0 */ + U_CURRENCY_SYMBOL = 25, + /** Sk @stable ICU 2.0 */ + U_MODIFIER_SYMBOL = 26, + /** So @stable ICU 2.0 */ + U_OTHER_SYMBOL = 27, + /** Pi @stable ICU 2.0 */ + U_INITIAL_PUNCTUATION = 28, + /** Pf @stable ICU 2.0 */ + U_FINAL_PUNCTUATION = 29, + /** + * One higher than the last enum UCharCategory constant. + * This numeric value is stable (will not change), see + * http://www.unicode.org/policies/stability_policy.html#Property_Value + * + * @stable ICU 2.0 + */ + U_CHAR_CATEGORY_COUNT +} UCharCategory; + +/** + * U_GC_XX_MASK constants are bit flags corresponding to Unicode + * general category values. + * For each category, the nth bit is set if the numeric value of the + * corresponding UCharCategory constant is n. + * + * There are also some U_GC_Y_MASK constants for groups of general categories + * like L for all letter categories. + * + * @see u_charType + * @see U_GET_GC_MASK + * @see UCharCategory + * @stable ICU 2.1 + */ +#define U_GC_CN_MASK U_MASK(U_GENERAL_OTHER_TYPES) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_LU_MASK U_MASK(U_UPPERCASE_LETTER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_LL_MASK U_MASK(U_LOWERCASE_LETTER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_LT_MASK U_MASK(U_TITLECASE_LETTER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_LM_MASK U_MASK(U_MODIFIER_LETTER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_LO_MASK U_MASK(U_OTHER_LETTER) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_MN_MASK U_MASK(U_NON_SPACING_MARK) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_ME_MASK U_MASK(U_ENCLOSING_MARK) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_MC_MASK U_MASK(U_COMBINING_SPACING_MARK) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_ND_MASK U_MASK(U_DECIMAL_DIGIT_NUMBER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_NL_MASK U_MASK(U_LETTER_NUMBER) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_NO_MASK U_MASK(U_OTHER_NUMBER) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_ZS_MASK U_MASK(U_SPACE_SEPARATOR) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_ZL_MASK U_MASK(U_LINE_SEPARATOR) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_ZP_MASK U_MASK(U_PARAGRAPH_SEPARATOR) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_CC_MASK U_MASK(U_CONTROL_CHAR) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_CF_MASK U_MASK(U_FORMAT_CHAR) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_CO_MASK U_MASK(U_PRIVATE_USE_CHAR) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_CS_MASK U_MASK(U_SURROGATE) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PD_MASK U_MASK(U_DASH_PUNCTUATION) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PS_MASK U_MASK(U_START_PUNCTUATION) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PE_MASK U_MASK(U_END_PUNCTUATION) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PC_MASK U_MASK(U_CONNECTOR_PUNCTUATION) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PO_MASK U_MASK(U_OTHER_PUNCTUATION) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_SM_MASK U_MASK(U_MATH_SYMBOL) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_SC_MASK U_MASK(U_CURRENCY_SYMBOL) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_SK_MASK U_MASK(U_MODIFIER_SYMBOL) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_SO_MASK U_MASK(U_OTHER_SYMBOL) + +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PI_MASK U_MASK(U_INITIAL_PUNCTUATION) +/** Mask constant for a UCharCategory. @stable ICU 2.1 */ +#define U_GC_PF_MASK U_MASK(U_FINAL_PUNCTUATION) + + +/** Mask constant for multiple UCharCategory bits (L Letters). @stable ICU 2.1 */ +#define U_GC_L_MASK \ + (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK|U_GC_LM_MASK|U_GC_LO_MASK) + +/** Mask constant for multiple UCharCategory bits (LC Cased Letters). @stable ICU 2.1 */ +#define U_GC_LC_MASK \ + (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK) + +/** Mask constant for multiple UCharCategory bits (M Marks). @stable ICU 2.1 */ +#define U_GC_M_MASK (U_GC_MN_MASK|U_GC_ME_MASK|U_GC_MC_MASK) + +/** Mask constant for multiple UCharCategory bits (N Numbers). @stable ICU 2.1 */ +#define U_GC_N_MASK (U_GC_ND_MASK|U_GC_NL_MASK|U_GC_NO_MASK) + +/** Mask constant for multiple UCharCategory bits (Z Separators). @stable ICU 2.1 */ +#define U_GC_Z_MASK (U_GC_ZS_MASK|U_GC_ZL_MASK|U_GC_ZP_MASK) + +/** Mask constant for multiple UCharCategory bits (C Others). @stable ICU 2.1 */ +#define U_GC_C_MASK \ + (U_GC_CN_MASK|U_GC_CC_MASK|U_GC_CF_MASK|U_GC_CO_MASK|U_GC_CS_MASK) + +/** Mask constant for multiple UCharCategory bits (P Punctuation). @stable ICU 2.1 */ +#define U_GC_P_MASK \ + (U_GC_PD_MASK|U_GC_PS_MASK|U_GC_PE_MASK|U_GC_PC_MASK|U_GC_PO_MASK| \ + U_GC_PI_MASK|U_GC_PF_MASK) + +/** Mask constant for multiple UCharCategory bits (S Symbols). @stable ICU 2.1 */ +#define U_GC_S_MASK (U_GC_SM_MASK|U_GC_SC_MASK|U_GC_SK_MASK|U_GC_SO_MASK) + +/** + * This specifies the language directional property of a character set. + * @stable ICU 2.0 + */ +typedef enum UCharDirection { + /* + * Note: UCharDirection constants and their API comments are parsed by preparseucd.py. + * It matches pairs of lines like + * / ** comment... * / + * U_<[A-Z_]+> = , + */ + + /** L @stable ICU 2.0 */ + U_LEFT_TO_RIGHT = 0, + /** R @stable ICU 2.0 */ + U_RIGHT_TO_LEFT = 1, + /** EN @stable ICU 2.0 */ + U_EUROPEAN_NUMBER = 2, + /** ES @stable ICU 2.0 */ + U_EUROPEAN_NUMBER_SEPARATOR = 3, + /** ET @stable ICU 2.0 */ + U_EUROPEAN_NUMBER_TERMINATOR = 4, + /** AN @stable ICU 2.0 */ + U_ARABIC_NUMBER = 5, + /** CS @stable ICU 2.0 */ + U_COMMON_NUMBER_SEPARATOR = 6, + /** B @stable ICU 2.0 */ + U_BLOCK_SEPARATOR = 7, + /** S @stable ICU 2.0 */ + U_SEGMENT_SEPARATOR = 8, + /** WS @stable ICU 2.0 */ + U_WHITE_SPACE_NEUTRAL = 9, + /** ON @stable ICU 2.0 */ + U_OTHER_NEUTRAL = 10, + /** LRE @stable ICU 2.0 */ + U_LEFT_TO_RIGHT_EMBEDDING = 11, + /** LRO @stable ICU 2.0 */ + U_LEFT_TO_RIGHT_OVERRIDE = 12, + /** AL @stable ICU 2.0 */ + U_RIGHT_TO_LEFT_ARABIC = 13, + /** RLE @stable ICU 2.0 */ + U_RIGHT_TO_LEFT_EMBEDDING = 14, + /** RLO @stable ICU 2.0 */ + U_RIGHT_TO_LEFT_OVERRIDE = 15, + /** PDF @stable ICU 2.0 */ + U_POP_DIRECTIONAL_FORMAT = 16, + /** NSM @stable ICU 2.0 */ + U_DIR_NON_SPACING_MARK = 17, + /** BN @stable ICU 2.0 */ + U_BOUNDARY_NEUTRAL = 18, + /** FSI @stable ICU 52 */ + U_FIRST_STRONG_ISOLATE = 19, + /** LRI @stable ICU 52 */ + U_LEFT_TO_RIGHT_ISOLATE = 20, + /** RLI @stable ICU 52 */ + U_RIGHT_TO_LEFT_ISOLATE = 21, + /** PDI @stable ICU 52 */ + U_POP_DIRECTIONAL_ISOLATE = 22, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest UCharDirection value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_CHAR_DIRECTION_COUNT +#endif // U_HIDE_DEPRECATED_API +} UCharDirection; + +/** + * Bidi Paired Bracket Type constants. + * + * @see UCHAR_BIDI_PAIRED_BRACKET_TYPE + * @stable ICU 52 + */ +typedef enum UBidiPairedBracketType { + /* + * Note: UBidiPairedBracketType constants are parsed by preparseucd.py. + * It matches lines like + * U_BPT_ + */ + + /** Not a paired bracket. @stable ICU 52 */ + U_BPT_NONE, + /** Open paired bracket. @stable ICU 52 */ + U_BPT_OPEN, + /** Close paired bracket. @stable ICU 52 */ + U_BPT_CLOSE, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UBidiPairedBracketType value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BIDI_PAIRED_BRACKET_TYPE). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_BPT_COUNT /* 3 */ +#endif // U_HIDE_DEPRECATED_API +} UBidiPairedBracketType; + +/** + * Constants for Unicode blocks, see the Unicode Data file Blocks.txt + * @stable ICU 2.0 + */ +enum UBlockCode { + /* + * Note: UBlockCode constants are parsed by preparseucd.py. + * It matches lines like + * UBLOCK_ = , + */ + + /** New No_Block value in Unicode 4. @stable ICU 2.6 */ + UBLOCK_NO_BLOCK = 0, /*[none]*/ /* Special range indicating No_Block */ + + /** @stable ICU 2.0 */ + UBLOCK_BASIC_LATIN = 1, /*[0000]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LATIN_1_SUPPLEMENT=2, /*[0080]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LATIN_EXTENDED_A =3, /*[0100]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LATIN_EXTENDED_B =4, /*[0180]*/ + + /** @stable ICU 2.0 */ + UBLOCK_IPA_EXTENSIONS =5, /*[0250]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SPACING_MODIFIER_LETTERS =6, /*[02B0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_COMBINING_DIACRITICAL_MARKS =7, /*[0300]*/ + + /** + * Unicode 3.2 renames this block to "Greek and Coptic". + * @stable ICU 2.0 + */ + UBLOCK_GREEK =8, /*[0370]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CYRILLIC =9, /*[0400]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ARMENIAN =10, /*[0530]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HEBREW =11, /*[0590]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ARABIC =12, /*[0600]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SYRIAC =13, /*[0700]*/ + + /** @stable ICU 2.0 */ + UBLOCK_THAANA =14, /*[0780]*/ + + /** @stable ICU 2.0 */ + UBLOCK_DEVANAGARI =15, /*[0900]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BENGALI =16, /*[0980]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GURMUKHI =17, /*[0A00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GUJARATI =18, /*[0A80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ORIYA =19, /*[0B00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_TAMIL =20, /*[0B80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_TELUGU =21, /*[0C00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_KANNADA =22, /*[0C80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MALAYALAM =23, /*[0D00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SINHALA =24, /*[0D80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_THAI =25, /*[0E00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LAO =26, /*[0E80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_TIBETAN =27, /*[0F00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MYANMAR =28, /*[1000]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GEORGIAN =29, /*[10A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HANGUL_JAMO =30, /*[1100]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ETHIOPIC =31, /*[1200]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CHEROKEE =32, /*[13A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS =33, /*[1400]*/ + + /** @stable ICU 2.0 */ + UBLOCK_OGHAM =34, /*[1680]*/ + + /** @stable ICU 2.0 */ + UBLOCK_RUNIC =35, /*[16A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_KHMER =36, /*[1780]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MONGOLIAN =37, /*[1800]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LATIN_EXTENDED_ADDITIONAL =38, /*[1E00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GREEK_EXTENDED =39, /*[1F00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GENERAL_PUNCTUATION =40, /*[2000]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SUPERSCRIPTS_AND_SUBSCRIPTS =41, /*[2070]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CURRENCY_SYMBOLS =42, /*[20A0]*/ + + /** + * Unicode 3.2 renames this block to "Combining Diacritical Marks for Symbols". + * @stable ICU 2.0 + */ + UBLOCK_COMBINING_MARKS_FOR_SYMBOLS =43, /*[20D0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LETTERLIKE_SYMBOLS =44, /*[2100]*/ + + /** @stable ICU 2.0 */ + UBLOCK_NUMBER_FORMS =45, /*[2150]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ARROWS =46, /*[2190]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MATHEMATICAL_OPERATORS =47, /*[2200]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MISCELLANEOUS_TECHNICAL =48, /*[2300]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CONTROL_PICTURES =49, /*[2400]*/ + + /** @stable ICU 2.0 */ + UBLOCK_OPTICAL_CHARACTER_RECOGNITION =50, /*[2440]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ENCLOSED_ALPHANUMERICS =51, /*[2460]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BOX_DRAWING =52, /*[2500]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BLOCK_ELEMENTS =53, /*[2580]*/ + + /** @stable ICU 2.0 */ + UBLOCK_GEOMETRIC_SHAPES =54, /*[25A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_MISCELLANEOUS_SYMBOLS =55, /*[2600]*/ + + /** @stable ICU 2.0 */ + UBLOCK_DINGBATS =56, /*[2700]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BRAILLE_PATTERNS =57, /*[2800]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_RADICALS_SUPPLEMENT =58, /*[2E80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_KANGXI_RADICALS =59, /*[2F00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_IDEOGRAPHIC_DESCRIPTION_CHARACTERS =60, /*[2FF0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION =61, /*[3000]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HIRAGANA =62, /*[3040]*/ + + /** @stable ICU 2.0 */ + UBLOCK_KATAKANA =63, /*[30A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BOPOMOFO =64, /*[3100]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HANGUL_COMPATIBILITY_JAMO =65, /*[3130]*/ + + /** @stable ICU 2.0 */ + UBLOCK_KANBUN =66, /*[3190]*/ + + /** @stable ICU 2.0 */ + UBLOCK_BOPOMOFO_EXTENDED =67, /*[31A0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ENCLOSED_CJK_LETTERS_AND_MONTHS =68, /*[3200]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_COMPATIBILITY =69, /*[3300]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A =70, /*[3400]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS =71, /*[4E00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_YI_SYLLABLES =72, /*[A000]*/ + + /** @stable ICU 2.0 */ + UBLOCK_YI_RADICALS =73, /*[A490]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HANGUL_SYLLABLES =74, /*[AC00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HIGH_SURROGATES =75, /*[D800]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HIGH_PRIVATE_USE_SURROGATES =76, /*[DB80]*/ + + /** @stable ICU 2.0 */ + UBLOCK_LOW_SURROGATES =77, /*[DC00]*/ + + /** + * Same as UBLOCK_PRIVATE_USE. + * Until Unicode 3.1.1, the corresponding block name was "Private Use", + * and multiple code point ranges had this block. + * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and + * adds separate blocks for the supplementary PUAs. + * + * @stable ICU 2.0 + */ + UBLOCK_PRIVATE_USE_AREA =78, /*[E000]*/ + /** + * Same as UBLOCK_PRIVATE_USE_AREA. + * Until Unicode 3.1.1, the corresponding block name was "Private Use", + * and multiple code point ranges had this block. + * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and + * adds separate blocks for the supplementary PUAs. + * + * @stable ICU 2.0 + */ + UBLOCK_PRIVATE_USE = UBLOCK_PRIVATE_USE_AREA, + + /** @stable ICU 2.0 */ + UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS =79, /*[F900]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ALPHABETIC_PRESENTATION_FORMS =80, /*[FB00]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ARABIC_PRESENTATION_FORMS_A =81, /*[FB50]*/ + + /** @stable ICU 2.0 */ + UBLOCK_COMBINING_HALF_MARKS =82, /*[FE20]*/ + + /** @stable ICU 2.0 */ + UBLOCK_CJK_COMPATIBILITY_FORMS =83, /*[FE30]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SMALL_FORM_VARIANTS =84, /*[FE50]*/ + + /** @stable ICU 2.0 */ + UBLOCK_ARABIC_PRESENTATION_FORMS_B =85, /*[FE70]*/ + + /** @stable ICU 2.0 */ + UBLOCK_SPECIALS =86, /*[FFF0]*/ + + /** @stable ICU 2.0 */ + UBLOCK_HALFWIDTH_AND_FULLWIDTH_FORMS =87, /*[FF00]*/ + + /* New blocks in Unicode 3.1 */ + + /** @stable ICU 2.0 */ + UBLOCK_OLD_ITALIC = 88, /*[10300]*/ + /** @stable ICU 2.0 */ + UBLOCK_GOTHIC = 89, /*[10330]*/ + /** @stable ICU 2.0 */ + UBLOCK_DESERET = 90, /*[10400]*/ + /** @stable ICU 2.0 */ + UBLOCK_BYZANTINE_MUSICAL_SYMBOLS = 91, /*[1D000]*/ + /** @stable ICU 2.0 */ + UBLOCK_MUSICAL_SYMBOLS = 92, /*[1D100]*/ + /** @stable ICU 2.0 */ + UBLOCK_MATHEMATICAL_ALPHANUMERIC_SYMBOLS = 93, /*[1D400]*/ + /** @stable ICU 2.0 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = 94, /*[20000]*/ + /** @stable ICU 2.0 */ + UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = 95, /*[2F800]*/ + /** @stable ICU 2.0 */ + UBLOCK_TAGS = 96, /*[E0000]*/ + + /* New blocks in Unicode 3.2 */ + + /** @stable ICU 3.0 */ + UBLOCK_CYRILLIC_SUPPLEMENT = 97, /*[0500]*/ + /** + * Unicode 4.0.1 renames the "Cyrillic Supplementary" block to "Cyrillic Supplement". + * @stable ICU 2.2 + */ + UBLOCK_CYRILLIC_SUPPLEMENTARY = UBLOCK_CYRILLIC_SUPPLEMENT, + /** @stable ICU 2.2 */ + UBLOCK_TAGALOG = 98, /*[1700]*/ + /** @stable ICU 2.2 */ + UBLOCK_HANUNOO = 99, /*[1720]*/ + /** @stable ICU 2.2 */ + UBLOCK_BUHID = 100, /*[1740]*/ + /** @stable ICU 2.2 */ + UBLOCK_TAGBANWA = 101, /*[1760]*/ + /** @stable ICU 2.2 */ + UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = 102, /*[27C0]*/ + /** @stable ICU 2.2 */ + UBLOCK_SUPPLEMENTAL_ARROWS_A = 103, /*[27F0]*/ + /** @stable ICU 2.2 */ + UBLOCK_SUPPLEMENTAL_ARROWS_B = 104, /*[2900]*/ + /** @stable ICU 2.2 */ + UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = 105, /*[2980]*/ + /** @stable ICU 2.2 */ + UBLOCK_SUPPLEMENTAL_MATHEMATICAL_OPERATORS = 106, /*[2A00]*/ + /** @stable ICU 2.2 */ + UBLOCK_KATAKANA_PHONETIC_EXTENSIONS = 107, /*[31F0]*/ + /** @stable ICU 2.2 */ + UBLOCK_VARIATION_SELECTORS = 108, /*[FE00]*/ + /** @stable ICU 2.2 */ + UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_A = 109, /*[F0000]*/ + /** @stable ICU 2.2 */ + UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_B = 110, /*[100000]*/ + + /* New blocks in Unicode 4 */ + + /** @stable ICU 2.6 */ + UBLOCK_LIMBU = 111, /*[1900]*/ + /** @stable ICU 2.6 */ + UBLOCK_TAI_LE = 112, /*[1950]*/ + /** @stable ICU 2.6 */ + UBLOCK_KHMER_SYMBOLS = 113, /*[19E0]*/ + /** @stable ICU 2.6 */ + UBLOCK_PHONETIC_EXTENSIONS = 114, /*[1D00]*/ + /** @stable ICU 2.6 */ + UBLOCK_MISCELLANEOUS_SYMBOLS_AND_ARROWS = 115, /*[2B00]*/ + /** @stable ICU 2.6 */ + UBLOCK_YIJING_HEXAGRAM_SYMBOLS = 116, /*[4DC0]*/ + /** @stable ICU 2.6 */ + UBLOCK_LINEAR_B_SYLLABARY = 117, /*[10000]*/ + /** @stable ICU 2.6 */ + UBLOCK_LINEAR_B_IDEOGRAMS = 118, /*[10080]*/ + /** @stable ICU 2.6 */ + UBLOCK_AEGEAN_NUMBERS = 119, /*[10100]*/ + /** @stable ICU 2.6 */ + UBLOCK_UGARITIC = 120, /*[10380]*/ + /** @stable ICU 2.6 */ + UBLOCK_SHAVIAN = 121, /*[10450]*/ + /** @stable ICU 2.6 */ + UBLOCK_OSMANYA = 122, /*[10480]*/ + /** @stable ICU 2.6 */ + UBLOCK_CYPRIOT_SYLLABARY = 123, /*[10800]*/ + /** @stable ICU 2.6 */ + UBLOCK_TAI_XUAN_JING_SYMBOLS = 124, /*[1D300]*/ + /** @stable ICU 2.6 */ + UBLOCK_VARIATION_SELECTORS_SUPPLEMENT = 125, /*[E0100]*/ + + /* New blocks in Unicode 4.1 */ + + /** @stable ICU 3.4 */ + UBLOCK_ANCIENT_GREEK_MUSICAL_NOTATION = 126, /*[1D200]*/ + /** @stable ICU 3.4 */ + UBLOCK_ANCIENT_GREEK_NUMBERS = 127, /*[10140]*/ + /** @stable ICU 3.4 */ + UBLOCK_ARABIC_SUPPLEMENT = 128, /*[0750]*/ + /** @stable ICU 3.4 */ + UBLOCK_BUGINESE = 129, /*[1A00]*/ + /** @stable ICU 3.4 */ + UBLOCK_CJK_STROKES = 130, /*[31C0]*/ + /** @stable ICU 3.4 */ + UBLOCK_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = 131, /*[1DC0]*/ + /** @stable ICU 3.4 */ + UBLOCK_COPTIC = 132, /*[2C80]*/ + /** @stable ICU 3.4 */ + UBLOCK_ETHIOPIC_EXTENDED = 133, /*[2D80]*/ + /** @stable ICU 3.4 */ + UBLOCK_ETHIOPIC_SUPPLEMENT = 134, /*[1380]*/ + /** @stable ICU 3.4 */ + UBLOCK_GEORGIAN_SUPPLEMENT = 135, /*[2D00]*/ + /** @stable ICU 3.4 */ + UBLOCK_GLAGOLITIC = 136, /*[2C00]*/ + /** @stable ICU 3.4 */ + UBLOCK_KHAROSHTHI = 137, /*[10A00]*/ + /** @stable ICU 3.4 */ + UBLOCK_MODIFIER_TONE_LETTERS = 138, /*[A700]*/ + /** @stable ICU 3.4 */ + UBLOCK_NEW_TAI_LUE = 139, /*[1980]*/ + /** @stable ICU 3.4 */ + UBLOCK_OLD_PERSIAN = 140, /*[103A0]*/ + /** @stable ICU 3.4 */ + UBLOCK_PHONETIC_EXTENSIONS_SUPPLEMENT = 141, /*[1D80]*/ + /** @stable ICU 3.4 */ + UBLOCK_SUPPLEMENTAL_PUNCTUATION = 142, /*[2E00]*/ + /** @stable ICU 3.4 */ + UBLOCK_SYLOTI_NAGRI = 143, /*[A800]*/ + /** @stable ICU 3.4 */ + UBLOCK_TIFINAGH = 144, /*[2D30]*/ + /** @stable ICU 3.4 */ + UBLOCK_VERTICAL_FORMS = 145, /*[FE10]*/ + + /* New blocks in Unicode 5.0 */ + + /** @stable ICU 3.6 */ + UBLOCK_NKO = 146, /*[07C0]*/ + /** @stable ICU 3.6 */ + UBLOCK_BALINESE = 147, /*[1B00]*/ + /** @stable ICU 3.6 */ + UBLOCK_LATIN_EXTENDED_C = 148, /*[2C60]*/ + /** @stable ICU 3.6 */ + UBLOCK_LATIN_EXTENDED_D = 149, /*[A720]*/ + /** @stable ICU 3.6 */ + UBLOCK_PHAGS_PA = 150, /*[A840]*/ + /** @stable ICU 3.6 */ + UBLOCK_PHOENICIAN = 151, /*[10900]*/ + /** @stable ICU 3.6 */ + UBLOCK_CUNEIFORM = 152, /*[12000]*/ + /** @stable ICU 3.6 */ + UBLOCK_CUNEIFORM_NUMBERS_AND_PUNCTUATION = 153, /*[12400]*/ + /** @stable ICU 3.6 */ + UBLOCK_COUNTING_ROD_NUMERALS = 154, /*[1D360]*/ + + /* New blocks in Unicode 5.1 */ + + /** @stable ICU 4.0 */ + UBLOCK_SUNDANESE = 155, /*[1B80]*/ + /** @stable ICU 4.0 */ + UBLOCK_LEPCHA = 156, /*[1C00]*/ + /** @stable ICU 4.0 */ + UBLOCK_OL_CHIKI = 157, /*[1C50]*/ + /** @stable ICU 4.0 */ + UBLOCK_CYRILLIC_EXTENDED_A = 158, /*[2DE0]*/ + /** @stable ICU 4.0 */ + UBLOCK_VAI = 159, /*[A500]*/ + /** @stable ICU 4.0 */ + UBLOCK_CYRILLIC_EXTENDED_B = 160, /*[A640]*/ + /** @stable ICU 4.0 */ + UBLOCK_SAURASHTRA = 161, /*[A880]*/ + /** @stable ICU 4.0 */ + UBLOCK_KAYAH_LI = 162, /*[A900]*/ + /** @stable ICU 4.0 */ + UBLOCK_REJANG = 163, /*[A930]*/ + /** @stable ICU 4.0 */ + UBLOCK_CHAM = 164, /*[AA00]*/ + /** @stable ICU 4.0 */ + UBLOCK_ANCIENT_SYMBOLS = 165, /*[10190]*/ + /** @stable ICU 4.0 */ + UBLOCK_PHAISTOS_DISC = 166, /*[101D0]*/ + /** @stable ICU 4.0 */ + UBLOCK_LYCIAN = 167, /*[10280]*/ + /** @stable ICU 4.0 */ + UBLOCK_CARIAN = 168, /*[102A0]*/ + /** @stable ICU 4.0 */ + UBLOCK_LYDIAN = 169, /*[10920]*/ + /** @stable ICU 4.0 */ + UBLOCK_MAHJONG_TILES = 170, /*[1F000]*/ + /** @stable ICU 4.0 */ + UBLOCK_DOMINO_TILES = 171, /*[1F030]*/ + + /* New blocks in Unicode 5.2 */ + + /** @stable ICU 4.4 */ + UBLOCK_SAMARITAN = 172, /*[0800]*/ + /** @stable ICU 4.4 */ + UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = 173, /*[18B0]*/ + /** @stable ICU 4.4 */ + UBLOCK_TAI_THAM = 174, /*[1A20]*/ + /** @stable ICU 4.4 */ + UBLOCK_VEDIC_EXTENSIONS = 175, /*[1CD0]*/ + /** @stable ICU 4.4 */ + UBLOCK_LISU = 176, /*[A4D0]*/ + /** @stable ICU 4.4 */ + UBLOCK_BAMUM = 177, /*[A6A0]*/ + /** @stable ICU 4.4 */ + UBLOCK_COMMON_INDIC_NUMBER_FORMS = 178, /*[A830]*/ + /** @stable ICU 4.4 */ + UBLOCK_DEVANAGARI_EXTENDED = 179, /*[A8E0]*/ + /** @stable ICU 4.4 */ + UBLOCK_HANGUL_JAMO_EXTENDED_A = 180, /*[A960]*/ + /** @stable ICU 4.4 */ + UBLOCK_JAVANESE = 181, /*[A980]*/ + /** @stable ICU 4.4 */ + UBLOCK_MYANMAR_EXTENDED_A = 182, /*[AA60]*/ + /** @stable ICU 4.4 */ + UBLOCK_TAI_VIET = 183, /*[AA80]*/ + /** @stable ICU 4.4 */ + UBLOCK_MEETEI_MAYEK = 184, /*[ABC0]*/ + /** @stable ICU 4.4 */ + UBLOCK_HANGUL_JAMO_EXTENDED_B = 185, /*[D7B0]*/ + /** @stable ICU 4.4 */ + UBLOCK_IMPERIAL_ARAMAIC = 186, /*[10840]*/ + /** @stable ICU 4.4 */ + UBLOCK_OLD_SOUTH_ARABIAN = 187, /*[10A60]*/ + /** @stable ICU 4.4 */ + UBLOCK_AVESTAN = 188, /*[10B00]*/ + /** @stable ICU 4.4 */ + UBLOCK_INSCRIPTIONAL_PARTHIAN = 189, /*[10B40]*/ + /** @stable ICU 4.4 */ + UBLOCK_INSCRIPTIONAL_PAHLAVI = 190, /*[10B60]*/ + /** @stable ICU 4.4 */ + UBLOCK_OLD_TURKIC = 191, /*[10C00]*/ + /** @stable ICU 4.4 */ + UBLOCK_RUMI_NUMERAL_SYMBOLS = 192, /*[10E60]*/ + /** @stable ICU 4.4 */ + UBLOCK_KAITHI = 193, /*[11080]*/ + /** @stable ICU 4.4 */ + UBLOCK_EGYPTIAN_HIEROGLYPHS = 194, /*[13000]*/ + /** @stable ICU 4.4 */ + UBLOCK_ENCLOSED_ALPHANUMERIC_SUPPLEMENT = 195, /*[1F100]*/ + /** @stable ICU 4.4 */ + UBLOCK_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = 196, /*[1F200]*/ + /** @stable ICU 4.4 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = 197, /*[2A700]*/ + + /* New blocks in Unicode 6.0 */ + + /** @stable ICU 4.6 */ + UBLOCK_MANDAIC = 198, /*[0840]*/ + /** @stable ICU 4.6 */ + UBLOCK_BATAK = 199, /*[1BC0]*/ + /** @stable ICU 4.6 */ + UBLOCK_ETHIOPIC_EXTENDED_A = 200, /*[AB00]*/ + /** @stable ICU 4.6 */ + UBLOCK_BRAHMI = 201, /*[11000]*/ + /** @stable ICU 4.6 */ + UBLOCK_BAMUM_SUPPLEMENT = 202, /*[16800]*/ + /** @stable ICU 4.6 */ + UBLOCK_KANA_SUPPLEMENT = 203, /*[1B000]*/ + /** @stable ICU 4.6 */ + UBLOCK_PLAYING_CARDS = 204, /*[1F0A0]*/ + /** @stable ICU 4.6 */ + UBLOCK_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = 205, /*[1F300]*/ + /** @stable ICU 4.6 */ + UBLOCK_EMOTICONS = 206, /*[1F600]*/ + /** @stable ICU 4.6 */ + UBLOCK_TRANSPORT_AND_MAP_SYMBOLS = 207, /*[1F680]*/ + /** @stable ICU 4.6 */ + UBLOCK_ALCHEMICAL_SYMBOLS = 208, /*[1F700]*/ + /** @stable ICU 4.6 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = 209, /*[2B740]*/ + + /* New blocks in Unicode 6.1 */ + + /** @stable ICU 49 */ + UBLOCK_ARABIC_EXTENDED_A = 210, /*[08A0]*/ + /** @stable ICU 49 */ + UBLOCK_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = 211, /*[1EE00]*/ + /** @stable ICU 49 */ + UBLOCK_CHAKMA = 212, /*[11100]*/ + /** @stable ICU 49 */ + UBLOCK_MEETEI_MAYEK_EXTENSIONS = 213, /*[AAE0]*/ + /** @stable ICU 49 */ + UBLOCK_MEROITIC_CURSIVE = 214, /*[109A0]*/ + /** @stable ICU 49 */ + UBLOCK_MEROITIC_HIEROGLYPHS = 215, /*[10980]*/ + /** @stable ICU 49 */ + UBLOCK_MIAO = 216, /*[16F00]*/ + /** @stable ICU 49 */ + UBLOCK_SHARADA = 217, /*[11180]*/ + /** @stable ICU 49 */ + UBLOCK_SORA_SOMPENG = 218, /*[110D0]*/ + /** @stable ICU 49 */ + UBLOCK_SUNDANESE_SUPPLEMENT = 219, /*[1CC0]*/ + /** @stable ICU 49 */ + UBLOCK_TAKRI = 220, /*[11680]*/ + + /* New blocks in Unicode 7.0 */ + + /** @stable ICU 54 */ + UBLOCK_BASSA_VAH = 221, /*[16AD0]*/ + /** @stable ICU 54 */ + UBLOCK_CAUCASIAN_ALBANIAN = 222, /*[10530]*/ + /** @stable ICU 54 */ + UBLOCK_COPTIC_EPACT_NUMBERS = 223, /*[102E0]*/ + /** @stable ICU 54 */ + UBLOCK_COMBINING_DIACRITICAL_MARKS_EXTENDED = 224, /*[1AB0]*/ + /** @stable ICU 54 */ + UBLOCK_DUPLOYAN = 225, /*[1BC00]*/ + /** @stable ICU 54 */ + UBLOCK_ELBASAN = 226, /*[10500]*/ + /** @stable ICU 54 */ + UBLOCK_GEOMETRIC_SHAPES_EXTENDED = 227, /*[1F780]*/ + /** @stable ICU 54 */ + UBLOCK_GRANTHA = 228, /*[11300]*/ + /** @stable ICU 54 */ + UBLOCK_KHOJKI = 229, /*[11200]*/ + /** @stable ICU 54 */ + UBLOCK_KHUDAWADI = 230, /*[112B0]*/ + /** @stable ICU 54 */ + UBLOCK_LATIN_EXTENDED_E = 231, /*[AB30]*/ + /** @stable ICU 54 */ + UBLOCK_LINEAR_A = 232, /*[10600]*/ + /** @stable ICU 54 */ + UBLOCK_MAHAJANI = 233, /*[11150]*/ + /** @stable ICU 54 */ + UBLOCK_MANICHAEAN = 234, /*[10AC0]*/ + /** @stable ICU 54 */ + UBLOCK_MENDE_KIKAKUI = 235, /*[1E800]*/ + /** @stable ICU 54 */ + UBLOCK_MODI = 236, /*[11600]*/ + /** @stable ICU 54 */ + UBLOCK_MRO = 237, /*[16A40]*/ + /** @stable ICU 54 */ + UBLOCK_MYANMAR_EXTENDED_B = 238, /*[A9E0]*/ + /** @stable ICU 54 */ + UBLOCK_NABATAEAN = 239, /*[10880]*/ + /** @stable ICU 54 */ + UBLOCK_OLD_NORTH_ARABIAN = 240, /*[10A80]*/ + /** @stable ICU 54 */ + UBLOCK_OLD_PERMIC = 241, /*[10350]*/ + /** @stable ICU 54 */ + UBLOCK_ORNAMENTAL_DINGBATS = 242, /*[1F650]*/ + /** @stable ICU 54 */ + UBLOCK_PAHAWH_HMONG = 243, /*[16B00]*/ + /** @stable ICU 54 */ + UBLOCK_PALMYRENE = 244, /*[10860]*/ + /** @stable ICU 54 */ + UBLOCK_PAU_CIN_HAU = 245, /*[11AC0]*/ + /** @stable ICU 54 */ + UBLOCK_PSALTER_PAHLAVI = 246, /*[10B80]*/ + /** @stable ICU 54 */ + UBLOCK_SHORTHAND_FORMAT_CONTROLS = 247, /*[1BCA0]*/ + /** @stable ICU 54 */ + UBLOCK_SIDDHAM = 248, /*[11580]*/ + /** @stable ICU 54 */ + UBLOCK_SINHALA_ARCHAIC_NUMBERS = 249, /*[111E0]*/ + /** @stable ICU 54 */ + UBLOCK_SUPPLEMENTAL_ARROWS_C = 250, /*[1F800]*/ + /** @stable ICU 54 */ + UBLOCK_TIRHUTA = 251, /*[11480]*/ + /** @stable ICU 54 */ + UBLOCK_WARANG_CITI = 252, /*[118A0]*/ + + /* New blocks in Unicode 8.0 */ + + /** @stable ICU 56 */ + UBLOCK_AHOM = 253, /*[11700]*/ + /** @stable ICU 56 */ + UBLOCK_ANATOLIAN_HIEROGLYPHS = 254, /*[14400]*/ + /** @stable ICU 56 */ + UBLOCK_CHEROKEE_SUPPLEMENT = 255, /*[AB70]*/ + /** @stable ICU 56 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E = 256, /*[2B820]*/ + /** @stable ICU 56 */ + UBLOCK_EARLY_DYNASTIC_CUNEIFORM = 257, /*[12480]*/ + /** @stable ICU 56 */ + UBLOCK_HATRAN = 258, /*[108E0]*/ + /** @stable ICU 56 */ + UBLOCK_MULTANI = 259, /*[11280]*/ + /** @stable ICU 56 */ + UBLOCK_OLD_HUNGARIAN = 260, /*[10C80]*/ + /** @stable ICU 56 */ + UBLOCK_SUPPLEMENTAL_SYMBOLS_AND_PICTOGRAPHS = 261, /*[1F900]*/ + /** @stable ICU 56 */ + UBLOCK_SUTTON_SIGNWRITING = 262, /*[1D800]*/ + + /* New blocks in Unicode 9.0 */ + + /** @stable ICU 58 */ + UBLOCK_ADLAM = 263, /*[1E900]*/ + /** @stable ICU 58 */ + UBLOCK_BHAIKSUKI = 264, /*[11C00]*/ + /** @stable ICU 58 */ + UBLOCK_CYRILLIC_EXTENDED_C = 265, /*[1C80]*/ + /** @stable ICU 58 */ + UBLOCK_GLAGOLITIC_SUPPLEMENT = 266, /*[1E000]*/ + /** @stable ICU 58 */ + UBLOCK_IDEOGRAPHIC_SYMBOLS_AND_PUNCTUATION = 267, /*[16FE0]*/ + /** @stable ICU 58 */ + UBLOCK_MARCHEN = 268, /*[11C70]*/ + /** @stable ICU 58 */ + UBLOCK_MONGOLIAN_SUPPLEMENT = 269, /*[11660]*/ + /** @stable ICU 58 */ + UBLOCK_NEWA = 270, /*[11400]*/ + /** @stable ICU 58 */ + UBLOCK_OSAGE = 271, /*[104B0]*/ + /** @stable ICU 58 */ + UBLOCK_TANGUT = 272, /*[17000]*/ + /** @stable ICU 58 */ + UBLOCK_TANGUT_COMPONENTS = 273, /*[18800]*/ + + // New blocks in Unicode 10.0 + + /** @stable ICU 60 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_F = 274, /*[2CEB0]*/ + /** @stable ICU 60 */ + UBLOCK_KANA_EXTENDED_A = 275, /*[1B100]*/ + /** @stable ICU 60 */ + UBLOCK_MASARAM_GONDI = 276, /*[11D00]*/ + /** @stable ICU 60 */ + UBLOCK_NUSHU = 277, /*[1B170]*/ + /** @stable ICU 60 */ + UBLOCK_SOYOMBO = 278, /*[11A50]*/ + /** @stable ICU 60 */ + UBLOCK_SYRIAC_SUPPLEMENT = 279, /*[0860]*/ + /** @stable ICU 60 */ + UBLOCK_ZANABAZAR_SQUARE = 280, /*[11A00]*/ + + // New blocks in Unicode 11.0 + + /** @stable ICU 62 */ + UBLOCK_CHESS_SYMBOLS = 281, /*[1FA00]*/ + /** @stable ICU 62 */ + UBLOCK_DOGRA = 282, /*[11800]*/ + /** @stable ICU 62 */ + UBLOCK_GEORGIAN_EXTENDED = 283, /*[1C90]*/ + /** @stable ICU 62 */ + UBLOCK_GUNJALA_GONDI = 284, /*[11D60]*/ + /** @stable ICU 62 */ + UBLOCK_HANIFI_ROHINGYA = 285, /*[10D00]*/ + /** @stable ICU 62 */ + UBLOCK_INDIC_SIYAQ_NUMBERS = 286, /*[1EC70]*/ + /** @stable ICU 62 */ + UBLOCK_MAKASAR = 287, /*[11EE0]*/ + /** @stable ICU 62 */ + UBLOCK_MAYAN_NUMERALS = 288, /*[1D2E0]*/ + /** @stable ICU 62 */ + UBLOCK_MEDEFAIDRIN = 289, /*[16E40]*/ + /** @stable ICU 62 */ + UBLOCK_OLD_SOGDIAN = 290, /*[10F00]*/ + /** @stable ICU 62 */ + UBLOCK_SOGDIAN = 291, /*[10F30]*/ + + // New blocks in Unicode 12.0 + + /** @stable ICU 64 */ + UBLOCK_EGYPTIAN_HIEROGLYPH_FORMAT_CONTROLS = 292, /*[13430]*/ + /** @stable ICU 64 */ + UBLOCK_ELYMAIC = 293, /*[10FE0]*/ + /** @stable ICU 64 */ + UBLOCK_NANDINAGARI = 294, /*[119A0]*/ + /** @stable ICU 64 */ + UBLOCK_NYIAKENG_PUACHUE_HMONG = 295, /*[1E100]*/ + /** @stable ICU 64 */ + UBLOCK_OTTOMAN_SIYAQ_NUMBERS = 296, /*[1ED00]*/ + /** @stable ICU 64 */ + UBLOCK_SMALL_KANA_EXTENSION = 297, /*[1B130]*/ + /** @stable ICU 64 */ + UBLOCK_SYMBOLS_AND_PICTOGRAPHS_EXTENDED_A = 298, /*[1FA70]*/ + /** @stable ICU 64 */ + UBLOCK_TAMIL_SUPPLEMENT = 299, /*[11FC0]*/ + /** @stable ICU 64 */ + UBLOCK_WANCHO = 300, /*[1E2C0]*/ + + // New blocks in Unicode 13.0 + + /** @stable ICU 66 */ + UBLOCK_CHORASMIAN = 301, /*[10FB0]*/ + /** @stable ICU 66 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_G = 302, /*[30000]*/ + /** @stable ICU 66 */ + UBLOCK_DIVES_AKURU = 303, /*[11900]*/ + /** @stable ICU 66 */ + UBLOCK_KHITAN_SMALL_SCRIPT = 304, /*[18B00]*/ + /** @stable ICU 66 */ + UBLOCK_LISU_SUPPLEMENT = 305, /*[11FB0]*/ + /** @stable ICU 66 */ + UBLOCK_SYMBOLS_FOR_LEGACY_COMPUTING = 306, /*[1FB00]*/ + /** @stable ICU 66 */ + UBLOCK_TANGUT_SUPPLEMENT = 307, /*[18D00]*/ + /** @stable ICU 66 */ + UBLOCK_YEZIDI = 308, /*[10E80]*/ + + // New blocks in Unicode 14.0 + + /** @stable ICU 70 */ + UBLOCK_ARABIC_EXTENDED_B = 309, /*[0870]*/ + /** @stable ICU 70 */ + UBLOCK_CYPRO_MINOAN = 310, /*[12F90]*/ + /** @stable ICU 70 */ + UBLOCK_ETHIOPIC_EXTENDED_B = 311, /*[1E7E0]*/ + /** @stable ICU 70 */ + UBLOCK_KANA_EXTENDED_B = 312, /*[1AFF0]*/ + /** @stable ICU 70 */ + UBLOCK_LATIN_EXTENDED_F = 313, /*[10780]*/ + /** @stable ICU 70 */ + UBLOCK_LATIN_EXTENDED_G = 314, /*[1DF00]*/ + /** @stable ICU 70 */ + UBLOCK_OLD_UYGHUR = 315, /*[10F70]*/ + /** @stable ICU 70 */ + UBLOCK_TANGSA = 316, /*[16A70]*/ + /** @stable ICU 70 */ + UBLOCK_TOTO = 317, /*[1E290]*/ + /** @stable ICU 70 */ + UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED_A = 318, /*[11AB0]*/ + /** @stable ICU 70 */ + UBLOCK_VITHKUQI = 319, /*[10570]*/ + /** @stable ICU 70 */ + UBLOCK_ZNAMENNY_MUSICAL_NOTATION = 320, /*[1CF00]*/ + + // New blocks in Unicode 15.0 + + /** @stable ICU 72 */ + UBLOCK_ARABIC_EXTENDED_C = 321, /*[10EC0]*/ + /** @stable ICU 72 */ + UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_H = 322, /*[31350]*/ + /** @stable ICU 72 */ + UBLOCK_CYRILLIC_EXTENDED_D = 323, /*[1E030]*/ + /** @stable ICU 72 */ + UBLOCK_DEVANAGARI_EXTENDED_A = 324, /*[11B00]*/ + /** @stable ICU 72 */ + UBLOCK_KAKTOVIK_NUMERALS = 325, /*[1D2C0]*/ + /** @stable ICU 72 */ + UBLOCK_KAWI = 326, /*[11F00]*/ + /** @stable ICU 72 */ + UBLOCK_NAG_MUNDARI = 327, /*[1E4D0]*/ + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UBlockCode value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BLOCK). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UBLOCK_COUNT = 328, +#endif // U_HIDE_DEPRECATED_API + + /** @stable ICU 2.0 */ + UBLOCK_INVALID_CODE=-1 +}; + +/** @stable ICU 2.0 */ +typedef enum UBlockCode UBlockCode; + +/** + * East Asian Width constants. + * + * @see UCHAR_EAST_ASIAN_WIDTH + * @see u_getIntPropertyValue + * @stable ICU 2.2 + */ +typedef enum UEastAsianWidth { + /* + * Note: UEastAsianWidth constants are parsed by preparseucd.py. + * It matches lines like + * U_EA_ + */ + + U_EA_NEUTRAL, /*[N]*/ + U_EA_AMBIGUOUS, /*[A]*/ + U_EA_HALFWIDTH, /*[H]*/ + U_EA_FULLWIDTH, /*[F]*/ + U_EA_NARROW, /*[Na]*/ + U_EA_WIDE, /*[W]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UEastAsianWidth value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_EAST_ASIAN_WIDTH). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_EA_COUNT +#endif // U_HIDE_DEPRECATED_API +} UEastAsianWidth; + +/** + * Selector constants for u_charName(). + * u_charName() returns the "modern" name of a + * Unicode character; or the name that was defined in + * Unicode version 1.0, before the Unicode standard merged + * with ISO-10646; or an "extended" name that gives each + * Unicode code point a unique name. + * + * @see u_charName + * @stable ICU 2.0 + */ +typedef enum UCharNameChoice { + /** Unicode character name (Name property). @stable ICU 2.0 */ + U_UNICODE_CHAR_NAME, +#ifndef U_HIDE_DEPRECATED_API + /** + * The Unicode_1_Name property value which is of little practical value. + * Beginning with ICU 49, ICU APIs return an empty string for this name choice. + * @deprecated ICU 49 + */ + U_UNICODE_10_CHAR_NAME, +#endif /* U_HIDE_DEPRECATED_API */ + /** Standard or synthetic character name. @stable ICU 2.0 */ + U_EXTENDED_CHAR_NAME = U_UNICODE_CHAR_NAME+2, + /** Corrected name from NameAliases.txt. @stable ICU 4.4 */ + U_CHAR_NAME_ALIAS, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UCharNameChoice value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_CHAR_NAME_CHOICE_COUNT +#endif // U_HIDE_DEPRECATED_API +} UCharNameChoice; + +/** + * Selector constants for u_getPropertyName() and + * u_getPropertyValueName(). These selectors are used to choose which + * name is returned for a given property or value. All properties and + * values have a long name. Most have a short name, but some do not. + * Unicode allows for additional names, beyond the long and short + * name, which would be indicated by U_LONG_PROPERTY_NAME + i, where + * i=1, 2,... + * + * @see u_getPropertyName() + * @see u_getPropertyValueName() + * @stable ICU 2.4 + */ +typedef enum UPropertyNameChoice { + U_SHORT_PROPERTY_NAME, + U_LONG_PROPERTY_NAME, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UPropertyNameChoice value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_PROPERTY_NAME_CHOICE_COUNT +#endif // U_HIDE_DEPRECATED_API +} UPropertyNameChoice; + +/** + * Decomposition Type constants. + * + * @see UCHAR_DECOMPOSITION_TYPE + * @stable ICU 2.2 + */ +typedef enum UDecompositionType { + /* + * Note: UDecompositionType constants are parsed by preparseucd.py. + * It matches lines like + * U_DT_ + */ + + U_DT_NONE, /*[none]*/ + U_DT_CANONICAL, /*[can]*/ + U_DT_COMPAT, /*[com]*/ + U_DT_CIRCLE, /*[enc]*/ + U_DT_FINAL, /*[fin]*/ + U_DT_FONT, /*[font]*/ + U_DT_FRACTION, /*[fra]*/ + U_DT_INITIAL, /*[init]*/ + U_DT_ISOLATED, /*[iso]*/ + U_DT_MEDIAL, /*[med]*/ + U_DT_NARROW, /*[nar]*/ + U_DT_NOBREAK, /*[nb]*/ + U_DT_SMALL, /*[sml]*/ + U_DT_SQUARE, /*[sqr]*/ + U_DT_SUB, /*[sub]*/ + U_DT_SUPER, /*[sup]*/ + U_DT_VERTICAL, /*[vert]*/ + U_DT_WIDE, /*[wide]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDecompositionType value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_DECOMPOSITION_TYPE). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_DT_COUNT /* 18 */ +#endif // U_HIDE_DEPRECATED_API +} UDecompositionType; + +/** + * Joining Type constants. + * + * @see UCHAR_JOINING_TYPE + * @stable ICU 2.2 + */ +typedef enum UJoiningType { + /* + * Note: UJoiningType constants are parsed by preparseucd.py. + * It matches lines like + * U_JT_ + */ + + U_JT_NON_JOINING, /*[U]*/ + U_JT_JOIN_CAUSING, /*[C]*/ + U_JT_DUAL_JOINING, /*[D]*/ + U_JT_LEFT_JOINING, /*[L]*/ + U_JT_RIGHT_JOINING, /*[R]*/ + U_JT_TRANSPARENT, /*[T]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UJoiningType value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_JOINING_TYPE). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_JT_COUNT /* 6 */ +#endif // U_HIDE_DEPRECATED_API +} UJoiningType; + +/** + * Joining Group constants. + * + * @see UCHAR_JOINING_GROUP + * @stable ICU 2.2 + */ +typedef enum UJoiningGroup { + /* + * Note: UJoiningGroup constants are parsed by preparseucd.py. + * It matches lines like + * U_JG_ + */ + + U_JG_NO_JOINING_GROUP, + U_JG_AIN, + U_JG_ALAPH, + U_JG_ALEF, + U_JG_BEH, + U_JG_BETH, + U_JG_DAL, + U_JG_DALATH_RISH, + U_JG_E, + U_JG_FEH, + U_JG_FINAL_SEMKATH, + U_JG_GAF, + U_JG_GAMAL, + U_JG_HAH, + U_JG_TEH_MARBUTA_GOAL, /**< @stable ICU 4.6 */ + U_JG_HAMZA_ON_HEH_GOAL=U_JG_TEH_MARBUTA_GOAL, + U_JG_HE, + U_JG_HEH, + U_JG_HEH_GOAL, + U_JG_HETH, + U_JG_KAF, + U_JG_KAPH, + U_JG_KNOTTED_HEH, + U_JG_LAM, + U_JG_LAMADH, + U_JG_MEEM, + U_JG_MIM, + U_JG_NOON, + U_JG_NUN, + U_JG_PE, + U_JG_QAF, + U_JG_QAPH, + U_JG_REH, + U_JG_REVERSED_PE, + U_JG_SAD, + U_JG_SADHE, + U_JG_SEEN, + U_JG_SEMKATH, + U_JG_SHIN, + U_JG_SWASH_KAF, + U_JG_SYRIAC_WAW, + U_JG_TAH, + U_JG_TAW, + U_JG_TEH_MARBUTA, + U_JG_TETH, + U_JG_WAW, + U_JG_YEH, + U_JG_YEH_BARREE, + U_JG_YEH_WITH_TAIL, + U_JG_YUDH, + U_JG_YUDH_HE, + U_JG_ZAIN, + U_JG_FE, /**< @stable ICU 2.6 */ + U_JG_KHAPH, /**< @stable ICU 2.6 */ + U_JG_ZHAIN, /**< @stable ICU 2.6 */ + U_JG_BURUSHASKI_YEH_BARREE, /**< @stable ICU 4.0 */ + U_JG_FARSI_YEH, /**< @stable ICU 4.4 */ + U_JG_NYA, /**< @stable ICU 4.4 */ + U_JG_ROHINGYA_YEH, /**< @stable ICU 49 */ + U_JG_MANICHAEAN_ALEPH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_AYIN, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_BETH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_DALETH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_DHAMEDH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_FIVE, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_GIMEL, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_HETH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_HUNDRED, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_KAPH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_LAMEDH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_MEM, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_NUN, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_ONE, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_PE, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_QOPH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_RESH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_SADHE, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_SAMEKH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_TAW, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_TEN, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_TETH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_THAMEDH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_TWENTY, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_WAW, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_YODH, /**< @stable ICU 54 */ + U_JG_MANICHAEAN_ZAYIN, /**< @stable ICU 54 */ + U_JG_STRAIGHT_WAW, /**< @stable ICU 54 */ + U_JG_AFRICAN_FEH, /**< @stable ICU 58 */ + U_JG_AFRICAN_NOON, /**< @stable ICU 58 */ + U_JG_AFRICAN_QAF, /**< @stable ICU 58 */ + + U_JG_MALAYALAM_BHA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_JA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_LLA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_LLLA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_NGA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_NNA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_NNNA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_NYA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_RA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_SSA, /**< @stable ICU 60 */ + U_JG_MALAYALAM_TTA, /**< @stable ICU 60 */ + + U_JG_HANIFI_ROHINGYA_KINNA_YA, /**< @stable ICU 62 */ + U_JG_HANIFI_ROHINGYA_PA, /**< @stable ICU 62 */ + + U_JG_THIN_YEH, /**< @stable ICU 70 */ + U_JG_VERTICAL_TAIL, /**< @stable ICU 70 */ + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UJoiningGroup value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_JOINING_GROUP). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_JG_COUNT +#endif // U_HIDE_DEPRECATED_API +} UJoiningGroup; + +/** + * Grapheme Cluster Break constants. + * + * @see UCHAR_GRAPHEME_CLUSTER_BREAK + * @stable ICU 3.4 + */ +typedef enum UGraphemeClusterBreak { + /* + * Note: UGraphemeClusterBreak constants are parsed by preparseucd.py. + * It matches lines like + * U_GCB_ + */ + + U_GCB_OTHER = 0, /*[XX]*/ + U_GCB_CONTROL = 1, /*[CN]*/ + U_GCB_CR = 2, /*[CR]*/ + U_GCB_EXTEND = 3, /*[EX]*/ + U_GCB_L = 4, /*[L]*/ + U_GCB_LF = 5, /*[LF]*/ + U_GCB_LV = 6, /*[LV]*/ + U_GCB_LVT = 7, /*[LVT]*/ + U_GCB_T = 8, /*[T]*/ + U_GCB_V = 9, /*[V]*/ + /** @stable ICU 4.0 */ + U_GCB_SPACING_MARK = 10, /*[SM]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ + /** @stable ICU 4.0 */ + U_GCB_PREPEND = 11, /*[PP]*/ + /** @stable ICU 50 */ + U_GCB_REGIONAL_INDICATOR = 12, /*[RI]*/ /* new in Unicode 6.2/ICU 50 */ + /** @stable ICU 58 */ + U_GCB_E_BASE = 13, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ + /** @stable ICU 58 */ + U_GCB_E_BASE_GAZ = 14, /*[EBG]*/ + /** @stable ICU 58 */ + U_GCB_E_MODIFIER = 15, /*[EM]*/ + /** @stable ICU 58 */ + U_GCB_GLUE_AFTER_ZWJ = 16, /*[GAZ]*/ + /** @stable ICU 58 */ + U_GCB_ZWJ = 17, /*[ZWJ]*/ + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UGraphemeClusterBreak value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_GRAPHEME_CLUSTER_BREAK). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_GCB_COUNT = 18 +#endif // U_HIDE_DEPRECATED_API +} UGraphemeClusterBreak; + +/** + * Word Break constants. + * (UWordBreak is a pre-existing enum type in ubrk.h for word break status tags.) + * + * @see UCHAR_WORD_BREAK + * @stable ICU 3.4 + */ +typedef enum UWordBreakValues { + /* + * Note: UWordBreakValues constants are parsed by preparseucd.py. + * It matches lines like + * U_WB_ + */ + + U_WB_OTHER = 0, /*[XX]*/ + U_WB_ALETTER = 1, /*[LE]*/ + U_WB_FORMAT = 2, /*[FO]*/ + U_WB_KATAKANA = 3, /*[KA]*/ + U_WB_MIDLETTER = 4, /*[ML]*/ + U_WB_MIDNUM = 5, /*[MN]*/ + U_WB_NUMERIC = 6, /*[NU]*/ + U_WB_EXTENDNUMLET = 7, /*[EX]*/ + /** @stable ICU 4.0 */ + U_WB_CR = 8, /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ + /** @stable ICU 4.0 */ + U_WB_EXTEND = 9, /*[Extend]*/ + /** @stable ICU 4.0 */ + U_WB_LF = 10, /*[LF]*/ + /** @stable ICU 4.0 */ + U_WB_MIDNUMLET =11, /*[MB]*/ + /** @stable ICU 4.0 */ + U_WB_NEWLINE =12, /*[NL]*/ + /** @stable ICU 50 */ + U_WB_REGIONAL_INDICATOR = 13, /*[RI]*/ /* new in Unicode 6.2/ICU 50 */ + /** @stable ICU 52 */ + U_WB_HEBREW_LETTER = 14, /*[HL]*/ /* from here on: new in Unicode 6.3/ICU 52 */ + /** @stable ICU 52 */ + U_WB_SINGLE_QUOTE = 15, /*[SQ]*/ + /** @stable ICU 52 */ + U_WB_DOUBLE_QUOTE = 16, /*[DQ]*/ + /** @stable ICU 58 */ + U_WB_E_BASE = 17, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ + /** @stable ICU 58 */ + U_WB_E_BASE_GAZ = 18, /*[EBG]*/ + /** @stable ICU 58 */ + U_WB_E_MODIFIER = 19, /*[EM]*/ + /** @stable ICU 58 */ + U_WB_GLUE_AFTER_ZWJ = 20, /*[GAZ]*/ + /** @stable ICU 58 */ + U_WB_ZWJ = 21, /*[ZWJ]*/ + /** @stable ICU 62 */ + U_WB_WSEGSPACE = 22, /*[WSEGSPACE]*/ + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UWordBreakValues value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_WORD_BREAK). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_WB_COUNT = 23 +#endif // U_HIDE_DEPRECATED_API +} UWordBreakValues; + +/** + * Sentence Break constants. + * + * @see UCHAR_SENTENCE_BREAK + * @stable ICU 3.4 + */ +typedef enum USentenceBreak { + /* + * Note: USentenceBreak constants are parsed by preparseucd.py. + * It matches lines like + * U_SB_ + */ + + U_SB_OTHER = 0, /*[XX]*/ + U_SB_ATERM = 1, /*[AT]*/ + U_SB_CLOSE = 2, /*[CL]*/ + U_SB_FORMAT = 3, /*[FO]*/ + U_SB_LOWER = 4, /*[LO]*/ + U_SB_NUMERIC = 5, /*[NU]*/ + U_SB_OLETTER = 6, /*[LE]*/ + U_SB_SEP = 7, /*[SE]*/ + U_SB_SP = 8, /*[SP]*/ + U_SB_STERM = 9, /*[ST]*/ + U_SB_UPPER = 10, /*[UP]*/ + U_SB_CR = 11, /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ + U_SB_EXTEND = 12, /*[EX]*/ + U_SB_LF = 13, /*[LF]*/ + U_SB_SCONTINUE = 14, /*[SC]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal USentenceBreak value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_SENTENCE_BREAK). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_SB_COUNT = 15 +#endif // U_HIDE_DEPRECATED_API +} USentenceBreak; + +/** + * Line Break constants. + * + * @see UCHAR_LINE_BREAK + * @stable ICU 2.2 + */ +typedef enum ULineBreak { + /* + * Note: ULineBreak constants are parsed by preparseucd.py. + * It matches lines like + * U_LB_ + */ + + U_LB_UNKNOWN = 0, /*[XX]*/ + U_LB_AMBIGUOUS = 1, /*[AI]*/ + U_LB_ALPHABETIC = 2, /*[AL]*/ + U_LB_BREAK_BOTH = 3, /*[B2]*/ + U_LB_BREAK_AFTER = 4, /*[BA]*/ + U_LB_BREAK_BEFORE = 5, /*[BB]*/ + U_LB_MANDATORY_BREAK = 6, /*[BK]*/ + U_LB_CONTINGENT_BREAK = 7, /*[CB]*/ + U_LB_CLOSE_PUNCTUATION = 8, /*[CL]*/ + U_LB_COMBINING_MARK = 9, /*[CM]*/ + U_LB_CARRIAGE_RETURN = 10, /*[CR]*/ + U_LB_EXCLAMATION = 11, /*[EX]*/ + U_LB_GLUE = 12, /*[GL]*/ + U_LB_HYPHEN = 13, /*[HY]*/ + U_LB_IDEOGRAPHIC = 14, /*[ID]*/ + /** Renamed from the misspelled "inseperable" in Unicode 4.0.1/ICU 3.0 @stable ICU 3.0 */ + U_LB_INSEPARABLE = 15, /*[IN]*/ + U_LB_INSEPERABLE = U_LB_INSEPARABLE, + U_LB_INFIX_NUMERIC = 16, /*[IS]*/ + U_LB_LINE_FEED = 17, /*[LF]*/ + U_LB_NONSTARTER = 18, /*[NS]*/ + U_LB_NUMERIC = 19, /*[NU]*/ + U_LB_OPEN_PUNCTUATION = 20, /*[OP]*/ + U_LB_POSTFIX_NUMERIC = 21, /*[PO]*/ + U_LB_PREFIX_NUMERIC = 22, /*[PR]*/ + U_LB_QUOTATION = 23, /*[QU]*/ + U_LB_COMPLEX_CONTEXT = 24, /*[SA]*/ + U_LB_SURROGATE = 25, /*[SG]*/ + U_LB_SPACE = 26, /*[SP]*/ + U_LB_BREAK_SYMBOLS = 27, /*[SY]*/ + U_LB_ZWSPACE = 28, /*[ZW]*/ + /** @stable ICU 2.6 */ + U_LB_NEXT_LINE = 29, /*[NL]*/ /* from here on: new in Unicode 4/ICU 2.6 */ + /** @stable ICU 2.6 */ + U_LB_WORD_JOINER = 30, /*[WJ]*/ + /** @stable ICU 3.4 */ + U_LB_H2 = 31, /*[H2]*/ /* from here on: new in Unicode 4.1/ICU 3.4 */ + /** @stable ICU 3.4 */ + U_LB_H3 = 32, /*[H3]*/ + /** @stable ICU 3.4 */ + U_LB_JL = 33, /*[JL]*/ + /** @stable ICU 3.4 */ + U_LB_JT = 34, /*[JT]*/ + /** @stable ICU 3.4 */ + U_LB_JV = 35, /*[JV]*/ + /** @stable ICU 4.4 */ + U_LB_CLOSE_PARENTHESIS = 36, /*[CP]*/ /* new in Unicode 5.2/ICU 4.4 */ + /** @stable ICU 49 */ + U_LB_CONDITIONAL_JAPANESE_STARTER = 37,/*[CJ]*/ /* new in Unicode 6.1/ICU 49 */ + /** @stable ICU 49 */ + U_LB_HEBREW_LETTER = 38, /*[HL]*/ /* new in Unicode 6.1/ICU 49 */ + /** @stable ICU 50 */ + U_LB_REGIONAL_INDICATOR = 39,/*[RI]*/ /* new in Unicode 6.2/ICU 50 */ + /** @stable ICU 58 */ + U_LB_E_BASE = 40, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ + /** @stable ICU 58 */ + U_LB_E_MODIFIER = 41, /*[EM]*/ + /** @stable ICU 58 */ + U_LB_ZWJ = 42, /*[ZWJ]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal ULineBreak value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_LINE_BREAK). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_LB_COUNT = 43 +#endif // U_HIDE_DEPRECATED_API +} ULineBreak; + +/** + * Numeric Type constants. + * + * @see UCHAR_NUMERIC_TYPE + * @stable ICU 2.2 + */ +typedef enum UNumericType { + /* + * Note: UNumericType constants are parsed by preparseucd.py. + * It matches lines like + * U_NT_ + */ + + U_NT_NONE, /*[None]*/ + U_NT_DECIMAL, /*[de]*/ + U_NT_DIGIT, /*[di]*/ + U_NT_NUMERIC, /*[nu]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UNumericType value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_NUMERIC_TYPE). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_NT_COUNT +#endif // U_HIDE_DEPRECATED_API +} UNumericType; + +/** + * Hangul Syllable Type constants. + * + * @see UCHAR_HANGUL_SYLLABLE_TYPE + * @stable ICU 2.6 + */ +typedef enum UHangulSyllableType { + /* + * Note: UHangulSyllableType constants are parsed by preparseucd.py. + * It matches lines like + * U_HST_ + */ + + U_HST_NOT_APPLICABLE, /*[NA]*/ + U_HST_LEADING_JAMO, /*[L]*/ + U_HST_VOWEL_JAMO, /*[V]*/ + U_HST_TRAILING_JAMO, /*[T]*/ + U_HST_LV_SYLLABLE, /*[LV]*/ + U_HST_LVT_SYLLABLE, /*[LVT]*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UHangulSyllableType value. + * The highest value is available via u_getIntPropertyMaxValue(UCHAR_HANGUL_SYLLABLE_TYPE). + * + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + U_HST_COUNT +#endif // U_HIDE_DEPRECATED_API +} UHangulSyllableType; + +/** + * Indic Positional Category constants. + * + * @see UCHAR_INDIC_POSITIONAL_CATEGORY + * @stable ICU 63 + */ +typedef enum UIndicPositionalCategory { + /* + * Note: UIndicPositionalCategory constants are parsed by preparseucd.py. + * It matches lines like + * U_INPC_ + */ + + /** @stable ICU 63 */ + U_INPC_NA, + /** @stable ICU 63 */ + U_INPC_BOTTOM, + /** @stable ICU 63 */ + U_INPC_BOTTOM_AND_LEFT, + /** @stable ICU 63 */ + U_INPC_BOTTOM_AND_RIGHT, + /** @stable ICU 63 */ + U_INPC_LEFT, + /** @stable ICU 63 */ + U_INPC_LEFT_AND_RIGHT, + /** @stable ICU 63 */ + U_INPC_OVERSTRUCK, + /** @stable ICU 63 */ + U_INPC_RIGHT, + /** @stable ICU 63 */ + U_INPC_TOP, + /** @stable ICU 63 */ + U_INPC_TOP_AND_BOTTOM, + /** @stable ICU 63 */ + U_INPC_TOP_AND_BOTTOM_AND_RIGHT, + /** @stable ICU 63 */ + U_INPC_TOP_AND_LEFT, + /** @stable ICU 63 */ + U_INPC_TOP_AND_LEFT_AND_RIGHT, + /** @stable ICU 63 */ + U_INPC_TOP_AND_RIGHT, + /** @stable ICU 63 */ + U_INPC_VISUAL_ORDER_LEFT, + /** @stable ICU 66 */ + U_INPC_TOP_AND_BOTTOM_AND_LEFT, +} UIndicPositionalCategory; + +/** + * Indic Syllabic Category constants. + * + * @see UCHAR_INDIC_SYLLABIC_CATEGORY + * @stable ICU 63 + */ +typedef enum UIndicSyllabicCategory { + /* + * Note: UIndicSyllabicCategory constants are parsed by preparseucd.py. + * It matches lines like + * U_INSC_ + */ + + /** @stable ICU 63 */ + U_INSC_OTHER, + /** @stable ICU 63 */ + U_INSC_AVAGRAHA, + /** @stable ICU 63 */ + U_INSC_BINDU, + /** @stable ICU 63 */ + U_INSC_BRAHMI_JOINING_NUMBER, + /** @stable ICU 63 */ + U_INSC_CANTILLATION_MARK, + /** @stable ICU 63 */ + U_INSC_CONSONANT, + /** @stable ICU 63 */ + U_INSC_CONSONANT_DEAD, + /** @stable ICU 63 */ + U_INSC_CONSONANT_FINAL, + /** @stable ICU 63 */ + U_INSC_CONSONANT_HEAD_LETTER, + /** @stable ICU 63 */ + U_INSC_CONSONANT_INITIAL_POSTFIXED, + /** @stable ICU 63 */ + U_INSC_CONSONANT_KILLER, + /** @stable ICU 63 */ + U_INSC_CONSONANT_MEDIAL, + /** @stable ICU 63 */ + U_INSC_CONSONANT_PLACEHOLDER, + /** @stable ICU 63 */ + U_INSC_CONSONANT_PRECEDING_REPHA, + /** @stable ICU 63 */ + U_INSC_CONSONANT_PREFIXED, + /** @stable ICU 63 */ + U_INSC_CONSONANT_SUBJOINED, + /** @stable ICU 63 */ + U_INSC_CONSONANT_SUCCEEDING_REPHA, + /** @stable ICU 63 */ + U_INSC_CONSONANT_WITH_STACKER, + /** @stable ICU 63 */ + U_INSC_GEMINATION_MARK, + /** @stable ICU 63 */ + U_INSC_INVISIBLE_STACKER, + /** @stable ICU 63 */ + U_INSC_JOINER, + /** @stable ICU 63 */ + U_INSC_MODIFYING_LETTER, + /** @stable ICU 63 */ + U_INSC_NON_JOINER, + /** @stable ICU 63 */ + U_INSC_NUKTA, + /** @stable ICU 63 */ + U_INSC_NUMBER, + /** @stable ICU 63 */ + U_INSC_NUMBER_JOINER, + /** @stable ICU 63 */ + U_INSC_PURE_KILLER, + /** @stable ICU 63 */ + U_INSC_REGISTER_SHIFTER, + /** @stable ICU 63 */ + U_INSC_SYLLABLE_MODIFIER, + /** @stable ICU 63 */ + U_INSC_TONE_LETTER, + /** @stable ICU 63 */ + U_INSC_TONE_MARK, + /** @stable ICU 63 */ + U_INSC_VIRAMA, + /** @stable ICU 63 */ + U_INSC_VISARGA, + /** @stable ICU 63 */ + U_INSC_VOWEL, + /** @stable ICU 63 */ + U_INSC_VOWEL_DEPENDENT, + /** @stable ICU 63 */ + U_INSC_VOWEL_INDEPENDENT, +} UIndicSyllabicCategory; + +/** + * Vertical Orientation constants. + * + * @see UCHAR_VERTICAL_ORIENTATION + * @stable ICU 63 + */ +typedef enum UVerticalOrientation { + /* + * Note: UVerticalOrientation constants are parsed by preparseucd.py. + * It matches lines like + * U_VO_ + */ + + /** @stable ICU 63 */ + U_VO_ROTATED, + /** @stable ICU 63 */ + U_VO_TRANSFORMED_ROTATED, + /** @stable ICU 63 */ + U_VO_TRANSFORMED_UPRIGHT, + /** @stable ICU 63 */ + U_VO_UPRIGHT, +} UVerticalOrientation; + +/** + * Check a binary Unicode property for a code point. + * + * Unicode, especially in version 3.2, defines many more properties than the + * original set in UnicodeData.txt. + * + * The properties APIs are intended to reflect Unicode properties as defined + * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). + * For details about the properties see http://www.unicode.org/ucd/ . + * For names of Unicode properties see the UCD file PropertyAliases.txt. + * + * Important: If ICU is built with UCD files from Unicode versions below 3.2, + * then properties marked with "new in Unicode 3.2" are not or not fully available. + * + * @param c Code point to test. + * @param which UProperty selector constant, identifies which binary property to check. + * Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT. + * @return true or false according to the binary Unicode property value for c. + * Also false if 'which' is out of bounds or if the Unicode version + * does not have data for the property at all. + * + * @see UProperty + * @see u_getBinaryPropertySet + * @see u_getIntPropertyValue + * @see u_getUnicodeVersion + * @stable ICU 2.1 + */ +U_CAPI UBool U_EXPORT2 +u_hasBinaryProperty(UChar32 c, UProperty which); + +/** + * Returns true if the property is true for the string. + * Same as u_hasBinaryProperty(single code point, which) + * if the string contains exactly one code point. + * + * Most properties apply only to single code points. + * UTS #51 Unicode Emoji + * defines several properties of strings. + * + * @param s String to test. + * @param length Length of the string, or negative if NUL-terminated. + * @param which UProperty selector constant, identifies which binary property to check. + * Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT. + * @return true or false according to the binary Unicode property value for the string. + * Also false if 'which' is out of bounds or if the Unicode version + * does not have data for the property at all. + * + * @see UProperty + * @see u_hasBinaryProperty + * @see u_getBinaryPropertySet + * @see u_getIntPropertyValue + * @see u_getUnicodeVersion + * @stable ICU 70 + */ +U_CAPI UBool U_EXPORT2 +u_stringHasBinaryProperty(const UChar *s, int32_t length, UProperty which); + +/** + * Returns a frozen USet for a binary property. + * The library retains ownership over the returned object. + * Sets an error code if the property number is not one for a binary property. + * + * The returned set contains all code points for which the property is true. + * + * @param property UCHAR_BINARY_START..UCHAR_BINARY_LIMIT-1 + * @param pErrorCode an in/out ICU UErrorCode + * @return the property as a set + * @see UProperty + * @see u_hasBinaryProperty + * @see Unicode::fromUSet + * @stable ICU 63 + */ +U_CAPI const USet * U_EXPORT2 +u_getBinaryPropertySet(UProperty property, UErrorCode *pErrorCode); + +/** + * Check if a code point has the Alphabetic Unicode property. + * Same as u_hasBinaryProperty(c, UCHAR_ALPHABETIC). + * This is different from u_isalpha! + * @param c Code point to test + * @return true if the code point has the Alphabetic Unicode property, false otherwise + * + * @see UCHAR_ALPHABETIC + * @see u_isalpha + * @see u_hasBinaryProperty + * @stable ICU 2.1 + */ +U_CAPI UBool U_EXPORT2 +u_isUAlphabetic(UChar32 c); + +/** + * Check if a code point has the Lowercase Unicode property. + * Same as u_hasBinaryProperty(c, UCHAR_LOWERCASE). + * This is different from u_islower! + * @param c Code point to test + * @return true if the code point has the Lowercase Unicode property, false otherwise + * + * @see UCHAR_LOWERCASE + * @see u_islower + * @see u_hasBinaryProperty + * @stable ICU 2.1 + */ +U_CAPI UBool U_EXPORT2 +u_isULowercase(UChar32 c); + +/** + * Check if a code point has the Uppercase Unicode property. + * Same as u_hasBinaryProperty(c, UCHAR_UPPERCASE). + * This is different from u_isupper! + * @param c Code point to test + * @return true if the code point has the Uppercase Unicode property, false otherwise + * + * @see UCHAR_UPPERCASE + * @see u_isupper + * @see u_hasBinaryProperty + * @stable ICU 2.1 + */ +U_CAPI UBool U_EXPORT2 +u_isUUppercase(UChar32 c); + +/** + * Check if a code point has the White_Space Unicode property. + * Same as u_hasBinaryProperty(c, UCHAR_WHITE_SPACE). + * This is different from both u_isspace and u_isWhitespace! + * + * Note: There are several ICU whitespace functions; please see the uchar.h + * file documentation for a detailed comparison. + * + * @param c Code point to test + * @return true if the code point has the White_Space Unicode property, false otherwise. + * + * @see UCHAR_WHITE_SPACE + * @see u_isWhitespace + * @see u_isspace + * @see u_isJavaSpaceChar + * @see u_hasBinaryProperty + * @stable ICU 2.1 + */ +U_CAPI UBool U_EXPORT2 +u_isUWhiteSpace(UChar32 c); + +/** + * Get the property value for an enumerated or integer Unicode property for a code point. + * Also returns binary and mask property values. + * + * Unicode, especially in version 3.2, defines many more properties than the + * original set in UnicodeData.txt. + * + * The properties APIs are intended to reflect Unicode properties as defined + * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). + * For details about the properties see http://www.unicode.org/ . + * For names of Unicode properties see the UCD file PropertyAliases.txt. + * + * Sample usage: + * UEastAsianWidth ea=(UEastAsianWidth)u_getIntPropertyValue(c, UCHAR_EAST_ASIAN_WIDTH); + * UBool b=(UBool)u_getIntPropertyValue(c, UCHAR_IDEOGRAPHIC); + * + * @param c Code point to test. + * @param which UProperty selector constant, identifies which property to check. + * Must be UCHAR_BINARY_START<=which=0. + * True for characters with general category "Nd" (decimal digit numbers) + * as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. + * (That is, for letters with code points + * 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.) + * + * In order to narrow the definition of hexadecimal digits to only ASCII + * characters, use (c<=0x7f && u_isxdigit(c)). + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a hexadecimal digit + * + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_isxdigit(UChar32 c); + +/** + * Determines whether the specified code point is a punctuation character. + * True for characters with general categories "P" (punctuation). + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a punctuation character + * + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_ispunct(UChar32 c); + +/** + * Determines whether the specified code point is a "graphic" character + * (printable, excluding spaces). + * true for all characters except those with general categories + * "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates), + * "Cn" (unassigned), and "Z" (separators). + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a "graphic" character + * + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_isgraph(UChar32 c); + +/** + * Determines whether the specified code point is a "blank" or "horizontal space", + * a character that visibly separates words on a line. + * The following are equivalent definitions: + * + * true for Unicode White_Space characters except for "vertical space controls" + * where "vertical space controls" are the following characters: + * U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS) + * + * same as + * + * true for U+0009 (TAB) and characters with general category "Zs" (space separators). + * + * Note: There are several ICU whitespace functions; please see the uchar.h + * file documentation for a detailed comparison. + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a "blank" + * + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_isblank(UChar32 c); + +/** + * Determines whether the specified code point is "defined", + * which usually means that it is assigned a character. + * True for general categories other than "Cn" (other, not assigned), + * i.e., true for all code points mentioned in UnicodeData.txt. + * + * Note that non-character code points (e.g., U+FDD0) are not "defined" + * (they are Cn), but surrogate code points are "defined" (Cs). + * + * Same as java.lang.Character.isDefined(). + * + * @param c the code point to be tested + * @return true if the code point is assigned a character + * + * @see u_isdigit + * @see u_isalpha + * @see u_isalnum + * @see u_isupper + * @see u_islower + * @see u_istitle + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isdefined(UChar32 c); + +/** + * Determines if the specified character is a space character or not. + * + * Note: There are several ICU whitespace functions; please see the uchar.h + * file documentation for a detailed comparison. + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the character to be tested + * @return true if the character is a space character; false otherwise. + * + * @see u_isJavaSpaceChar + * @see u_isWhitespace + * @see u_isUWhiteSpace + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isspace(UChar32 c); + +/** + * Determine if the specified code point is a space character according to Java. + * True for characters with general categories "Z" (separators), + * which does not include control codes (e.g., TAB or Line Feed). + * + * Same as java.lang.Character.isSpaceChar(). + * + * Note: There are several ICU whitespace functions; please see the uchar.h + * file documentation for a detailed comparison. + * + * @param c the code point to be tested + * @return true if the code point is a space character according to Character.isSpaceChar() + * + * @see u_isspace + * @see u_isWhitespace + * @see u_isUWhiteSpace + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_isJavaSpaceChar(UChar32 c); + +/** + * Determines if the specified code point is a whitespace character according to Java/ICU. + * A character is considered to be a Java whitespace character if and only + * if it satisfies one of the following criteria: + * + * - It is a Unicode Separator character (categories "Z" = "Zs" or "Zl" or "Zp"), but is not + * also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP). + * - It is U+0009 HORIZONTAL TABULATION. + * - It is U+000A LINE FEED. + * - It is U+000B VERTICAL TABULATION. + * - It is U+000C FORM FEED. + * - It is U+000D CARRIAGE RETURN. + * - It is U+001C FILE SEPARATOR. + * - It is U+001D GROUP SEPARATOR. + * - It is U+001E RECORD SEPARATOR. + * - It is U+001F UNIT SEPARATOR. + * + * This API tries to sync with the semantics of Java's + * java.lang.Character.isWhitespace(), but it may not return + * the exact same results because of the Unicode version + * difference. + * + * Note: Unicode 4.0.1 changed U+200B ZERO WIDTH SPACE from a Space Separator (Zs) + * to a Format Control (Cf). Since then, isWhitespace(0x200b) returns false. + * See http://www.unicode.org/versions/Unicode4.0.1/ + * + * Note: There are several ICU whitespace functions; please see the uchar.h + * file documentation for a detailed comparison. + * + * @param c the code point to be tested + * @return true if the code point is a whitespace character according to Java/ICU + * + * @see u_isspace + * @see u_isJavaSpaceChar + * @see u_isUWhiteSpace + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isWhitespace(UChar32 c); + +/** + * Determines whether the specified code point is a control character + * (as defined by this function). + * A control character is one of the following: + * - ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f) + * - U_CONTROL_CHAR (Cc) + * - U_FORMAT_CHAR (Cf) + * - U_LINE_SEPARATOR (Zl) + * - U_PARAGRAPH_SEPARATOR (Zp) + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a control character + * + * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT + * @see u_isprint + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_iscntrl(UChar32 c); + +/** + * Determines whether the specified code point is an ISO control code. + * True for U+0000..U+001f and U+007f..U+009f (general category "Cc"). + * + * Same as java.lang.Character.isISOControl(). + * + * @param c the code point to be tested + * @return true if the code point is an ISO control code + * + * @see u_iscntrl + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +u_isISOControl(UChar32 c); + +/** + * Determines whether the specified code point is a printable character. + * True for general categories other than "C" (controls). + * + * This is a C/POSIX migration function. + * See the comments about C/POSIX character classification functions in the + * documentation at the top of this header file. + * + * @param c the code point to be tested + * @return true if the code point is a printable character + * + * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT + * @see u_iscntrl + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isprint(UChar32 c); + +/** + * Non-standard: Determines whether the specified code point is a base character. + * True for general categories "L" (letters), "N" (numbers), + * "Mc" (spacing combining marks), and "Me" (enclosing marks). + * + * Note that this is different from the Unicode Standard definition in + * chapter 3.6, conformance clause D51 “Base character”, + * which defines base characters as the code points with general categories + * Letter (L), Number (N), Punctuation (P), Symbol (S), or Space Separator (Zs). + * + * @param c the code point to be tested + * @return true if the code point is a base character according to this function + * + * @see u_isalpha + * @see u_isdigit + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isbase(UChar32 c); + +/** + * Returns the bidirectional category value for the code point, + * which is used in the Unicode bidirectional algorithm + * (UAX #9 http://www.unicode.org/reports/tr9/). + * Note that some unassigned code points have bidi values + * of R or AL because they are in blocks that are reserved + * for Right-To-Left scripts. + * + * Same as java.lang.Character.getDirectionality() + * + * @param c the code point to be tested + * @return the bidirectional category (UCharDirection) value + * + * @see UCharDirection + * @stable ICU 2.0 + */ +U_CAPI UCharDirection U_EXPORT2 +u_charDirection(UChar32 c); + +/** + * Determines whether the code point has the Bidi_Mirrored property. + * This property is set for characters that are commonly used in + * Right-To-Left contexts and need to be displayed with a "mirrored" + * glyph. + * + * Same as java.lang.Character.isMirrored(). + * Same as UCHAR_BIDI_MIRRORED + * + * @param c the code point to be tested + * @return true if the character has the Bidi_Mirrored property + * + * @see UCHAR_BIDI_MIRRORED + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +u_isMirrored(UChar32 c); + +/** + * Maps the specified character to a "mirror-image" character. + * For characters with the Bidi_Mirrored property, implementations + * sometimes need a "poor man's" mapping to another Unicode + * character (code point) such that the default glyph may serve + * as the mirror-image of the default glyph of the specified + * character. This is useful for text conversion to and from + * codepages with visual order, and for displays without glyph + * selection capabilities. + * + * @param c the code point to be mapped + * @return another Unicode code point that may serve as a mirror-image + * substitute, or c itself if there is no such mapping or c + * does not have the Bidi_Mirrored property + * + * @see UCHAR_BIDI_MIRRORED + * @see u_isMirrored + * @stable ICU 2.0 + */ +U_CAPI UChar32 U_EXPORT2 +u_charMirror(UChar32 c); + +/** + * Maps the specified character to its paired bracket character. + * For Bidi_Paired_Bracket_Type!=None, this is the same as u_charMirror(). + * Otherwise c itself is returned. + * See http://www.unicode.org/reports/tr9/ + * + * @param c the code point to be mapped + * @return the paired bracket code point, + * or c itself if there is no such mapping + * (Bidi_Paired_Bracket_Type=None) + * + * @see UCHAR_BIDI_PAIRED_BRACKET + * @see UCHAR_BIDI_PAIRED_BRACKET_TYPE + * @see u_charMirror + * @stable ICU 52 + */ +U_CAPI UChar32 U_EXPORT2 +u_getBidiPairedBracket(UChar32 c); + +/** + * Returns the general category value for the code point. + * + * Same as java.lang.Character.getType(). + * + * @param c the code point to be tested + * @return the general category (UCharCategory) value + * + * @see UCharCategory + * @stable ICU 2.0 + */ +U_CAPI int8_t U_EXPORT2 +u_charType(UChar32 c); + +/** + * Get a single-bit bit set for the general category of a character. + * This bit set can be compared bitwise with U_GC_SM_MASK, U_GC_L_MASK, etc. + * Same as U_MASK(u_charType(c)). + * + * @param c the code point to be tested + * @return a single-bit mask corresponding to the general category (UCharCategory) value + * + * @see u_charType + * @see UCharCategory + * @see U_GC_CN_MASK + * @stable ICU 2.1 + */ +#define U_GET_GC_MASK(c) U_MASK(u_charType(c)) + +/** + * Callback from u_enumCharTypes(), is called for each contiguous range + * of code points c (where start<=cnameChoice, the character name written + * into the buffer is the "modern" name or the name that was defined + * in Unicode version 1.0. + * The name contains only "invariant" characters + * like A-Z, 0-9, space, and '-'. + * Unicode 1.0 names are only retrieved if they are different from the modern + * names and if the data file contains the data for them. gennames may or may + * not be called with a command line option to include 1.0 names in unames.dat. + * + * @param code The character (code point) for which to get the name. + * It must be 0<=code<=0x10ffff. + * @param nameChoice Selector for which name to get. + * @param buffer Destination address for copying the name. + * The name will always be zero-terminated. + * If there is no name, then the buffer will be set to the empty string. + * @param bufferLength ==sizeof(buffer) + * @param pErrorCode Pointer to a UErrorCode variable; + * check for U_SUCCESS() after u_charName() + * returns. + * @return The length of the name, or 0 if there is no name for this character. + * If the bufferLength is less than or equal to the length, then the buffer + * contains the truncated name and the returned length indicates the full + * length of the name. + * The length does not include the zero-termination. + * + * @see UCharNameChoice + * @see u_charFromName + * @see u_enumCharNames + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_charName(UChar32 code, UCharNameChoice nameChoice, + char *buffer, int32_t bufferLength, + UErrorCode *pErrorCode); + +#ifndef U_HIDE_DEPRECATED_API +/** + * Returns an empty string. + * Used to return the ISO 10646 comment for a character. + * The Unicode ISO_Comment property is deprecated and has no values. + * + * @param c The character (code point) for which to get the ISO comment. + * It must be 0<=c<=0x10ffff. + * @param dest Destination address for copying the comment. + * The comment will be zero-terminated if possible. + * If there is no comment, then the buffer will be set to the empty string. + * @param destCapacity ==sizeof(dest) + * @param pErrorCode Pointer to a UErrorCode variable; + * check for U_SUCCESS() after u_getISOComment() + * returns. + * @return 0 + * + * @deprecated ICU 49 + */ +U_DEPRECATED int32_t U_EXPORT2 +u_getISOComment(UChar32 c, + char *dest, int32_t destCapacity, + UErrorCode *pErrorCode); +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Find a Unicode character by its name and return its code point value. + * The name is matched exactly and completely. + * If the name does not correspond to a code point, pErrorCode + * is set to U_INVALID_CHAR_FOUND. + * A Unicode 1.0 name is matched only if it differs from the modern name. + * Unicode names are all uppercase. Extended names are lowercase followed + * by an uppercase hexadecimal number, and within angle brackets. + * + * @param nameChoice Selector for which name to match. + * @param name The name to match. + * @param pErrorCode Pointer to a UErrorCode variable + * @return The Unicode value of the code point with the given name, + * or an undefined value if there is no such code point. + * + * @see UCharNameChoice + * @see u_charName + * @see u_enumCharNames + * @stable ICU 1.7 + */ +U_CAPI UChar32 U_EXPORT2 +u_charFromName(UCharNameChoice nameChoice, + const char *name, + UErrorCode *pErrorCode); + +/** + * Type of a callback function for u_enumCharNames() that gets called + * for each Unicode character with the code point value and + * the character name. + * If such a function returns false, then the enumeration is stopped. + * + * @param context The context pointer that was passed to u_enumCharNames(). + * @param code The Unicode code point for the character with this name. + * @param nameChoice Selector for which kind of names is enumerated. + * @param name The character's name, zero-terminated. + * @param length The length of the name. + * @return true if the enumeration should continue, false to stop it. + * + * @see UCharNameChoice + * @see u_enumCharNames + * @stable ICU 1.7 + */ +typedef UBool U_CALLCONV UEnumCharNamesFn(void *context, + UChar32 code, + UCharNameChoice nameChoice, + const char *name, + int32_t length); + +/** + * Enumerate all assigned Unicode characters between the start and limit + * code points (start inclusive, limit exclusive) and call a function + * for each, passing the code point value and the character name. + * For Unicode 1.0 names, only those are enumerated that differ from the + * modern names. + * + * @param start The first code point in the enumeration range. + * @param limit One more than the last code point in the enumeration range + * (the first one after the range). + * @param fn The function that is to be called for each character name. + * @param context An arbitrary pointer that is passed to the function. + * @param nameChoice Selector for which kind of names to enumerate. + * @param pErrorCode Pointer to a UErrorCode variable + * + * @see UCharNameChoice + * @see UEnumCharNamesFn + * @see u_charName + * @see u_charFromName + * @stable ICU 1.7 + */ +U_CAPI void U_EXPORT2 +u_enumCharNames(UChar32 start, UChar32 limit, + UEnumCharNamesFn *fn, + void *context, + UCharNameChoice nameChoice, + UErrorCode *pErrorCode); + +/** + * Return the Unicode name for a given property, as given in the + * Unicode database file PropertyAliases.txt. + * + * In addition, this function maps the property + * UCHAR_GENERAL_CATEGORY_MASK to the synthetic names "gcm" / + * "General_Category_Mask". These names are not in + * PropertyAliases.txt. + * + * @param property UProperty selector other than UCHAR_INVALID_CODE. + * If out of range, NULL is returned. + * + * @param nameChoice selector for which name to get. If out of range, + * NULL is returned. All properties have a long name. Most + * have a short name, but some do not. Unicode allows for + * additional names; if present these will be returned by + * U_LONG_PROPERTY_NAME + i, where i=1, 2,... + * + * @return a pointer to the name, or NULL if either the + * property or the nameChoice is out of range. If a given + * nameChoice returns NULL, then all larger values of + * nameChoice will return NULL, with one exception: if NULL is + * returned for U_SHORT_PROPERTY_NAME, then + * U_LONG_PROPERTY_NAME (and higher) may still return a + * non-NULL value. The returned pointer is valid until + * u_cleanup() is called. + * + * @see UProperty + * @see UPropertyNameChoice + * @stable ICU 2.4 + */ +U_CAPI const char* U_EXPORT2 +u_getPropertyName(UProperty property, + UPropertyNameChoice nameChoice); + +/** + * Return the UProperty enum for a given property name, as specified + * in the Unicode database file PropertyAliases.txt. Short, long, and + * any other variants are recognized. + * + * In addition, this function maps the synthetic names "gcm" / + * "General_Category_Mask" to the property + * UCHAR_GENERAL_CATEGORY_MASK. These names are not in + * PropertyAliases.txt. + * + * @param alias the property name to be matched. The name is compared + * using "loose matching" as described in PropertyAliases.txt. + * + * @return a UProperty enum, or UCHAR_INVALID_CODE if the given name + * does not match any property. + * + * @see UProperty + * @stable ICU 2.4 + */ +U_CAPI UProperty U_EXPORT2 +u_getPropertyEnum(const char* alias); + +/** + * Return the Unicode name for a given property value, as given in the + * Unicode database file PropertyValueAliases.txt. + * + * Note: Some of the names in PropertyValueAliases.txt can only be + * retrieved using UCHAR_GENERAL_CATEGORY_MASK, not + * UCHAR_GENERAL_CATEGORY. These include: "C" / "Other", "L" / + * "Letter", "LC" / "Cased_Letter", "M" / "Mark", "N" / "Number", "P" + * / "Punctuation", "S" / "Symbol", and "Z" / "Separator". + * + * @param property UProperty selector constant. + * Must be UCHAR_BINARY_START<=which2<=radix<=36 or if the + * value of c is not a valid digit in the specified + * radix, -1 is returned. A character is a valid digit + * if at least one of the following is true: + *

    + *
  • The character has a decimal digit value. + * Such characters have the general category "Nd" (decimal digit numbers) + * and a Numeric_Type of Decimal. + * In this case the value is the character's decimal digit value.
  • + *
  • The character is one of the uppercase Latin letters + * 'A' through 'Z'. + * In this case the value is c-'A'+10.
  • + *
  • The character is one of the lowercase Latin letters + * 'a' through 'z'. + * In this case the value is ch-'a'+10.
  • + *
  • Latin letters from both the ASCII range (0061..007A, 0041..005A) + * as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) + * are recognized.
  • + *
+ * + * Same as java.lang.Character.digit(). + * + * @param ch the code point to be tested. + * @param radix the radix. + * @return the numeric value represented by the character in the + * specified radix, + * or -1 if there is no value or if the value exceeds the radix. + * + * @see UCHAR_NUMERIC_TYPE + * @see u_forDigit + * @see u_charDigitValue + * @see u_isdigit + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_digit(UChar32 ch, int8_t radix); + +/** + * Determines the character representation for a specific digit in + * the specified radix. If the value of radix is not a + * valid radix, or the value of digit is not a valid + * digit in the specified radix, the null character + * (U+0000) is returned. + *

+ * The radix argument is valid if it is greater than or + * equal to 2 and less than or equal to 36. + * The digit argument is valid if + * 0 <= digit < radix. + *

+ * If the digit is less than 10, then + * '0' + digit is returned. Otherwise, the value + * 'a' + digit - 10 is returned. + * + * Same as java.lang.Character.forDigit(). + * + * @param digit the number to convert to a character. + * @param radix the radix. + * @return the char representation of the specified digit + * in the specified radix. + * + * @see u_digit + * @see u_charDigitValue + * @see u_isdigit + * @stable ICU 2.0 + */ +U_CAPI UChar32 U_EXPORT2 +u_forDigit(int32_t digit, int8_t radix); + +/** + * Get the "age" of the code point. + * The "age" is the Unicode version when the code point was first + * designated (as a non-character or for Private Use) + * or assigned a character. + * This can be useful to avoid emitting code points to receiving + * processes that do not accept newer characters. + * The data is from the UCD file DerivedAge.txt. + * + * @param c The code point. + * @param versionArray The Unicode version number array, to be filled in. + * + * @stable ICU 2.1 + */ +U_CAPI void U_EXPORT2 +u_charAge(UChar32 c, UVersionInfo versionArray); + +/** + * Gets the Unicode version information. + * The version array is filled in with the version information + * for the Unicode standard that is currently used by ICU. + * For example, Unicode version 3.1.1 is represented as an array with + * the values { 3, 1, 1, 0 }. + * + * @param versionArray an output array that will be filled in with + * the Unicode version number + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_getUnicodeVersion(UVersionInfo versionArray); + +#if !UCONFIG_NO_NORMALIZATION +/** + * Get the FC_NFKC_Closure property string for a character. + * See Unicode Standard Annex #15 for details, search for "FC_NFKC_Closure" + * or for "FNC": http://www.unicode.org/reports/tr15/ + * + * @param c The character (code point) for which to get the FC_NFKC_Closure string. + * It must be 0<=c<=0x10ffff. + * @param dest Destination address for copying the string. + * The string will be zero-terminated if possible. + * If there is no FC_NFKC_Closure string, + * then the buffer will be set to the empty string. + * @param destCapacity ==sizeof(dest) + * @param pErrorCode Pointer to a UErrorCode variable. + * @return The length of the string, or 0 if there is no FC_NFKC_Closure string for this character. + * If the destCapacity is less than or equal to the length, then the buffer + * contains the truncated name and the returned length indicates the full + * length of the name. + * The length does not include the zero-termination. + * + * @stable ICU 2.2 + */ +U_CAPI int32_t U_EXPORT2 +u_getFC_NFKC_Closure(UChar32 c, UChar *dest, int32_t destCapacity, UErrorCode *pErrorCode); + +#endif + + +U_CDECL_END + +#endif /*_UCHAR*/ +/*eof*/ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstrie.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstrie.h new file mode 100644 index 0000000000000000000000000000000000000000..fa1b55616c65997e20693a9f0babaf43e6ca0aac --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstrie.h @@ -0,0 +1,623 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2012, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: ucharstrie.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010nov14 +* created by: Markus W. Scherer +*/ + +#ifndef __UCHARSTRIE_H__ +#define __UCHARSTRIE_H__ + +/** + * \file + * \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences) + * to integer values. + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/unistr.h" +#include "unicode/uobject.h" +#include "unicode/ustringtrie.h" + +U_NAMESPACE_BEGIN + +class Appendable; +class UCharsTrieBuilder; +class UVector32; + +/** + * Light-weight, non-const reader class for a UCharsTrie. + * Traverses a char16_t-serialized data structure with minimal state, + * for mapping strings (16-bit-unit sequences) to non-negative integer values. + * + * This class owns the serialized trie data only if it was constructed by + * the builder's build() method. + * The public constructor and the copy constructor only alias the data (only copy the pointer). + * There is no assignment operator. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API UCharsTrie : public UMemory { +public: + /** + * Constructs a UCharsTrie reader instance. + * + * The trieUChars must contain a copy of a char16_t sequence from the UCharsTrieBuilder, + * starting with the first char16_t of that sequence. + * The UCharsTrie object will not read more char16_ts than + * the UCharsTrieBuilder generated in the corresponding build() call. + * + * The array is not copied/cloned and must not be modified while + * the UCharsTrie object is in use. + * + * @param trieUChars The char16_t array that contains the serialized trie. + * @stable ICU 4.8 + */ + UCharsTrie(ConstChar16Ptr trieUChars) + : ownedArray_(nullptr), uchars_(trieUChars), + pos_(uchars_), remainingMatchLength_(-1) {} + + /** + * Destructor. + * @stable ICU 4.8 + */ + ~UCharsTrie(); + + /** + * Copy constructor, copies the other trie reader object and its state, + * but not the char16_t array which will be shared. (Shallow copy.) + * @param other Another UCharsTrie object. + * @stable ICU 4.8 + */ + UCharsTrie(const UCharsTrie &other) + : ownedArray_(nullptr), uchars_(other.uchars_), + pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {} + + /** + * Resets this trie to its initial state. + * @return *this + * @stable ICU 4.8 + */ + UCharsTrie &reset() { + pos_=uchars_; + remainingMatchLength_=-1; + return *this; + } + + /** + * Returns the state of this trie as a 64-bit integer. + * The state value is never 0. + * + * @return opaque state value + * @see resetToState64 + * @stable ICU 65 + */ + uint64_t getState64() const { + return (static_cast(remainingMatchLength_ + 2) << kState64RemainingShift) | + (uint64_t)(pos_ - uchars_); + } + + /** + * Resets this trie to the saved state. + * Unlike resetToState(State), the 64-bit state value + * must be from getState64() from the same trie object or + * from one initialized the exact same way. + * Because of no validation, this method is faster. + * + * @param state The opaque trie state value from getState64(). + * @return *this + * @see getState64 + * @see resetToState + * @see reset + * @stable ICU 65 + */ + UCharsTrie &resetToState64(uint64_t state) { + remainingMatchLength_ = static_cast(state >> kState64RemainingShift) - 2; + pos_ = uchars_ + (state & kState64PosMask); + return *this; + } + + /** + * UCharsTrie state object, for saving a trie's current state + * and resetting the trie back to this state later. + * @stable ICU 4.8 + */ + class State : public UMemory { + public: + /** + * Constructs an empty State. + * @stable ICU 4.8 + */ + State() { uchars=nullptr; } + private: + friend class UCharsTrie; + + const char16_t *uchars; + const char16_t *pos; + int32_t remainingMatchLength; + }; + + /** + * Saves the state of this trie. + * @param state The State object to hold the trie's state. + * @return *this + * @see resetToState + * @stable ICU 4.8 + */ + const UCharsTrie &saveState(State &state) const { + state.uchars=uchars_; + state.pos=pos_; + state.remainingMatchLength=remainingMatchLength_; + return *this; + } + + /** + * Resets this trie to the saved state. + * If the state object contains no state, or the state of a different trie, + * then this trie remains unchanged. + * @param state The State object which holds a saved trie state. + * @return *this + * @see saveState + * @see reset + * @stable ICU 4.8 + */ + UCharsTrie &resetToState(const State &state) { + if(uchars_==state.uchars && uchars_!=nullptr) { + pos_=state.pos; + remainingMatchLength_=state.remainingMatchLength; + } + return *this; + } + + /** + * Determines whether the string so far matches, whether it has a value, + * and whether another input char16_t can continue a matching string. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult current() const; + + /** + * Traverses the trie from the initial state for this input char16_t. + * Equivalent to reset().next(uchar). + * @param uchar Input char value. Values below 0 and above 0xffff will never match. + * @return The match/value Result. + * @stable ICU 4.8 + */ + inline UStringTrieResult first(int32_t uchar) { + remainingMatchLength_=-1; + return nextImpl(uchars_, uchar); + } + + /** + * Traverses the trie from the initial state for the + * one or two UTF-16 code units for this input code point. + * Equivalent to reset().nextForCodePoint(cp). + * @param cp A Unicode code point 0..0x10ffff. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult firstForCodePoint(UChar32 cp); + + /** + * Traverses the trie from the current state for this input char16_t. + * @param uchar Input char value. Values below 0 and above 0xffff will never match. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult next(int32_t uchar); + + /** + * Traverses the trie from the current state for the + * one or two UTF-16 code units for this input code point. + * @param cp A Unicode code point 0..0x10ffff. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult nextForCodePoint(UChar32 cp); + + /** + * Traverses the trie from the current state for this string. + * Equivalent to + * \code + * Result result=current(); + * for(each c in s) + * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH; + * result=next(c); + * return result; + * \endcode + * @param s A string. Can be nullptr if length is 0. + * @param length The length of the string. Can be -1 if NUL-terminated. + * @return The match/value Result. + * @stable ICU 4.8 + */ + UStringTrieResult next(ConstChar16Ptr s, int32_t length); + + /** + * Returns a matching string's value if called immediately after + * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE. + * getValue() can be called multiple times. + * + * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE! + * @return The value for the string so far. + * @stable ICU 4.8 + */ + inline int32_t getValue() const { + const char16_t *pos=pos_; + int32_t leadUnit=*pos++; + // U_ASSERT(leadUnit>=kMinValueLead); + return leadUnit&kValueIsFinal ? + readValue(pos, leadUnit&0x7fff) : readNodeValue(pos, leadUnit); + } + + /** + * Determines whether all strings reachable from the current state + * map to the same value. + * @param uniqueValue Receives the unique value, if this function returns true. + * (output-only) + * @return true if all strings reachable from the current state + * map to the same value. + * @stable ICU 4.8 + */ + inline UBool hasUniqueValue(int32_t &uniqueValue) const { + const char16_t *pos=pos_; + // Skip the rest of a pending linear-match node. + return pos!=nullptr && findUniqueValue(pos+remainingMatchLength_+1, false, uniqueValue); + } + + /** + * Finds each char16_t which continues the string from the current state. + * That is, each char16_t c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now. + * @param out Each next char16_t is appended to this object. + * @return the number of char16_ts which continue the string from here + * @stable ICU 4.8 + */ + int32_t getNextUChars(Appendable &out) const; + + /** + * Iterator for all of the (string, value) pairs in a UCharsTrie. + * @stable ICU 4.8 + */ + class U_COMMON_API Iterator : public UMemory { + public: + /** + * Iterates from the root of a char16_t-serialized UCharsTrie. + * @param trieUChars The trie char16_ts. + * @param maxStringLength If 0, the iterator returns full strings. + * Otherwise, the iterator returns strings with this maximum length. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + Iterator(ConstChar16Ptr trieUChars, int32_t maxStringLength, UErrorCode &errorCode); + + /** + * Iterates from the current state of the specified UCharsTrie. + * @param trie The trie whose state will be copied for iteration. + * @param maxStringLength If 0, the iterator returns full strings. + * Otherwise, the iterator returns strings with this maximum length. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @stable ICU 4.8 + */ + Iterator(const UCharsTrie &trie, int32_t maxStringLength, UErrorCode &errorCode); + + /** + * Destructor. + * @stable ICU 4.8 + */ + ~Iterator(); + + /** + * Resets this iterator to its initial state. + * @return *this + * @stable ICU 4.8 + */ + Iterator &reset(); + + /** + * @return true if there are more elements. + * @stable ICU 4.8 + */ + UBool hasNext() const; + + /** + * Finds the next (string, value) pair if there is one. + * + * If the string is truncated to the maximum length and does not + * have a real value, then the value is set to -1. + * In this case, this "not a real value" is indistinguishable from + * a real value of -1. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return true if there is another element. + * @stable ICU 4.8 + */ + UBool next(UErrorCode &errorCode); + + /** + * @return The string for the last successful next(). + * @stable ICU 4.8 + */ + const UnicodeString &getString() const { return str_; } + /** + * @return The value for the last successful next(). + * @stable ICU 4.8 + */ + int32_t getValue() const { return value_; } + + private: + UBool truncateAndStop() { + pos_=nullptr; + value_=-1; // no real value for str + return true; + } + + const char16_t *branchNext(const char16_t *pos, int32_t length, UErrorCode &errorCode); + + const char16_t *uchars_; + const char16_t *pos_; + const char16_t *initialPos_; + int32_t remainingMatchLength_; + int32_t initialRemainingMatchLength_; + UBool skipValue_; // Skip intermediate value which was already delivered. + + UnicodeString str_; + int32_t maxLength_; + int32_t value_; + + // The stack stores pairs of integers for backtracking to another + // outbound edge of a branch node. + // The first integer is an offset from uchars_. + // The second integer has the str_.length() from before the node in bits 15..0, + // and the remaining branch length in bits 31..16. + // (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit, + // but the code looks more confusing that way.) + UVector32 *stack_; + }; + +private: + friend class UCharsTrieBuilder; + + /** + * Constructs a UCharsTrie reader instance. + * Unlike the public constructor which just aliases an array, + * this constructor adopts the builder's array. + * This constructor is only called by the builder. + */ + UCharsTrie(char16_t *adoptUChars, const char16_t *trieUChars) + : ownedArray_(adoptUChars), uchars_(trieUChars), + pos_(uchars_), remainingMatchLength_(-1) {} + + // No assignment operator. + UCharsTrie &operator=(const UCharsTrie &other) = delete; + + inline void stop() { + pos_=nullptr; + } + + // Reads a compact 32-bit integer. + // pos is already after the leadUnit, and the lead unit has bit 15 reset. + static inline int32_t readValue(const char16_t *pos, int32_t leadUnit) { + int32_t value; + if(leadUnit=kMinTwoUnitValueLead) { + if(leadUnit>6)-1; + } else if(leadUnit=kMinTwoUnitNodeValueLead) { + if(leadUnit=kMinTwoUnitDeltaLead) { + if(delta==kThreeUnitDeltaLead) { + delta=(pos[0]<<16)|pos[1]; + pos+=2; + } else { + delta=((delta-kMinTwoUnitDeltaLead)<<16)|*pos++; + } + } + return pos+delta; + } + + static const char16_t *skipDelta(const char16_t *pos) { + int32_t delta=*pos++; + if(delta>=kMinTwoUnitDeltaLead) { + if(delta==kThreeUnitDeltaLead) { + pos+=2; + } else { + ++pos; + } + } + return pos; + } + + static inline UStringTrieResult valueResult(int32_t node) { + return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node>>15)); + } + + // Handles a branch node for both next(uchar) and next(string). + UStringTrieResult branchNext(const char16_t *pos, int32_t length, int32_t uchar); + + // Requires remainingLength_<0. + UStringTrieResult nextImpl(const char16_t *pos, int32_t uchar); + + // Helper functions for hasUniqueValue(). + // Recursively finds a unique value (or whether there is not a unique one) + // from a branch. + static const char16_t *findUniqueValueFromBranch(const char16_t *pos, int32_t length, + UBool haveUniqueValue, int32_t &uniqueValue); + // Recursively finds a unique value (or whether there is not a unique one) + // starting from a position on a node lead unit. + static UBool findUniqueValue(const char16_t *pos, UBool haveUniqueValue, int32_t &uniqueValue); + + // Helper functions for getNextUChars(). + // getNextUChars() when pos is on a branch node. + static void getNextBranchUChars(const char16_t *pos, int32_t length, Appendable &out); + + // UCharsTrie data structure + // + // The trie consists of a series of char16_t-serialized nodes for incremental + // Unicode string/char16_t sequence matching. (char16_t=16-bit unsigned integer) + // The root node is at the beginning of the trie data. + // + // Types of nodes are distinguished by their node lead unit ranges. + // After each node, except a final-value node, another node follows to + // encode match values or continue matching further units. + // + // Node types: + // - Final-value node: Stores a 32-bit integer in a compact, variable-length format. + // The value is for the string/char16_t sequence so far. + // - Match node, optionally with an intermediate value in a different compact format. + // The value, if present, is for the string/char16_t sequence so far. + // + // Aside from the value, which uses the node lead unit's high bits: + // + // - Linear-match node: Matches a number of units. + // - Branch node: Branches to other nodes according to the current input unit. + // The node unit is the length of the branch (number of units to select from) + // minus 1. It is followed by a sub-node: + // - If the length is at most kMaxBranchLinearSubNodeLength, then + // there are length-1 (key, value) pairs and then one more comparison unit. + // If one of the key units matches, then the value is either a final value for + // the string so far, or a "jump" delta to the next node. + // If the last unit matches, then matching continues with the next node. + // (Values have the same encoding as final-value nodes.) + // - If the length is greater than kMaxBranchLinearSubNodeLength, then + // there is one unit and one "jump" delta. + // If the input unit is less than the sub-node unit, then "jump" by delta to + // the next sub-node which will have a length of length/2. + // (The delta has its own compact encoding.) + // Otherwise, skip the "jump" delta to the next sub-node + // which will have a length of length-length/2. + + // Match-node lead unit values, after masking off intermediate-value bits: + + // 0000..002f: Branch node. If node!=0 then the length is node+1, otherwise + // the length is one more than the next unit. + + // For a branch sub-node with at most this many entries, we drop down + // to a linear search. + static const int32_t kMaxBranchLinearSubNodeLength=5; + + // 0030..003f: Linear-match node, match 1..16 units and continue reading the next node. + static const int32_t kMinLinearMatch=0x30; + static const int32_t kMaxLinearMatchLength=0x10; + + // Match-node lead unit bits 14..6 for the optional intermediate value. + // If these bits are 0, then there is no intermediate value. + // Otherwise, see the *NodeValue* constants below. + static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength; // 0x0040 + static const int32_t kNodeTypeMask=kMinValueLead-1; // 0x003f + + // A final-value node has bit 15 set. + static const int32_t kValueIsFinal=0x8000; + + // Compact value: After testing and masking off bit 15, use the following thresholds. + static const int32_t kMaxOneUnitValue=0x3fff; + + static const int32_t kMinTwoUnitValueLead=kMaxOneUnitValue+1; // 0x4000 + static const int32_t kThreeUnitValueLead=0x7fff; + + static const int32_t kMaxTwoUnitValue=((kThreeUnitValueLead-kMinTwoUnitValueLead)<<16)-1; // 0x3ffeffff + + // Compact intermediate-value integer, lead unit shared with a branch or linear-match node. + static const int32_t kMaxOneUnitNodeValue=0xff; + static const int32_t kMinTwoUnitNodeValueLead=kMinValueLead+((kMaxOneUnitNodeValue+1)<<6); // 0x4040 + static const int32_t kThreeUnitNodeValueLead=0x7fc0; + + static const int32_t kMaxTwoUnitNodeValue= + ((kThreeUnitNodeValueLead-kMinTwoUnitNodeValueLead)<<10)-1; // 0xfdffff + + // Compact delta integers. + static const int32_t kMaxOneUnitDelta=0xfbff; + static const int32_t kMinTwoUnitDeltaLead=kMaxOneUnitDelta+1; // 0xfc00 + static const int32_t kThreeUnitDeltaLead=0xffff; + + static const int32_t kMaxTwoUnitDelta=((kThreeUnitDeltaLead-kMinTwoUnitDeltaLead)<<16)-1; // 0x03feffff + + // For getState64(): + // The remainingMatchLength_ is -1..14=(kMaxLinearMatchLength=0x10)-2 + // so we need at least 5 bits for that. + // We add 2 to store it as a positive value 1..16=kMaxLinearMatchLength. + static constexpr int32_t kState64RemainingShift = 59; + static constexpr uint64_t kState64PosMask = (UINT64_C(1) << kState64RemainingShift) - 1; + + char16_t *ownedArray_; + + // Fixed value referencing the UCharsTrie words. + const char16_t *uchars_; + + // Iterator variables. + + // Pointer to next trie unit to read. nullptr if no more matches. + const char16_t *pos_; + // Remaining length of a linear-match node, minus 1. Negative if not in such a node. + int32_t remainingMatchLength_; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __UCHARSTRIE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstriebuilder.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstriebuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..5c8aa33ffb39f522a552817bb85305fc5e89c5f4 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucharstriebuilder.h @@ -0,0 +1,193 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2016, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* file name: ucharstriebuilder.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2010nov14 +* created by: Markus W. Scherer +*/ + +#ifndef __UCHARSTRIEBUILDER_H__ +#define __UCHARSTRIEBUILDER_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/stringtriebuilder.h" +#include "unicode/ucharstrie.h" +#include "unicode/unistr.h" + +/** + * \file + * \brief C++ API: Builder for icu::UCharsTrie + */ + +U_NAMESPACE_BEGIN + +class UCharsTrieElement; + +/** + * Builder class for UCharsTrie. + * + * This class is not intended for public subclassing. + * @stable ICU 4.8 + */ +class U_COMMON_API UCharsTrieBuilder : public StringTrieBuilder { +public: + /** + * Constructs an empty builder. + * @param errorCode Standard ICU error code. + * @stable ICU 4.8 + */ + UCharsTrieBuilder(UErrorCode &errorCode); + + /** + * Destructor. + * @stable ICU 4.8 + */ + virtual ~UCharsTrieBuilder(); + + /** + * Adds a (string, value) pair. + * The string must be unique. + * The string contents will be copied; the builder does not keep + * a reference to the input UnicodeString or its buffer. + * @param s The input string. + * @param value The value associated with this string. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return *this + * @stable ICU 4.8 + */ + UCharsTrieBuilder &add(const UnicodeString &s, int32_t value, UErrorCode &errorCode); + + /** + * Builds a UCharsTrie for the add()ed data. + * Once built, no further data can be add()ed until clear() is called. + * + * A UCharsTrie cannot be empty. At least one (string, value) pair + * must have been add()ed. + * + * This method passes ownership of the builder's internal result array to the new trie object. + * Another call to any build() variant will re-serialize the trie. + * After clear() has been called, a new array will be used as well. + * @param buildOption Build option, see UStringTrieBuildOption. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return A new UCharsTrie for the add()ed data. + * @stable ICU 4.8 + */ + UCharsTrie *build(UStringTrieBuildOption buildOption, UErrorCode &errorCode); + + /** + * Builds a UCharsTrie for the add()ed data and char16_t-serializes it. + * Once built, no further data can be add()ed until clear() is called. + * + * A UCharsTrie cannot be empty. At least one (string, value) pair + * must have been add()ed. + * + * Multiple calls to buildUnicodeString() set the UnicodeStrings to the + * builder's same char16_t array, without rebuilding. + * If buildUnicodeString() is called after build(), the trie will be + * re-serialized into a new array (because build() passes on ownership). + * If build() is called after buildUnicodeString(), the trie object returned + * by build() will become the owner of the underlying data for the + * previously returned UnicodeString. + * After clear() has been called, a new array will be used as well. + * @param buildOption Build option, see UStringTrieBuildOption. + * @param result A UnicodeString which will be set to the char16_t-serialized + * UCharsTrie for the add()ed data. + * @param errorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return result + * @stable ICU 4.8 + */ + UnicodeString &buildUnicodeString(UStringTrieBuildOption buildOption, UnicodeString &result, + UErrorCode &errorCode); + + /** + * Removes all (string, value) pairs. + * New data can then be add()ed and a new trie can be built. + * @return *this + * @stable ICU 4.8 + */ + UCharsTrieBuilder &clear() { + strings.remove(); + elementsLength=0; + ucharsLength=0; + return *this; + } + +private: + UCharsTrieBuilder(const UCharsTrieBuilder &other) = delete; // no copy constructor + UCharsTrieBuilder &operator=(const UCharsTrieBuilder &other) = delete; // no assignment operator + + void buildUChars(UStringTrieBuildOption buildOption, UErrorCode &errorCode); + + virtual int32_t getElementStringLength(int32_t i) const override; + virtual char16_t getElementUnit(int32_t i, int32_t unitIndex) const override; + virtual int32_t getElementValue(int32_t i) const override; + + virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t unitIndex) const override; + + virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t unitIndex) const override; + virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t unitIndex, int32_t count) const override; + virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t unitIndex, char16_t unit) const override; + + virtual UBool matchNodesCanHaveValues() const override { return true; } + + virtual int32_t getMaxBranchLinearSubNodeLength() const override { return UCharsTrie::kMaxBranchLinearSubNodeLength; } + virtual int32_t getMinLinearMatch() const override { return UCharsTrie::kMinLinearMatch; } + virtual int32_t getMaxLinearMatchLength() const override { return UCharsTrie::kMaxLinearMatchLength; } + + class UCTLinearMatchNode : public LinearMatchNode { + public: + UCTLinearMatchNode(const char16_t *units, int32_t len, Node *nextNode); + virtual bool operator==(const Node &other) const override; + virtual void write(StringTrieBuilder &builder) override; + private: + const char16_t *s; + }; + + virtual Node *createLinearMatchNode(int32_t i, int32_t unitIndex, int32_t length, + Node *nextNode) const override; + + UBool ensureCapacity(int32_t length); + virtual int32_t write(int32_t unit) override; + int32_t write(const char16_t *s, int32_t length); + virtual int32_t writeElementUnits(int32_t i, int32_t unitIndex, int32_t length) override; + virtual int32_t writeValueAndFinal(int32_t i, UBool isFinal) override; + virtual int32_t writeValueAndType(UBool hasValue, int32_t value, int32_t node) override; + virtual int32_t writeDeltaTo(int32_t jumpTarget) override; + + UnicodeString strings; + UCharsTrieElement *elements; + int32_t elementsCapacity; + int32_t elementsLength; + + // char16_t serialization of the trie. + // Grows from the back: ucharsLength measures from the end of the buffer! + char16_t *uchars; + int32_t ucharsCapacity; + int32_t ucharsLength; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif // __UCHARSTRIEBUILDER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchriter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchriter.h new file mode 100644 index 0000000000000000000000000000000000000000..9fae5e7de08feed29c07fcdd080da4b2ce743b8a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uchriter.h @@ -0,0 +1,393 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1998-2005, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +*/ + +#ifndef UCHRITER_H +#define UCHRITER_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/chariter.h" + +/** + * \file + * \brief C++ API: char16_t Character Iterator + */ + +U_NAMESPACE_BEGIN + +/** + * A concrete subclass of CharacterIterator that iterates over the + * characters (code units or code points) in a char16_t array. + * It's possible not only to create an + * iterator that iterates over an entire char16_t array, but also to + * create one that iterates over only a subrange of a char16_t array + * (iterators over different subranges of the same char16_t array don't + * compare equal). + * @see CharacterIterator + * @see ForwardCharacterIterator + * @stable ICU 2.0 + */ +class U_COMMON_API UCharCharacterIterator : public CharacterIterator { +public: + /** + * Create an iterator over the char16_t array referred to by "textPtr". + * The iteration range is 0 to length-1. + * text is only aliased, not adopted (the + * destructor will not delete it). + * @param textPtr The char16_t array to be iterated over + * @param length The length of the char16_t array + * @stable ICU 2.0 + */ + UCharCharacterIterator(ConstChar16Ptr textPtr, int32_t length); + + /** + * Create an iterator over the char16_t array referred to by "textPtr". + * The iteration range is 0 to length-1. + * text is only aliased, not adopted (the + * destructor will not delete it). + * The starting + * position is specified by "position". If "position" is outside the valid + * iteration range, the behavior of this object is undefined. + * @param textPtr The char16_t array to be iterated over + * @param length The length of the char16_t array + * @param position The starting position of the iteration + * @stable ICU 2.0 + */ + UCharCharacterIterator(ConstChar16Ptr textPtr, int32_t length, + int32_t position); + + /** + * Create an iterator over the char16_t array referred to by "textPtr". + * The iteration range is 0 to end-1. + * text is only aliased, not adopted (the + * destructor will not delete it). + * The starting + * position is specified by "position". If begin and end do not + * form a valid iteration range or "position" is outside the valid + * iteration range, the behavior of this object is undefined. + * @param textPtr The char16_t array to be iterated over + * @param length The length of the char16_t array + * @param textBegin The begin position of the iteration range + * @param textEnd The end position of the iteration range + * @param position The starting position of the iteration + * @stable ICU 2.0 + */ + UCharCharacterIterator(ConstChar16Ptr textPtr, int32_t length, + int32_t textBegin, + int32_t textEnd, + int32_t position); + + /** + * Copy constructor. The new iterator iterates over the same range + * of the same string as "that", and its initial position is the + * same as "that"'s current position. + * @param that The UCharCharacterIterator to be copied + * @stable ICU 2.0 + */ + UCharCharacterIterator(const UCharCharacterIterator& that); + + /** + * Destructor. + * @stable ICU 2.0 + */ + virtual ~UCharCharacterIterator(); + + /** + * Assignment operator. *this is altered to iterate over the sane + * range of the same string as "that", and refers to the same + * character within that string as "that" does. + * @param that The object to be copied + * @return the newly created object + * @stable ICU 2.0 + */ + UCharCharacterIterator& + operator=(const UCharCharacterIterator& that); + + /** + * Returns true if the iterators iterate over the same range of the + * same string and are pointing at the same character. + * @param that The ForwardCharacterIterator used to be compared for equality + * @return true if the iterators iterate over the same range of the + * same string and are pointing at the same character. + * @stable ICU 2.0 + */ + virtual bool operator==(const ForwardCharacterIterator& that) const override; + + /** + * Generates a hash code for this iterator. + * @return the hash code. + * @stable ICU 2.0 + */ + virtual int32_t hashCode(void) const override; + + /** + * Returns a new UCharCharacterIterator referring to the same + * character in the same range of the same string as this one. The + * caller must delete the new iterator. + * @return the CharacterIterator newly created + * @stable ICU 2.0 + */ + virtual UCharCharacterIterator* clone() const override; + + /** + * Sets the iterator to refer to the first code unit in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with next(). + * @return the first code unit in its iteration range. + * @stable ICU 2.0 + */ + virtual char16_t first(void) override; + + /** + * Sets the iterator to refer to the first code unit in its + * iteration range, returns that code unit, and moves the position + * to the second code unit. This is an alternative to setToStart() + * for forward iteration with nextPostInc(). + * @return the first code unit in its iteration range + * @stable ICU 2.0 + */ + virtual char16_t firstPostInc(void) override; + + /** + * Sets the iterator to refer to the first code point in its + * iteration range, and returns that code unit, + * This can be used to begin an iteration with next32(). + * Note that an iteration with next32PostInc(), beginning with, + * e.g., setToStart() or firstPostInc(), is more efficient. + * @return the first code point in its iteration range + * @stable ICU 2.0 + */ + virtual UChar32 first32(void) override; + + /** + * Sets the iterator to refer to the first code point in its + * iteration range, returns that code point, and moves the position + * to the second code point. This is an alternative to setToStart() + * for forward iteration with next32PostInc(). + * @return the first code point in its iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 first32PostInc(void) override; + + /** + * Sets the iterator to refer to the last code unit in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with previous(). + * @return the last code unit in its iteration range. + * @stable ICU 2.0 + */ + virtual char16_t last(void) override; + + /** + * Sets the iterator to refer to the last code point in its + * iteration range, and returns that code unit. + * This can be used to begin an iteration with previous32(). + * @return the last code point in its iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 last32(void) override; + + /** + * Sets the iterator to refer to the "position"-th code unit + * in the text-storage object the iterator refers to, and + * returns that code unit. + * @param position the position within the text-storage object + * @return the code unit + * @stable ICU 2.0 + */ + virtual char16_t setIndex(int32_t position) override; + + /** + * Sets the iterator to refer to the beginning of the code point + * that contains the "position"-th code unit + * in the text-storage object the iterator refers to, and + * returns that code point. + * The current position is adjusted to the beginning of the code point + * (its first code unit). + * @param position the position within the text-storage object + * @return the code unit + * @stable ICU 2.0 + */ + virtual UChar32 setIndex32(int32_t position) override; + + /** + * Returns the code unit the iterator currently refers to. + * @return the code unit the iterator currently refers to. + * @stable ICU 2.0 + */ + virtual char16_t current(void) const override; + + /** + * Returns the code point the iterator currently refers to. + * @return the code point the iterator currently refers to. + * @stable ICU 2.0 + */ + virtual UChar32 current32(void) const override; + + /** + * Advances to the next code unit in the iteration range (toward + * endIndex()), and returns that code unit. If there are no more + * code units to return, returns DONE. + * @return the next code unit in the iteration range. + * @stable ICU 2.0 + */ + virtual char16_t next(void) override; + + /** + * Gets the current code unit for returning and advances to the next code unit + * in the iteration range + * (toward endIndex()). If there are + * no more code units to return, returns DONE. + * @return the current code unit. + * @stable ICU 2.0 + */ + virtual char16_t nextPostInc(void) override; + + /** + * Advances to the next code point in the iteration range (toward + * endIndex()), and returns that code point. If there are no more + * code points to return, returns DONE. + * Note that iteration with "pre-increment" semantics is less + * efficient than iteration with "post-increment" semantics + * that is provided by next32PostInc(). + * @return the next code point in the iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 next32(void) override; + + /** + * Gets the current code point for returning and advances to the next code point + * in the iteration range + * (toward endIndex()). If there are + * no more code points to return, returns DONE. + * @return the current point. + * @stable ICU 2.0 + */ + virtual UChar32 next32PostInc(void) override; + + /** + * Returns false if there are no more code units or code points + * at or after the current position in the iteration range. + * This is used with nextPostInc() or next32PostInc() in forward + * iteration. + * @return false if there are no more code units or code points + * at or after the current position in the iteration range. + * @stable ICU 2.0 + */ + virtual UBool hasNext() override; + + /** + * Advances to the previous code unit in the iteration range (toward + * startIndex()), and returns that code unit. If there are no more + * code units to return, returns DONE. + * @return the previous code unit in the iteration range. + * @stable ICU 2.0 + */ + virtual char16_t previous(void) override; + + /** + * Advances to the previous code point in the iteration range (toward + * startIndex()), and returns that code point. If there are no more + * code points to return, returns DONE. + * @return the previous code point in the iteration range. + * @stable ICU 2.0 + */ + virtual UChar32 previous32(void) override; + + /** + * Returns false if there are no more code units or code points + * before the current position in the iteration range. + * This is used with previous() or previous32() in backward + * iteration. + * @return false if there are no more code units or code points + * before the current position in the iteration range. + * @stable ICU 2.0 + */ + virtual UBool hasPrevious() override; + + /** + * Moves the current position relative to the start or end of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code units forward + * or backward by specifying a positive or negative delta. + * @param delta the position relative to origin. A positive delta means forward; + * a negative delta means backward. + * @param origin Origin enumeration {kStart, kCurrent, kEnd} + * @return the new position + * @stable ICU 2.0 + */ + virtual int32_t move(int32_t delta, EOrigin origin) override; + + /** + * Moves the current position relative to the start or end of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code points forward + * or backward by specifying a positive or negative delta. + * @param delta the position relative to origin. A positive delta means forward; + * a negative delta means backward. + * @param origin Origin enumeration {kStart, kCurrent, kEnd} + * @return the new position + * @stable ICU 2.0 + */ +#ifdef move32 + // One of the system headers right now is sometimes defining a conflicting macro we don't use +#undef move32 +#endif + virtual int32_t move32(int32_t delta, EOrigin origin) override; + + /** + * Sets the iterator to iterate over a new range of text + * @stable ICU 2.0 + */ + void setText(ConstChar16Ptr newText, int32_t newTextLength); + + /** + * Copies the char16_t array under iteration into the UnicodeString + * referred to by "result". Even if this iterator iterates across + * only a part of this string, the whole string is copied. + * @param result Receives a copy of the text under iteration. + * @stable ICU 2.0 + */ + virtual void getText(UnicodeString& result) override; + + /** + * Return a class ID for this class (not really public) + * @return a class ID for this class + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Return a class ID for this object (not really public) + * @return a class ID for this object. + * @stable ICU 2.0 + */ + virtual UClassID getDynamicClassID(void) const override; + +protected: + /** + * Protected constructor + * @stable ICU 2.0 + */ + UCharCharacterIterator(); + /** + * Protected member text + * @stable ICU 2.0 + */ + const char16_t* text; + +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uclean.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uclean.h new file mode 100644 index 0000000000000000000000000000000000000000..f5b0aa088a94143245fca9ef03ad342ab408f231 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uclean.h @@ -0,0 +1,262 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* Copyright (C) 2001-2014, International Business Machines +* Corporation and others. All Rights Reserved. +****************************************************************************** +* file name: uclean.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2001July05 +* created by: George Rhoten +*/ + +#ifndef __UCLEAN_H__ +#define __UCLEAN_H__ + +#include "unicode/utypes.h" +/** + * \file + * \brief C API: Initialize and clean up ICU + */ + +/** + * Initialize ICU. + * + * Use of this function is optional. It is OK to simply use ICU + * services and functions without first having initialized + * ICU by calling u_init(). + * + * u_init() will attempt to load some part of ICU's data, and is + * useful as a test for configuration or installation problems that + * leave the ICU data inaccessible. A successful invocation of u_init() + * does not, however, guarantee that all ICU data is accessible. + * + * Multiple calls to u_init() cause no harm, aside from the small amount + * of time required. + * + * In old versions of ICU, u_init() was required in multi-threaded applications + * to ensure the thread safety of ICU. u_init() is no longer needed for this purpose. + * + * @param status An ICU UErrorCode parameter. It must not be NULL. + * An Error will be returned if some required part of ICU data can not + * be loaded or initialized. + * The function returns immediately if the input error code indicates a + * failure, as usual. + * + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +u_init(UErrorCode *status); + +#ifndef U_HIDE_SYSTEM_API +/** + * Clean up the system resources, such as allocated memory or open files, + * used in all ICU libraries. This will free/delete all memory owned by the + * ICU libraries, and return them to their original load state. All open ICU + * items (collators, resource bundles, converters, etc.) must be closed before + * calling this function, otherwise ICU may not free its allocated memory + * (e.g. close your converters and resource bundles before calling this + * function). Generally, this function should be called once just before + * an application exits. For applications that dynamically load and unload + * the ICU libraries (relatively uncommon), u_cleanup() should be called + * just before the library unload. + *

+ * u_cleanup() also clears any ICU heap functions, mutex functions or + * trace functions that may have been set for the process. + * This has the effect of restoring ICU to its initial condition, before + * any of these override functions were installed. Refer to + * u_setMemoryFunctions(), u_setMutexFunctions and + * utrace_setFunctions(). If ICU is to be reinitialized after + * calling u_cleanup(), these runtime override functions will need to + * be set up again if they are still required. + *

+ * u_cleanup() is not thread safe. All other threads should stop using ICU + * before calling this function. + *

+ * Any open ICU items will be left in an undefined state by u_cleanup(), + * and any subsequent attempt to use such an item will give unpredictable + * results. + *

+ * After calling u_cleanup(), an application may continue to use ICU by + * calling u_init(). An application must invoke u_init() first from one single + * thread before allowing other threads call u_init(). All threads existing + * at the time of the first thread's call to u_init() must also call + * u_init() themselves before continuing with other ICU operations. + *

+ * The use of u_cleanup() just before an application terminates is optional, + * but it should be called only once for performance reasons. The primary + * benefit is to eliminate reports of memory or resource leaks originating + * in ICU code from the results generated by heap analysis tools. + *

+ * Use this function with great care! + *

+ * + * @stable ICU 2.0 + * @system + */ +U_CAPI void U_EXPORT2 +u_cleanup(void); + +U_CDECL_BEGIN +/** + * Pointer type for a user supplied memory allocation function. + * @param context user supplied value, obtained from u_setMemoryFunctions(). + * @param size The number of bytes to be allocated + * @return Pointer to the newly allocated memory, or NULL if the allocation failed. + * @stable ICU 2.8 + * @system + */ +typedef void *U_CALLCONV UMemAllocFn(const void *context, size_t size); +/** + * Pointer type for a user supplied memory re-allocation function. + * @param context user supplied value, obtained from u_setMemoryFunctions(). + * @param mem Pointer to the memory block to be resized. + * @param size The new size for the block. + * @return Pointer to the newly allocated memory, or NULL if the allocation failed. + * @stable ICU 2.8 + * @system + */ +typedef void *U_CALLCONV UMemReallocFn(const void *context, void *mem, size_t size); +/** + * Pointer type for a user supplied memory free function. Behavior should be + * similar the standard C library free(). + * @param context user supplied value, obtained from u_setMemoryFunctions(). + * @param mem Pointer to the memory block to be freed. + * @return Pointer to the resized memory block, or NULL if the resizing failed. + * @stable ICU 2.8 + * @system + */ +typedef void U_CALLCONV UMemFreeFn (const void *context, void *mem); + +/** + * Set the functions that ICU will use for memory allocation. + * Use of this function is optional; by default (without this function), ICU will + * use the standard C library malloc() and free() functions. + * This function can only be used when ICU is in an initial, unused state, before + * u_init() has been called. + * @param context This pointer value will be saved, and then (later) passed as + * a parameter to the memory functions each time they + * are called. + * @param a Pointer to a user-supplied malloc function. + * @param r Pointer to a user-supplied realloc function. + * @param f Pointer to a user-supplied free function. + * @param status Receives error values. + * @stable ICU 2.8 + * @system + */ +U_CAPI void U_EXPORT2 +u_setMemoryFunctions(const void *context, UMemAllocFn * U_CALLCONV_FPTR a, UMemReallocFn * U_CALLCONV_FPTR r, UMemFreeFn * U_CALLCONV_FPTR f, + UErrorCode *status); + +U_CDECL_END + +#ifndef U_HIDE_DEPRECATED_API +/********************************************************************************* + * + * Deprecated Functions + * + * The following functions for user supplied mutexes are no longer supported. + * Any attempt to use them will return a U_UNSUPPORTED_ERROR. + * + **********************************************************************************/ + +/** + * An opaque pointer type that represents an ICU mutex. + * For user-implemented mutexes, the value will typically point to a + * struct or object that implements the mutex. + * @deprecated ICU 52. This type is no longer supported. + * @system + */ +typedef void *UMTX; + +U_CDECL_BEGIN +/** + * Function Pointer type for a user supplied mutex initialization function. + * The user-supplied function will be called by ICU whenever ICU needs to create a + * new mutex. The function implementation should create a mutex, and store a pointer + * to something that uniquely identifies the mutex into the UMTX that is supplied + * as a parameter. + * @param context user supplied value, obtained from u_setMutexFunctions(). + * @param mutex Receives a pointer that identifies the new mutex. + * The mutex init function must set the UMTX to a non-null value. + * Subsequent calls by ICU to lock, unlock, or destroy a mutex will + * identify the mutex by the UMTX value. + * @param status Error status. Report errors back to ICU by setting this variable + * with an error code. + * @deprecated ICU 52. This function is no longer supported. + * @system + */ +typedef void U_CALLCONV UMtxInitFn (const void *context, UMTX *mutex, UErrorCode* status); + + +/** + * Function Pointer type for a user supplied mutex functions. + * One of the user-supplied functions with this signature will be called by ICU + * whenever ICU needs to lock, unlock, or destroy a mutex. + * @param context user supplied value, obtained from u_setMutexFunctions(). + * @param mutex specify the mutex on which to operate. + * @deprecated ICU 52. This function is no longer supported. + * @system + */ +typedef void U_CALLCONV UMtxFn (const void *context, UMTX *mutex); +U_CDECL_END + +/** + * Set the functions that ICU will use for mutex operations + * Use of this function is optional; by default (without this function), ICU will + * directly access system functions for mutex operations + * This function can only be used when ICU is in an initial, unused state, before + * u_init() has been called. + * @param context This pointer value will be saved, and then (later) passed as + * a parameter to the user-supplied mutex functions each time they + * are called. + * @param init Pointer to a mutex initialization function. Must be non-null. + * @param destroy Pointer to the mutex destroy function. Must be non-null. + * @param lock pointer to the mutex lock function. Must be non-null. + * @param unlock Pointer to the mutex unlock function. Must be non-null. + * @param status Receives error values. + * @deprecated ICU 52. This function is no longer supported. + * @system + */ +U_DEPRECATED void U_EXPORT2 +u_setMutexFunctions(const void *context, UMtxInitFn *init, UMtxFn *destroy, UMtxFn *lock, UMtxFn *unlock, + UErrorCode *status); + + +/** + * Pointer type for a user supplied atomic increment or decrement function. + * @param context user supplied value, obtained from u_setAtomicIncDecFunctions(). + * @param p Pointer to a 32 bit int to be incremented or decremented + * @return The value of the variable after the inc or dec operation. + * @deprecated ICU 52. This function is no longer supported. + * @system + */ +typedef int32_t U_CALLCONV UMtxAtomicFn(const void *context, int32_t *p); + +/** + * Set the functions that ICU will use for atomic increment and decrement of int32_t values. + * Use of this function is optional; by default (without this function), ICU will + * use its own internal implementation of atomic increment/decrement. + * This function can only be used when ICU is in an initial, unused state, before + * u_init() has been called. + * @param context This pointer value will be saved, and then (later) passed as + * a parameter to the increment and decrement functions each time they + * are called. This function can only be called + * @param inc Pointer to a function to do an atomic increment operation. Must be non-null. + * @param dec Pointer to a function to do an atomic decrement operation. Must be non-null. + * @param status Receives error values. + * @deprecated ICU 52. This function is no longer supported. + * @system + */ +U_DEPRECATED void U_EXPORT2 +u_setAtomicIncDecFunctions(const void *context, UMtxAtomicFn *inc, UMtxAtomicFn *dec, + UErrorCode *status); + +#endif /* U_HIDE_DEPRECATED_API */ +#endif /* U_HIDE_SYSTEM_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv.h new file mode 100644 index 0000000000000000000000000000000000000000..20c173b662832ddbbceaf17ce7fa370406e33d0b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv.h @@ -0,0 +1,2056 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2014, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** + * ucnv.h: + * External APIs for the ICU's codeset conversion library + * Bertrand A. Damiba + * + * Modification History: + * + * Date Name Description + * 04/04/99 helena Fixed internal header inclusion. + * 05/11/00 helena Added setFallback and usesFallback APIs. + * 06/29/2000 helena Major rewrite of the callback APIs. + * 12/07/2000 srl Update of documentation + */ + +/** + * \file + * \brief C API: Character conversion + * + *

Character Conversion C API

+ * + *

This API is used to convert codepage or character encoded data to and + * from UTF-16. You can open a converter with {@link ucnv_open() }. With that + * converter, you can get its properties, set options, convert your data and + * close the converter.

+ * + *

Since many software programs recognize different converter names for + * different types of converters, there are other functions in this API to + * iterate over the converter aliases. The functions {@link ucnv_getAvailableName() }, + * {@link ucnv_getAlias() } and {@link ucnv_getStandardName() } are some of the + * more frequently used alias functions to get this information.

+ * + *

When a converter encounters an illegal, irregular, invalid or unmappable character + * its default behavior is to use a substitution character to replace the + * bad byte sequence. This behavior can be changed by using {@link ucnv_setFromUCallBack() } + * or {@link ucnv_setToUCallBack() } on the converter. The header ucnv_err.h defines + * many other callback actions that can be used instead of a character substitution.

+ * + *

More information about this API can be found in our + * User Guide.

+ */ + +#ifndef UCNV_H +#define UCNV_H + +#include "unicode/ucnv_err.h" +#include "unicode/uenum.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +#if !defined(USET_DEFINED) && !defined(U_IN_DOXYGEN) + +#define USET_DEFINED + +/** + * USet is the C API type corresponding to C++ class UnicodeSet. + * It is forward-declared here to avoid including unicode/uset.h file if related + * conversion APIs are not used. + * + * @see ucnv_getUnicodeSet + * @stable ICU 2.4 + */ +typedef struct USet USet; + +#endif + +#if !UCONFIG_NO_CONVERSION + +U_CDECL_BEGIN + +/** Maximum length of a converter name including the terminating NULL @stable ICU 2.0 */ +#define UCNV_MAX_CONVERTER_NAME_LENGTH 60 +/** Maximum length of a converter name including path and terminating NULL @stable ICU 2.0 */ +#define UCNV_MAX_FULL_FILE_NAME_LENGTH (600+UCNV_MAX_CONVERTER_NAME_LENGTH) + +/** Shift in for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */ +#define UCNV_SI 0x0F +/** Shift out for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */ +#define UCNV_SO 0x0E + +/** + * Enum for specifying basic types of converters + * @see ucnv_getType + * @stable ICU 2.0 + */ +typedef enum { + /** @stable ICU 2.0 */ + UCNV_UNSUPPORTED_CONVERTER = -1, + /** @stable ICU 2.0 */ + UCNV_SBCS = 0, + /** @stable ICU 2.0 */ + UCNV_DBCS = 1, + /** @stable ICU 2.0 */ + UCNV_MBCS = 2, + /** @stable ICU 2.0 */ + UCNV_LATIN_1 = 3, + /** @stable ICU 2.0 */ + UCNV_UTF8 = 4, + /** @stable ICU 2.0 */ + UCNV_UTF16_BigEndian = 5, + /** @stable ICU 2.0 */ + UCNV_UTF16_LittleEndian = 6, + /** @stable ICU 2.0 */ + UCNV_UTF32_BigEndian = 7, + /** @stable ICU 2.0 */ + UCNV_UTF32_LittleEndian = 8, + /** @stable ICU 2.0 */ + UCNV_EBCDIC_STATEFUL = 9, + /** @stable ICU 2.0 */ + UCNV_ISO_2022 = 10, + + /** @stable ICU 2.0 */ + UCNV_LMBCS_1 = 11, + /** @stable ICU 2.0 */ + UCNV_LMBCS_2, + /** @stable ICU 2.0 */ + UCNV_LMBCS_3, + /** @stable ICU 2.0 */ + UCNV_LMBCS_4, + /** @stable ICU 2.0 */ + UCNV_LMBCS_5, + /** @stable ICU 2.0 */ + UCNV_LMBCS_6, + /** @stable ICU 2.0 */ + UCNV_LMBCS_8, + /** @stable ICU 2.0 */ + UCNV_LMBCS_11, + /** @stable ICU 2.0 */ + UCNV_LMBCS_16, + /** @stable ICU 2.0 */ + UCNV_LMBCS_17, + /** @stable ICU 2.0 */ + UCNV_LMBCS_18, + /** @stable ICU 2.0 */ + UCNV_LMBCS_19, + /** @stable ICU 2.0 */ + UCNV_LMBCS_LAST = UCNV_LMBCS_19, + /** @stable ICU 2.0 */ + UCNV_HZ, + /** @stable ICU 2.0 */ + UCNV_SCSU, + /** @stable ICU 2.0 */ + UCNV_ISCII, + /** @stable ICU 2.0 */ + UCNV_US_ASCII, + /** @stable ICU 2.0 */ + UCNV_UTF7, + /** @stable ICU 2.2 */ + UCNV_BOCU1, + /** @stable ICU 2.2 */ + UCNV_UTF16, + /** @stable ICU 2.2 */ + UCNV_UTF32, + /** @stable ICU 2.2 */ + UCNV_CESU8, + /** @stable ICU 2.4 */ + UCNV_IMAP_MAILBOX, + /** @stable ICU 4.8 */ + UCNV_COMPOUND_TEXT, + + /* Number of converter types for which we have conversion routines. */ + UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES +} UConverterType; + +/** + * Enum for specifying which platform a converter ID refers to. + * The use of platform/CCSID is not recommended. See ucnv_openCCSID(). + * + * @see ucnv_getPlatform + * @see ucnv_openCCSID + * @see ucnv_getCCSID + * @stable ICU 2.0 + */ +typedef enum { + UCNV_UNKNOWN = -1, + UCNV_IBM = 0 +} UConverterPlatform; + +/** + * Function pointer for error callback in the codepage to unicode direction. + * Called when an error has occurred in conversion to unicode, or on open/close of the callback (see reason). + * @param context Pointer to the callback's private data + * @param args Information about the conversion in progress + * @param codeUnits Points to 'length' bytes of the concerned codepage sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param reason Defines the reason the callback was invoked + * @param pErrorCode ICU error code in/out parameter. + * For converter callback functions, set to a conversion error + * before the call, and the callback may reset it to U_ZERO_ERROR. + * @see ucnv_setToUCallBack + * @see UConverterToUnicodeArgs + * @stable ICU 2.0 + */ +typedef void (U_EXPORT2 *UConverterToUCallback) ( + const void* context, + UConverterToUnicodeArgs *args, + const char *codeUnits, + int32_t length, + UConverterCallbackReason reason, + UErrorCode *pErrorCode); + +/** + * Function pointer for error callback in the unicode to codepage direction. + * Called when an error has occurred in conversion from unicode, or on open/close of the callback (see reason). + * @param context Pointer to the callback's private data + * @param args Information about the conversion in progress + * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. + * @param reason Defines the reason the callback was invoked + * @param pErrorCode ICU error code in/out parameter. + * For converter callback functions, set to a conversion error + * before the call, and the callback may reset it to U_ZERO_ERROR. + * @see ucnv_setFromUCallBack + * @stable ICU 2.0 + */ +typedef void (U_EXPORT2 *UConverterFromUCallback) ( + const void* context, + UConverterFromUnicodeArgs *args, + const UChar* codeUnits, + int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode *pErrorCode); + +U_CDECL_END + +/** + * Character that separates converter names from options and options from each other. + * @see ucnv_open + * @stable ICU 2.0 + */ +#define UCNV_OPTION_SEP_CHAR ',' + +/** + * String version of UCNV_OPTION_SEP_CHAR. + * @see ucnv_open + * @stable ICU 2.0 + */ +#define UCNV_OPTION_SEP_STRING "," + +/** + * Character that separates a converter option from its value. + * @see ucnv_open + * @stable ICU 2.0 + */ +#define UCNV_VALUE_SEP_CHAR '=' + +/** + * String version of UCNV_VALUE_SEP_CHAR. + * @see ucnv_open + * @stable ICU 2.0 + */ +#define UCNV_VALUE_SEP_STRING "=" + +/** + * Converter option for specifying a locale. + * For example, ucnv_open("SCSU,locale=ja", &errorCode); + * See convrtrs.txt. + * + * @see ucnv_open + * @stable ICU 2.0 + */ +#define UCNV_LOCALE_OPTION_STRING ",locale=" + +/** + * Converter option for specifying a version selector (0..9) for some converters. + * For example, + * \code + * ucnv_open("UTF-7,version=1", &errorCode); + * \endcode + * See convrtrs.txt. + * + * @see ucnv_open + * @stable ICU 2.4 + */ +#define UCNV_VERSION_OPTION_STRING ",version=" + +/** + * Converter option for EBCDIC SBCS or mixed-SBCS/DBCS (stateful) codepages. + * Swaps Unicode mappings for EBCDIC LF and NL codes, as used on + * S/390 (z/OS) Unix System Services (Open Edition). + * For example, ucnv_open("ibm-1047,swaplfnl", &errorCode); + * See convrtrs.txt. + * + * @see ucnv_open + * @stable ICU 2.4 + */ +#define UCNV_SWAP_LFNL_OPTION_STRING ",swaplfnl" + +/** + * Do a fuzzy compare of two converter/alias names. + * The comparison is case-insensitive, ignores leading zeroes if they are not + * followed by further digits, and ignores all but letters and digits. + * Thus the strings "UTF-8", "utf_8", "u*T@f08" and "Utf 8" are exactly equivalent. + * See section 1.4, Charset Alias Matching in Unicode Technical Standard #22 + * at http://www.unicode.org/reports/tr22/ + * + * @param name1 a converter name or alias, zero-terminated + * @param name2 a converter name or alias, zero-terminated + * @return 0 if the names match, or a negative value if the name1 + * lexically precedes name2, or a positive value if the name1 + * lexically follows name2. + * @stable ICU 2.0 + */ +U_CAPI int U_EXPORT2 +ucnv_compareNames(const char *name1, const char *name2); + + +/** + * Creates a UConverter object with the name of a coded character set specified as a C string. + * The actual name will be resolved with the alias file + * using a case-insensitive string comparison that ignores + * leading zeroes and all non-alphanumeric characters. + * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent. + * (See also ucnv_compareNames().) + * If NULL is passed for the converter name, it will create one with the + * getDefaultName return value. + * + *

A converter name for ICU 1.5 and above may contain options + * like a locale specification to control the specific behavior of + * the newly instantiated converter. + * The meaning of the options depends on the particular converter. + * If an option is not defined for or recognized by a given converter, then it is ignored.

+ * + *

Options are appended to the converter name string, with a + * UCNV_OPTION_SEP_CHAR between the name and the first option and + * also between adjacent options.

+ * + *

If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.

+ * + *

The conversion behavior and names can vary between platforms. ICU may + * convert some characters differently from other platforms. Details on this topic + * are in the User + * Guide. Aliases starting with a "cp" prefix have no specific meaning + * other than its an alias starting with the letters "cp". Please do not + * associate any meaning to these aliases.

+ * + * \snippet samples/ucnv/convsamp.cpp ucnv_open + * + * @param converterName Name of the coded character set table. + * This may have options appended to the string. + * IANA alias character set names, IBM CCSIDs starting with "ibm-", + * Windows codepage numbers starting with "windows-" are frequently + * used for this parameter. See ucnv_getAvailableName and + * ucnv_getAlias for a complete list that is available. + * If this parameter is NULL, the default converter will be used. + * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR + * @return the created Unicode converter object, or NULL if an error occurred + * @see ucnv_openU + * @see ucnv_openCCSID + * @see ucnv_getAvailableName + * @see ucnv_getAlias + * @see ucnv_getDefaultName + * @see ucnv_close + * @see ucnv_compareNames + * @stable ICU 2.0 + */ +U_CAPI UConverter* U_EXPORT2 +ucnv_open(const char *converterName, UErrorCode *err); + + +/** + * Creates a Unicode converter with the names specified as unicode string. + * The name should be limited to the ASCII-7 alphanumerics range. + * The actual name will be resolved with the alias file + * using a case-insensitive string comparison that ignores + * leading zeroes and all non-alphanumeric characters. + * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent. + * (See also ucnv_compareNames().) + * If NULL is passed for the converter name, it will create + * one with the ucnv_getDefaultName() return value. + * If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. + * + *

See ucnv_open for the complete details

+ * @param name Name of the UConverter table in a zero terminated + * Unicode string + * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, + * U_FILE_ACCESS_ERROR + * @return the created Unicode converter object, or NULL if an + * error occurred + * @see ucnv_open + * @see ucnv_openCCSID + * @see ucnv_close + * @see ucnv_compareNames + * @stable ICU 2.0 + */ +U_CAPI UConverter* U_EXPORT2 +ucnv_openU(const UChar *name, + UErrorCode *err); + +/** + * Creates a UConverter object from a CCSID number and platform pair. + * Note that the usefulness of this function is limited to platforms with numeric + * encoding IDs. Only IBM and Microsoft platforms use numeric (16-bit) identifiers for + * encodings. + * + * In addition, IBM CCSIDs and Unicode conversion tables are not 1:1 related. + * For many IBM CCSIDs there are multiple (up to six) Unicode conversion tables, and + * for some Unicode conversion tables there are multiple CCSIDs. + * Some "alternate" Unicode conversion tables are provided by the + * IBM CDRA conversion table registry. + * The most prominent example of a systematic modification of conversion tables that is + * not provided in the form of conversion table files in the repository is + * that S/390 Unix System Services swaps the codes for Line Feed and New Line in all + * EBCDIC codepages, which requires such a swap in the Unicode conversion tables as well. + * + * Only IBM default conversion tables are accessible with ucnv_openCCSID(). + * ucnv_getCCSID() will return the same CCSID for all conversion tables that are associated + * with that CCSID. + * + * Currently, the only "platform" supported in the ICU converter API is UCNV_IBM. + * + * In summary, the use of CCSIDs and the associated API functions is not recommended. + * + * In order to open a converter with the default IBM CDRA Unicode conversion table, + * you can use this function or use the prefix "ibm-": + * \code + * char name[20]; + * sprintf(name, "ibm-%hu", ccsid); + * cnv=ucnv_open(name, &errorCode); + * \endcode + * + * In order to open a converter with the IBM S/390 Unix System Services variant + * of a Unicode/EBCDIC conversion table, + * you can use the prefix "ibm-" together with the option string UCNV_SWAP_LFNL_OPTION_STRING: + * \code + * char name[20]; + * sprintf(name, "ibm-%hu" UCNV_SWAP_LFNL_OPTION_STRING, ccsid); + * cnv=ucnv_open(name, &errorCode); + * \endcode + * + * In order to open a converter from a Microsoft codepage number, use the prefix "cp": + * \code + * char name[20]; + * sprintf(name, "cp%hu", codepageID); + * cnv=ucnv_open(name, &errorCode); + * \endcode + * + * If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. + * + * @param codepage codepage number to create + * @param platform the platform in which the codepage number exists + * @param err error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR + * @return the created Unicode converter object, or NULL if an error + * occurred. + * @see ucnv_open + * @see ucnv_openU + * @see ucnv_close + * @see ucnv_getCCSID + * @see ucnv_getPlatform + * @see UConverterPlatform + * @stable ICU 2.0 + */ +U_CAPI UConverter* U_EXPORT2 +ucnv_openCCSID(int32_t codepage, + UConverterPlatform platform, + UErrorCode * err); + +/** + *

Creates a UConverter object specified from a packageName and a converterName.

+ * + *

The packageName and converterName must point to an ICU udata object, as defined by + * udata_open( packageName, "cnv", converterName, err) or equivalent. + * Typically, packageName will refer to a (.dat) file, or to a package registered with + * udata_setAppData(). Using a full file or directory pathname for packageName is deprecated.

+ * + *

The name will NOT be looked up in the alias mechanism, nor will the converter be + * stored in the converter cache or the alias table. The only way to open further converters + * is call this function multiple times, or use the ucnv_clone() function to clone a + * 'primary' converter.

+ * + *

A future version of ICU may add alias table lookups and/or caching + * to this function.

+ * + *

Example Use: + * cnv = ucnv_openPackage("myapp", "myconverter", &err); + *

+ * + * @param packageName name of the package (equivalent to 'path' in udata_open() call) + * @param converterName name of the data item to be used, without suffix. + * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR + * @return the created Unicode converter object, or NULL if an error occurred + * @see udata_open + * @see ucnv_open + * @see ucnv_clone + * @see ucnv_close + * @stable ICU 2.2 + */ +U_CAPI UConverter* U_EXPORT2 +ucnv_openPackage(const char *packageName, const char *converterName, UErrorCode *err); + +/** + * Thread safe converter cloning operation. + * + * You must ucnv_close() the clone. + * + * @param cnv converter to be cloned + * @param status to indicate whether the operation went on smoothly or there were errors + * @return pointer to the new clone + * @stable ICU 71 + */ +U_CAPI UConverter* U_EXPORT2 ucnv_clone(const UConverter *cnv, UErrorCode *status); + +#ifndef U_HIDE_DEPRECATED_API + +/** + * Thread safe converter cloning operation. + * For most efficient operation, pass in a stackBuffer (and a *pBufferSize) + * with at least U_CNV_SAFECLONE_BUFFERSIZE bytes of space. + * If the buffer size is sufficient, then the clone will use the stack buffer; + * otherwise, it will be allocated, and *pBufferSize will indicate + * the actual size. (This should not occur with U_CNV_SAFECLONE_BUFFERSIZE.) + * + * You must ucnv_close() the clone in any case. + * + * If *pBufferSize==0, (regardless of whether stackBuffer==NULL or not) + * then *pBufferSize will be changed to a sufficient size + * for cloning this converter, + * without actually cloning the converter ("pure pre-flighting"). + * + * If *pBufferSize is greater than zero but not large enough for a stack-based + * clone, then the converter is cloned using newly allocated memory + * and *pBufferSize is changed to the necessary size. + * + * If the converter clone fits into the stack buffer but the stack buffer is not + * sufficiently aligned for the clone, then the clone will use an + * adjusted pointer and use an accordingly smaller buffer size. + * + * @param cnv converter to be cloned + * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
+ * user allocated space for the new clone. If NULL new memory will be allocated. + * If buffer is not large enough, new memory will be allocated. + * Clients can use the U_CNV_SAFECLONE_BUFFERSIZE. This will probably be enough to avoid memory allocations. + * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
+ * pointer to size of allocated space. + * @param status to indicate whether the operation went on smoothly or there were errors + * An informational status value, U_SAFECLONE_ALLOCATED_WARNING, + * is used if pBufferSize != NULL and any allocations were necessary + * However, it is better to check if *pBufferSize grew for checking for + * allocations because warning codes can be overridden by subsequent + * function calls. + * @return pointer to the new clone + * @deprecated ICU 71 Use ucnv_clone() instead. + */ +U_DEPRECATED UConverter * U_EXPORT2 +ucnv_safeClone(const UConverter *cnv, + void *stackBuffer, + int32_t *pBufferSize, + UErrorCode *status); + +/** + * \def U_CNV_SAFECLONE_BUFFERSIZE + * Definition of a buffer size that is designed to be large enough for + * converters to be cloned with ucnv_safeClone(). + * @deprecated ICU 52. Do not rely on ucnv_safeClone() cloning into any provided buffer. + */ +#define U_CNV_SAFECLONE_BUFFERSIZE 1024 + +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Deletes the unicode converter and releases resources associated + * with just this instance. + * Does not free up shared converter tables. + * + * @param converter the converter object to be deleted + * @see ucnv_open + * @see ucnv_openU + * @see ucnv_openCCSID + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_close(UConverter * converter); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUConverterPointer + * "Smart pointer" class, closes a UConverter via ucnv_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterPointer, UConverter, ucnv_close); + +U_NAMESPACE_END + +#endif + +/** + * Fills in the output parameter, subChars, with the substitution characters + * as multiple bytes. + * If ucnv_setSubstString() set a Unicode string because the converter is + * stateful, then subChars will be an empty string. + * + * @param converter the Unicode converter + * @param subChars the substitution characters + * @param len on input the capacity of subChars, on output the number + * of bytes copied to it + * @param err the outgoing error status code. + * If the substitution character array is too small, an + * U_INDEX_OUTOFBOUNDS_ERROR will be returned. + * @see ucnv_setSubstString + * @see ucnv_setSubstChars + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getSubstChars(const UConverter *converter, + char *subChars, + int8_t *len, + UErrorCode *err); + +/** + * Sets the substitution chars when converting from unicode to a codepage. The + * substitution is specified as a string of 1-4 bytes, and may contain + * NULL bytes. + * The subChars must represent a single character. The caller needs to know the + * byte sequence of a valid character in the converter's charset. + * For some converters, for example some ISO 2022 variants, only single-byte + * substitution characters may be supported. + * The newer ucnv_setSubstString() function relaxes these limitations. + * + * @param converter the Unicode converter + * @param subChars the substitution character byte sequence we want set + * @param len the number of bytes in subChars + * @param err the error status code. U_INDEX_OUTOFBOUNDS_ERROR if + * len is bigger than the maximum number of bytes allowed in subchars + * @see ucnv_setSubstString + * @see ucnv_getSubstChars + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_setSubstChars(UConverter *converter, + const char *subChars, + int8_t len, + UErrorCode *err); + +/** + * Set a substitution string for converting from Unicode to a charset. + * The caller need not know the charset byte sequence for each charset. + * + * Unlike ucnv_setSubstChars() which is designed to set a charset byte sequence + * for a single character, this function takes a Unicode string with + * zero, one or more characters, and immediately verifies that the string can be + * converted to the charset. + * If not, or if the result is too long (more than 32 bytes as of ICU 3.6), + * then the function returns with an error accordingly. + * + * Also unlike ucnv_setSubstChars(), this function works for stateful charsets + * by converting on the fly at the point of substitution rather than setting + * a fixed byte sequence. + * + * @param cnv The UConverter object. + * @param s The Unicode string. + * @param length The number of UChars in s, or -1 for a NUL-terminated string. + * @param err Pointer to a standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * + * @see ucnv_setSubstChars + * @see ucnv_getSubstChars + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ucnv_setSubstString(UConverter *cnv, + const UChar *s, + int32_t length, + UErrorCode *err); + +/** + * Fills in the output parameter, errBytes, with the error characters from the + * last failing conversion. + * + * @param converter the Unicode converter + * @param errBytes the codepage bytes which were in error + * @param len on input the capacity of errBytes, on output the number of + * bytes which were copied to it + * @param err the error status code. + * If the substitution character array is too small, an + * U_INDEX_OUTOFBOUNDS_ERROR will be returned. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getInvalidChars(const UConverter *converter, + char *errBytes, + int8_t *len, + UErrorCode *err); + +/** + * Fills in the output parameter, errChars, with the error characters from the + * last failing conversion. + * + * @param converter the Unicode converter + * @param errUChars the UChars which were in error + * @param len on input the capacity of errUChars, on output the number of + * UChars which were copied to it + * @param err the error status code. + * If the substitution character array is too small, an + * U_INDEX_OUTOFBOUNDS_ERROR will be returned. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getInvalidUChars(const UConverter *converter, + UChar *errUChars, + int8_t *len, + UErrorCode *err); + +/** + * Resets the state of a converter to the default state. This is used + * in the case of an error, to restart a conversion from a known default state. + * It will also empty the internal output buffers. + * @param converter the Unicode converter + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_reset(UConverter *converter); + +/** + * Resets the to-Unicode part of a converter state to the default state. + * This is used in the case of an error to restart a conversion to + * Unicode to a known default state. It will also empty the internal + * output buffers used for the conversion to Unicode codepoints. + * @param converter the Unicode converter + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_resetToUnicode(UConverter *converter); + +/** + * Resets the from-Unicode part of a converter state to the default state. + * This is used in the case of an error to restart a conversion from + * Unicode to a known default state. It will also empty the internal output + * buffers used for the conversion from Unicode codepoints. + * @param converter the Unicode converter + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_resetFromUnicode(UConverter *converter); + +/** + * Returns the maximum number of bytes that are output per UChar in conversion + * from Unicode using this converter. + * The returned number can be used with UCNV_GET_MAX_BYTES_FOR_STRING + * to calculate the size of a target buffer for conversion from Unicode. + * + * Note: Before ICU 2.8, this function did not return reliable numbers for + * some stateful converters (EBCDIC_STATEFUL, ISO-2022) and LMBCS. + * + * This number may not be the same as the maximum number of bytes per + * "conversion unit". In other words, it may not be the intuitively expected + * number of bytes per character that would be published for a charset, + * and may not fulfill any other purpose than the allocation of an output + * buffer of guaranteed sufficient size for a given input length and converter. + * + * Examples for special cases that are taken into account: + * - Supplementary code points may convert to more bytes than BMP code points. + * This function returns bytes per UChar (UTF-16 code unit), not per + * Unicode code point, for efficient buffer allocation. + * - State-shifting output (SI/SO, escapes, etc.) from stateful converters. + * - When m input UChars are converted to n output bytes, then the maximum m/n + * is taken into account. + * + * The number returned here does not take into account + * (see UCNV_GET_MAX_BYTES_FOR_STRING): + * - callbacks which output more than one charset character sequence per call, + * like escape callbacks + * - initial and final non-character bytes that are output by some converters + * (automatic BOMs, initial escape sequence, final SI, etc.) + * + * Examples for returned values: + * - SBCS charsets: 1 + * - Shift-JIS: 2 + * - UTF-16: 2 (2 per BMP, 4 per surrogate _pair_, BOM not counted) + * - UTF-8: 3 (3 per BMP, 4 per surrogate _pair_) + * - EBCDIC_STATEFUL (EBCDIC mixed SBCS/DBCS): 3 (SO + DBCS) + * - ISO-2022: 3 (always outputs UTF-8) + * - ISO-2022-JP: 6 (4-byte escape sequences + DBCS) + * - ISO-2022-CN: 8 (4-byte designator sequences + 2-byte SS2/SS3 + DBCS) + * + * @param converter The Unicode converter. + * @return The maximum number of bytes per UChar (16 bit code unit) + * that are output by ucnv_fromUnicode(), + * to be used together with UCNV_GET_MAX_BYTES_FOR_STRING + * for buffer allocation. + * + * @see UCNV_GET_MAX_BYTES_FOR_STRING + * @see ucnv_getMinCharSize + * @stable ICU 2.0 + */ +U_CAPI int8_t U_EXPORT2 +ucnv_getMaxCharSize(const UConverter *converter); + +/** + * Calculates the size of a buffer for conversion from Unicode to a charset. + * The calculated size is guaranteed to be sufficient for this conversion. + * + * It takes into account initial and final non-character bytes that are output + * by some converters. + * It does not take into account callbacks which output more than one charset + * character sequence per call, like escape callbacks. + * The default (substitution) callback only outputs one charset character sequence. + * + * @param length Number of UChars to be converted. + * @param maxCharSize Return value from ucnv_getMaxCharSize() for the converter + * that will be used. + * @return Size of a buffer that will be large enough to hold the output bytes of + * converting length UChars with the converter that returned the maxCharSize. + * + * @see ucnv_getMaxCharSize + * @stable ICU 2.8 + */ +#define UCNV_GET_MAX_BYTES_FOR_STRING(length, maxCharSize) \ + (((int32_t)(length)+10)*(int32_t)(maxCharSize)) + +/** + * Returns the minimum byte length (per codepoint) for characters in this codepage. + * This is usually either 1 or 2. + * @param converter the Unicode converter + * @return the minimum number of bytes per codepoint allowed by this particular converter + * @see ucnv_getMaxCharSize + * @stable ICU 2.0 + */ +U_CAPI int8_t U_EXPORT2 +ucnv_getMinCharSize(const UConverter *converter); + +/** + * Returns the display name of the converter passed in based on the Locale + * passed in. If the locale contains no display name, the internal ASCII + * name will be filled in. + * + * @param converter the Unicode converter. + * @param displayLocale is the specific Locale we want to localized for + * @param displayName user provided buffer to be filled in + * @param displayNameCapacity size of displayName Buffer + * @param err error status code + * @return displayNameLength number of UChar needed in displayName + * @see ucnv_getName + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_getDisplayName(const UConverter *converter, + const char *displayLocale, + UChar *displayName, + int32_t displayNameCapacity, + UErrorCode *err); + +/** + * Gets the internal, canonical name of the converter (zero-terminated). + * The lifetime of the returned string will be that of the converter + * passed to this function. + * @param converter the Unicode converter + * @param err UErrorCode status + * @return the internal name of the converter + * @see ucnv_getDisplayName + * @stable ICU 2.0 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getName(const UConverter *converter, UErrorCode *err); + +/** + * Gets a codepage number associated with the converter. This is not guaranteed + * to be the one used to create the converter. Some converters do not represent + * platform registered codepages and return zero for the codepage number. + * The error code fill-in parameter indicates if the codepage number + * is available. + * Does not check if the converter is NULL or if converter's data + * table is NULL. + * + * Important: The use of CCSIDs is not recommended because it is limited + * to only two platforms in principle and only one (UCNV_IBM) in the current + * ICU converter API. + * Also, CCSIDs are insufficient to identify IBM Unicode conversion tables precisely. + * For more details see ucnv_openCCSID(). + * + * @param converter the Unicode converter + * @param err the error status code. + * @return If any error occurs, -1 will be returned otherwise, the codepage number + * will be returned + * @see ucnv_openCCSID + * @see ucnv_getPlatform + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_getCCSID(const UConverter *converter, + UErrorCode *err); + +/** + * Gets a codepage platform associated with the converter. Currently, + * only UCNV_IBM will be returned. + * Does not test if the converter is NULL or if converter's data + * table is NULL. + * @param converter the Unicode converter + * @param err the error status code. + * @return The codepage platform + * @stable ICU 2.0 + */ +U_CAPI UConverterPlatform U_EXPORT2 +ucnv_getPlatform(const UConverter *converter, + UErrorCode *err); + +/** + * Gets the type of the converter + * e.g. SBCS, MBCS, DBCS, UTF8, UTF16_BE, UTF16_LE, ISO_2022, + * EBCDIC_STATEFUL, LATIN_1 + * @param converter a valid, opened converter + * @return the type of the converter + * @stable ICU 2.0 + */ +U_CAPI UConverterType U_EXPORT2 +ucnv_getType(const UConverter * converter); + +/** + * Gets the "starter" (lead) bytes for converters of type MBCS. + * Will fill in an U_ILLEGAL_ARGUMENT_ERROR if converter passed in + * is not MBCS. Fills in an array of type UBool, with the value of the byte + * as offset to the array. For example, if (starters[0x20] == true) at return, + * it means that the byte 0x20 is a starter byte in this converter. + * Context pointers are always owned by the caller. + * + * @param converter a valid, opened converter of type MBCS + * @param starters an array of size 256 to be filled in + * @param err error status, U_ILLEGAL_ARGUMENT_ERROR if the + * converter is not a type which can return starters. + * @see ucnv_getType + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getStarters(const UConverter* converter, + UBool starters[256], + UErrorCode* err); + + +/** + * Selectors for Unicode sets that can be returned by ucnv_getUnicodeSet(). + * @see ucnv_getUnicodeSet + * @stable ICU 2.6 + */ +typedef enum UConverterUnicodeSet { + /** Select the set of roundtrippable Unicode code points. @stable ICU 2.6 */ + UCNV_ROUNDTRIP_SET, + /** Select the set of Unicode code points with roundtrip or fallback mappings. @stable ICU 4.0 */ + UCNV_ROUNDTRIP_AND_FALLBACK_SET, +#ifndef U_HIDE_DEPRECATED_API + /** + * Number of UConverterUnicodeSet selectors. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCNV_SET_COUNT +#endif // U_HIDE_DEPRECATED_API +} UConverterUnicodeSet; + + +/** + * Returns the set of Unicode code points that can be converted by an ICU converter. + * + * Returns one of several kinds of set: + * + * 1. UCNV_ROUNDTRIP_SET + * + * The set of all Unicode code points that can be roundtrip-converted + * (converted without any data loss) with the converter (ucnv_fromUnicode()). + * This set will not include code points that have fallback mappings + * or are only the result of reverse fallback mappings. + * This set will also not include PUA code points with fallbacks, although + * ucnv_fromUnicode() will always uses those mappings despite ucnv_setFallback(). + * See UTR #22 "Character Mapping Markup Language" + * at http://www.unicode.org/reports/tr22/ + * + * This is useful for example for + * - checking that a string or document can be roundtrip-converted with a converter, + * without/before actually performing the conversion + * - testing if a converter can be used for text for typical text for a certain locale, + * by comparing its roundtrip set with the set of ExemplarCharacters from + * ICU's locale data or other sources + * + * 2. UCNV_ROUNDTRIP_AND_FALLBACK_SET + * + * The set of all Unicode code points that can be converted with the converter (ucnv_fromUnicode()) + * when fallbacks are turned on (see ucnv_setFallback()). + * This set includes all code points with roundtrips and fallbacks (but not reverse fallbacks). + * + * In the future, there may be more UConverterUnicodeSet choices to select + * sets with different properties. + * + * @param cnv The converter for which a set is requested. + * @param setFillIn A valid USet *. It will be cleared by this function before + * the converter's specific set is filled into the USet. + * @param whichSet A UConverterUnicodeSet selector; + * currently UCNV_ROUNDTRIP_SET is the only supported value. + * @param pErrorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * + * @see UConverterUnicodeSet + * @see uset_open + * @see uset_close + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +ucnv_getUnicodeSet(const UConverter *cnv, + USet *setFillIn, + UConverterUnicodeSet whichSet, + UErrorCode *pErrorCode); + +/** + * Gets the current callback function used by the converter when an illegal + * or invalid codepage sequence is found. + * Context pointers are always owned by the caller. + * + * @param converter the unicode converter + * @param action fillin: returns the callback function pointer + * @param context fillin: returns the callback's private void* context + * @see ucnv_setToUCallBack + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getToUCallBack (const UConverter * converter, + UConverterToUCallback *action, + const void **context); + +/** + * Gets the current callback function used by the converter when illegal + * or invalid Unicode sequence is found. + * Context pointers are always owned by the caller. + * + * @param converter the unicode converter + * @param action fillin: returns the callback function pointer + * @param context fillin: returns the callback's private void* context + * @see ucnv_setFromUCallBack + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getFromUCallBack (const UConverter * converter, + UConverterFromUCallback *action, + const void **context); + +/** + * Changes the callback function used by the converter when + * an illegal or invalid sequence is found. + * Context pointers are always owned by the caller. + * Predefined actions and contexts can be found in the ucnv_err.h header. + * + * @param converter the unicode converter + * @param newAction the new callback function + * @param newContext the new toUnicode callback context pointer. This can be NULL. + * @param oldAction fillin: returns the old callback function pointer. This can be NULL. + * @param oldContext fillin: returns the old callback's private void* context. This can be NULL. + * @param err The error code status + * @see ucnv_getToUCallBack + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_setToUCallBack (UConverter * converter, + UConverterToUCallback newAction, + const void* newContext, + UConverterToUCallback *oldAction, + const void** oldContext, + UErrorCode * err); + +/** + * Changes the current callback function used by the converter when + * an illegal or invalid sequence is found. + * Context pointers are always owned by the caller. + * Predefined actions and contexts can be found in the ucnv_err.h header. + * + * @param converter the unicode converter + * @param newAction the new callback function + * @param newContext the new fromUnicode callback context pointer. This can be NULL. + * @param oldAction fillin: returns the old callback function pointer. This can be NULL. + * @param oldContext fillin: returns the old callback's private void* context. This can be NULL. + * @param err The error code status + * @see ucnv_getFromUCallBack + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_setFromUCallBack (UConverter * converter, + UConverterFromUCallback newAction, + const void *newContext, + UConverterFromUCallback *oldAction, + const void **oldContext, + UErrorCode * err); + +/** + * Converts an array of unicode characters to an array of codepage + * characters. This function is optimized for converting a continuous + * stream of data in buffer-sized chunks, where the entire source and + * target does not fit in available buffers. + * + * The source pointer is an in/out parameter. It starts out pointing where the + * conversion is to begin, and ends up pointing after the last UChar consumed. + * + * Target similarly starts out pointer at the first available byte in the output + * buffer, and ends up pointing after the last byte written to the output. + * + * The converter always attempts to consume the entire source buffer, unless + * (1.) the target buffer is full, or (2.) a failing error is returned from the + * current callback function. When a successful error status has been + * returned, it means that all of the source buffer has been + * consumed. At that point, the caller should reset the source and + * sourceLimit pointers to point to the next chunk. + * + * At the end of the stream (flush==true), the input is completely consumed + * when *source==sourceLimit and no error code is set. + * The converter object is then automatically reset by this function. + * (This means that a converter need not be reset explicitly between data + * streams if it finishes the previous stream without errors.) + * + * This is a stateful conversion. Additionally, even when all source data has + * been consumed, some data may be in the converters' internal state. + * Call this function repeatedly, updating the target pointers with + * the next empty chunk of target in case of a + * U_BUFFER_OVERFLOW_ERROR, and updating the source pointers + * with the next chunk of source when a successful error status is + * returned, until there are no more chunks of source data. + * @param converter the Unicode converter + * @param target I/O parameter. Input : Points to the beginning of the buffer to copy + * codepage characters to. Output : points to after the last codepage character copied + * to target. + * @param targetLimit the pointer just after last of the target buffer + * @param source I/O parameter, pointer to pointer to the source Unicode character buffer. + * @param sourceLimit the pointer just after the last of the source buffer + * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number + * of allocated cells as target. Will fill in offsets from target to source pointer + * e.g: offsets[3] is equal to 6, it means that the target[3] was a result of transcoding source[6] + * For output data carried across calls, and other data without a specific source character + * (such as from escape sequences or callbacks) -1 will be placed for offsets. + * @param flush set to true if the current source buffer is the last available + * chunk of the source, false otherwise. Note that if a failing status is returned, + * this function may have to be called multiple times with flush set to true until + * the source buffer is consumed. + * @param err the error status. U_ILLEGAL_ARGUMENT_ERROR will be set if the + * converter is NULL. + * U_BUFFER_OVERFLOW_ERROR will be set if the target is full and there is + * still data to be written to the target. + * @see ucnv_fromUChars + * @see ucnv_convert + * @see ucnv_getMinCharSize + * @see ucnv_setToUCallBack + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_fromUnicode (UConverter * converter, + char **target, + const char *targetLimit, + const UChar ** source, + const UChar * sourceLimit, + int32_t* offsets, + UBool flush, + UErrorCode * err); + +/** + * Converts a buffer of codepage bytes into an array of unicode UChars + * characters. This function is optimized for converting a continuous + * stream of data in buffer-sized chunks, where the entire source and + * target does not fit in available buffers. + * + * The source pointer is an in/out parameter. It starts out pointing where the + * conversion is to begin, and ends up pointing after the last byte of source consumed. + * + * Target similarly starts out pointer at the first available UChar in the output + * buffer, and ends up pointing after the last UChar written to the output. + * It does NOT necessarily keep UChar sequences together. + * + * The converter always attempts to consume the entire source buffer, unless + * (1.) the target buffer is full, or (2.) a failing error is returned from the + * current callback function. When a successful error status has been + * returned, it means that all of the source buffer has been + * consumed. At that point, the caller should reset the source and + * sourceLimit pointers to point to the next chunk. + * + * At the end of the stream (flush==true), the input is completely consumed + * when *source==sourceLimit and no error code is set + * The converter object is then automatically reset by this function. + * (This means that a converter need not be reset explicitly between data + * streams if it finishes the previous stream without errors.) + * + * This is a stateful conversion. Additionally, even when all source data has + * been consumed, some data may be in the converters' internal state. + * Call this function repeatedly, updating the target pointers with + * the next empty chunk of target in case of a + * U_BUFFER_OVERFLOW_ERROR, and updating the source pointers + * with the next chunk of source when a successful error status is + * returned, until there are no more chunks of source data. + * @param converter the Unicode converter + * @param target I/O parameter. Input : Points to the beginning of the buffer to copy + * UChars into. Output : points to after the last UChar copied. + * @param targetLimit the pointer just after the end of the target buffer + * @param source I/O parameter, pointer to pointer to the source codepage buffer. + * @param sourceLimit the pointer to the byte after the end of the source buffer + * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number + * of allocated cells as target. Will fill in offsets from target to source pointer + * e.g: offsets[3] is equal to 6, it means that the target[3] was a result of transcoding source[6] + * For output data carried across calls, and other data without a specific source character + * (such as from escape sequences or callbacks) -1 will be placed for offsets. + * @param flush set to true if the current source buffer is the last available + * chunk of the source, false otherwise. Note that if a failing status is returned, + * this function may have to be called multiple times with flush set to true until + * the source buffer is consumed. + * @param err the error status. U_ILLEGAL_ARGUMENT_ERROR will be set if the + * converter is NULL. + * U_BUFFER_OVERFLOW_ERROR will be set if the target is full and there is + * still data to be written to the target. + * @see ucnv_fromUChars + * @see ucnv_convert + * @see ucnv_getMinCharSize + * @see ucnv_setFromUCallBack + * @see ucnv_getNextUChar + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_toUnicode(UConverter *converter, + UChar **target, + const UChar *targetLimit, + const char **source, + const char *sourceLimit, + int32_t *offsets, + UBool flush, + UErrorCode *err); + +/** + * Convert the Unicode string into a codepage string using an existing UConverter. + * The output string is NUL-terminated if possible. + * + * This function is a more convenient but less powerful version of ucnv_fromUnicode(). + * It is only useful for whole strings, not for streaming conversion. + * + * The maximum output buffer capacity required (barring output from callbacks) will be + * UCNV_GET_MAX_BYTES_FOR_STRING(srcLength, ucnv_getMaxCharSize(cnv)). + * + * @param cnv the converter object to be used (ucnv_resetFromUnicode() will be called) + * @param src the input Unicode string + * @param srcLength the input string length, or -1 if NUL-terminated + * @param dest destination string buffer, can be NULL if destCapacity==0 + * @param destCapacity the number of chars available at dest + * @param pErrorCode normal ICU error code; + * common error codes that may be set by this function include + * U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING, + * U_ILLEGAL_ARGUMENT_ERROR, and conversion errors + * @return the length of the output string, not counting the terminating NUL; + * if the length is greater than destCapacity, then the string will not fit + * and a buffer of the indicated length would need to be passed in + * @see ucnv_fromUnicode + * @see ucnv_convert + * @see UCNV_GET_MAX_BYTES_FOR_STRING + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_fromUChars(UConverter *cnv, + char *dest, int32_t destCapacity, + const UChar *src, int32_t srcLength, + UErrorCode *pErrorCode); + +/** + * Convert the codepage string into a Unicode string using an existing UConverter. + * The output string is NUL-terminated if possible. + * + * This function is a more convenient but less powerful version of ucnv_toUnicode(). + * It is only useful for whole strings, not for streaming conversion. + * + * The maximum output buffer capacity required (barring output from callbacks) will be + * 2*srcLength (each char may be converted into a surrogate pair). + * + * @param cnv the converter object to be used (ucnv_resetToUnicode() will be called) + * @param src the input codepage string + * @param srcLength the input string length, or -1 if NUL-terminated + * @param dest destination string buffer, can be NULL if destCapacity==0 + * @param destCapacity the number of UChars available at dest + * @param pErrorCode normal ICU error code; + * common error codes that may be set by this function include + * U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING, + * U_ILLEGAL_ARGUMENT_ERROR, and conversion errors + * @return the length of the output string, not counting the terminating NUL; + * if the length is greater than destCapacity, then the string will not fit + * and a buffer of the indicated length would need to be passed in + * @see ucnv_toUnicode + * @see ucnv_convert + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_toUChars(UConverter *cnv, + UChar *dest, int32_t destCapacity, + const char *src, int32_t srcLength, + UErrorCode *pErrorCode); + +/** + * Convert a codepage buffer into Unicode one character at a time. + * The input is completely consumed when the U_INDEX_OUTOFBOUNDS_ERROR is set. + * + * Advantage compared to ucnv_toUnicode() or ucnv_toUChars(): + * - Faster for small amounts of data, for most converters, e.g., + * US-ASCII, ISO-8859-1, UTF-8/16/32, and most "normal" charsets. + * (For complex converters, e.g., SCSU, UTF-7 and ISO 2022 variants, + * it uses ucnv_toUnicode() internally.) + * - Convenient. + * + * Limitations compared to ucnv_toUnicode(): + * - Always assumes flush=true. + * This makes ucnv_getNextUChar() unsuitable for "streaming" conversion, + * that is, for where the input is supplied in multiple buffers, + * because ucnv_getNextUChar() will assume the end of the input at the end + * of the first buffer. + * - Does not provide offset output. + * + * It is possible to "mix" ucnv_getNextUChar() and ucnv_toUnicode() because + * ucnv_getNextUChar() uses the current state of the converter + * (unlike ucnv_toUChars() which always resets first). + * However, if ucnv_getNextUChar() is called after ucnv_toUnicode() + * stopped in the middle of a character sequence (with flush=false), + * then ucnv_getNextUChar() will always use the slower ucnv_toUnicode() + * internally until the next character boundary. + * (This is new in ICU 2.6. In earlier releases, ucnv_getNextUChar() had to + * start at a character boundary.) + * + * Instead of using ucnv_getNextUChar(), it is recommended + * to convert using ucnv_toUnicode() or ucnv_toUChars() + * and then iterate over the text using U16_NEXT() or a UCharIterator (uiter.h) + * or a C++ CharacterIterator or similar. + * This allows streaming conversion and offset output, for example. + * + *

Handling of surrogate pairs and supplementary-plane code points:
+ * There are two different kinds of codepages that provide mappings for surrogate characters: + *

    + *
  • Codepages like UTF-8, UTF-32, and GB 18030 provide direct representations for Unicode + * code points U+10000-U+10ffff as well as for single surrogates U+d800-U+dfff. + * Each valid sequence will result in exactly one returned code point. + * If a sequence results in a single surrogate, then that will be returned + * by itself, even if a neighboring sequence encodes the matching surrogate.
  • + *
  • Codepages like SCSU and LMBCS (and UTF-16) provide direct representations only for BMP code points + * including surrogates. Code points in supplementary planes are represented with + * two sequences, each encoding a surrogate. + * For these codepages, matching pairs of surrogates will be combined into single + * code points for returning from this function. + * (Note that SCSU is actually a mix of these codepage types.)
  • + *

+ * + * @param converter an open UConverter + * @param source the address of a pointer to the codepage buffer, will be + * updated to point after the bytes consumed in the conversion call. + * @param sourceLimit points to the end of the input buffer + * @param err fills in error status (see ucnv_toUnicode) + * U_INDEX_OUTOFBOUNDS_ERROR will be set if the input + * is empty or does not convert to any output (e.g.: pure state-change + * codes SI/SO, escape sequences for ISO 2022, + * or if the callback did not output anything, ...). + * This function will not set a U_BUFFER_OVERFLOW_ERROR because + * the "buffer" is the return code. However, there might be subsequent output + * stored in the converter object + * that will be returned in following calls to this function. + * @return a UChar32 resulting from the partial conversion of source + * @see ucnv_toUnicode + * @see ucnv_toUChars + * @see ucnv_convert + * @stable ICU 2.0 + */ +U_CAPI UChar32 U_EXPORT2 +ucnv_getNextUChar(UConverter * converter, + const char **source, + const char * sourceLimit, + UErrorCode * err); + +/** + * Convert from one external charset to another using two existing UConverters. + * Internally, two conversions - ucnv_toUnicode() and ucnv_fromUnicode() - + * are used, "pivoting" through 16-bit Unicode. + * + * Important: For streaming conversion (multiple function calls for successive + * parts of a text stream), the caller must provide a pivot buffer explicitly, + * and must preserve the pivot buffer and associated pointers from one + * call to another. (The buffer may be moved if its contents and the relative + * pointer positions are preserved.) + * + * There is a similar function, ucnv_convert(), + * which has the following limitations: + * - it takes charset names, not converter objects, so that + * - two converters are opened for each call + * - only single-string conversion is possible, not streaming operation + * - it does not provide enough information to find out, + * in case of failure, whether the toUnicode or + * the fromUnicode conversion failed + * + * By contrast, ucnv_convertEx() + * - takes UConverter parameters instead of charset names + * - fully exposes the pivot buffer for streaming conversion and complete error handling + * + * ucnv_convertEx() also provides further convenience: + * - an option to reset the converters at the beginning + * (if reset==true, see parameters; + * also sets *pivotTarget=*pivotSource=pivotStart) + * - allow NUL-terminated input + * (only a single NUL byte, will not work for charsets with multi-byte NULs) + * (if sourceLimit==NULL, see parameters) + * - terminate with a NUL on output + * (only a single NUL byte, not useful for charsets with multi-byte NULs), + * or set U_STRING_NOT_TERMINATED_WARNING if the output exactly fills + * the target buffer + * - the pivot buffer can be provided internally; + * possible only for whole-string conversion, not streaming conversion; + * in this case, the caller will not be able to get details about where an + * error occurred + * (if pivotStart==NULL, see below) + * + * The function returns when one of the following is true: + * - the entire source text has been converted successfully to the target buffer + * - a target buffer overflow occurred (U_BUFFER_OVERFLOW_ERROR) + * - a conversion error occurred + * (other U_FAILURE(), see description of pErrorCode) + * + * Limitation compared to the direct use of + * ucnv_fromUnicode() and ucnv_toUnicode(): + * ucnv_convertEx() does not provide offset information. + * + * Limitation compared to ucnv_fromUChars() and ucnv_toUChars(): + * ucnv_convertEx() does not support preflighting directly. + * + * Sample code for converting a single string from + * one external charset to UTF-8, ignoring the location of errors: + * + * \code + * int32_t + * myToUTF8(UConverter *cnv, + * const char *s, int32_t length, + * char *u8, int32_t capacity, + * UErrorCode *pErrorCode) { + * UConverter *utf8Cnv; + * char *target; + * + * if(U_FAILURE(*pErrorCode)) { + * return 0; + * } + * + * utf8Cnv=myGetCachedUTF8Converter(pErrorCode); + * if(U_FAILURE(*pErrorCode)) { + * return 0; + * } + * + * if(length<0) { + * length=strlen(s); + * } + * target=u8; + * ucnv_convertEx(utf8Cnv, cnv, + * &target, u8+capacity, + * &s, s+length, + * NULL, NULL, NULL, NULL, + * true, true, + * pErrorCode); + * + * myReleaseCachedUTF8Converter(utf8Cnv); + * + * // return the output string length, but without preflighting + * return (int32_t)(target-u8); + * } + * \endcode + * + * @param targetCnv Output converter, used to convert from the UTF-16 pivot + * to the target using ucnv_fromUnicode(). + * @param sourceCnv Input converter, used to convert from the source to + * the UTF-16 pivot using ucnv_toUnicode(). + * @param target I/O parameter, same as for ucnv_fromUChars(). + * Input: *target points to the beginning of the target buffer. + * Output: *target points to the first unit after the last char written. + * @param targetLimit Pointer to the first unit after the target buffer. + * @param source I/O parameter, same as for ucnv_toUChars(). + * Input: *source points to the beginning of the source buffer. + * Output: *source points to the first unit after the last char read. + * @param sourceLimit Pointer to the first unit after the source buffer. + * @param pivotStart Pointer to the UTF-16 pivot buffer. If pivotStart==NULL, + * then an internal buffer is used and the other pivot + * arguments are ignored and can be NULL as well. + * @param pivotSource I/O parameter, same as source in ucnv_fromUChars() for + * conversion from the pivot buffer to the target buffer. + * @param pivotTarget I/O parameter, same as target in ucnv_toUChars() for + * conversion from the source buffer to the pivot buffer. + * It must be pivotStart<=*pivotSource<=*pivotTarget<=pivotLimit + * and pivotStart[0..ucnv_countAvailable()]) + * @return a pointer a string (library owned), or NULL if the index is out of bounds. + * @see ucnv_countAvailable + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +ucnv_getAvailableName(int32_t n); + +/** + * Returns a UEnumeration to enumerate all of the canonical converter + * names, as per the alias file, regardless of the ability to open each + * converter. + * + * @return A UEnumeration object for getting all the recognized canonical + * converter names. + * @see ucnv_getAvailableName + * @see uenum_close + * @see uenum_next + * @stable ICU 2.4 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucnv_openAllNames(UErrorCode *pErrorCode); + +/** + * Gives the number of aliases for a given converter or alias name. + * If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. + * This method only enumerates the listed entries in the alias file. + * @param alias alias name + * @param pErrorCode error status + * @return number of names on alias list for given alias + * @stable ICU 2.0 + */ +U_CAPI uint16_t U_EXPORT2 +ucnv_countAliases(const char *alias, UErrorCode *pErrorCode); + +/** + * Gives the name of the alias at given index of alias list. + * This method only enumerates the listed entries in the alias file. + * If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. + * @param alias alias name + * @param n index in alias list + * @param pErrorCode result of operation + * @return returns the name of the alias at given index + * @see ucnv_countAliases + * @stable ICU 2.0 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getAlias(const char *alias, uint16_t n, UErrorCode *pErrorCode); + +/** + * Fill-up the list of alias names for the given alias. + * This method only enumerates the listed entries in the alias file. + * If the alias is ambiguous, then the preferred converter is used + * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. + * @param alias alias name + * @param aliases fill-in list, aliases is a pointer to an array of + * ucnv_countAliases() string-pointers + * (const char *) that will be filled in. + * The strings themselves are owned by the library. + * @param pErrorCode result of operation + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_getAliases(const char *alias, const char **aliases, UErrorCode *pErrorCode); + +/** + * Return a new UEnumeration object for enumerating all the + * alias names for a given converter that are recognized by a standard. + * This method only enumerates the listed entries in the alias file. + * The convrtrs.txt file can be modified to change the results of + * this function. + * The first result in this list is the same result given by + * ucnv_getStandardName, which is the default alias for + * the specified standard name. The returned object must be closed with + * uenum_close when you are done with the object. + * + * @param convName original converter name + * @param standard name of the standard governing the names; MIME and IANA + * are such standards + * @param pErrorCode The error code + * @return A UEnumeration object for getting all aliases that are recognized + * by a standard. If any of the parameters are invalid, NULL + * is returned. + * @see ucnv_getStandardName + * @see uenum_close + * @see uenum_next + * @stable ICU 2.2 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucnv_openStandardNames(const char *convName, + const char *standard, + UErrorCode *pErrorCode); + +/** + * Gives the number of standards associated to converter names. + * @return number of standards + * @stable ICU 2.0 + */ +U_CAPI uint16_t U_EXPORT2 +ucnv_countStandards(void); + +/** + * Gives the name of the standard at given index of standard list. + * @param n index in standard list + * @param pErrorCode result of operation + * @return returns the name of the standard at given index. Owned by the library. + * @stable ICU 2.0 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getStandard(uint16_t n, UErrorCode *pErrorCode); + +/** + * Returns a standard name for a given converter name. + *

+ * Example alias table:
+ * conv alias1 { STANDARD1 } alias2 { STANDARD1* } + *

+ * Result of ucnv_getStandardName("conv", "STANDARD1") from example + * alias table:
+ * "alias2" + * + * @param name original converter name + * @param standard name of the standard governing the names; MIME and IANA + * are such standards + * @param pErrorCode result of operation + * @return returns the standard converter name; + * if a standard converter name cannot be determined, + * then NULL is returned. Owned by the library. + * @stable ICU 2.0 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getStandardName(const char *name, const char *standard, UErrorCode *pErrorCode); + +/** + * This function will return the internal canonical converter name of the + * tagged alias. This is the opposite of ucnv_openStandardNames, which + * returns the tagged alias given the canonical name. + *

+ * Example alias table:
+ * conv alias1 { STANDARD1 } alias2 { STANDARD1* } + *

+ * Result of ucnv_getStandardName("alias1", "STANDARD1") from example + * alias table:
+ * "conv" + * + * @return returns the canonical converter name; + * if a standard or alias name cannot be determined, + * then NULL is returned. The returned string is + * owned by the library. + * @see ucnv_getStandardName + * @stable ICU 2.4 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getCanonicalName(const char *alias, const char *standard, UErrorCode *pErrorCode); + +/** + * Returns the current default converter name. If you want to open + * a default converter, you do not need to use this function. + * It is faster if you pass a NULL argument to ucnv_open the + * default converter. + * + * If U_CHARSET_IS_UTF8 is defined to 1 in utypes.h then this function + * always returns "UTF-8". + * + * @return returns the current default converter name. + * Storage owned by the library + * @see ucnv_setDefaultName + * @stable ICU 2.0 + */ +U_CAPI const char * U_EXPORT2 +ucnv_getDefaultName(void); + +#ifndef U_HIDE_SYSTEM_API +/** + * This function is not thread safe. DO NOT call this function when ANY ICU + * function is being used from more than one thread! This function sets the + * current default converter name. If this function needs to be called, it + * should be called during application initialization. Most of the time, the + * results from ucnv_getDefaultName() or ucnv_open with a NULL string argument + * is sufficient for your application. + * + * If U_CHARSET_IS_UTF8 is defined to 1 in utypes.h then this function + * does nothing. + * + * @param name the converter name to be the default (must be known by ICU). + * @see ucnv_getDefaultName + * @system + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_setDefaultName(const char *name); +#endif /* U_HIDE_SYSTEM_API */ + +/** + * Fixes the backslash character mismapping. For example, in SJIS, the backslash + * character in the ASCII portion is also used to represent the yen currency sign. + * When mapping from Unicode character 0x005C, it's unclear whether to map the + * character back to yen or backslash in SJIS. This function will take the input + * buffer and replace all the yen sign characters with backslash. This is necessary + * when the user tries to open a file with the input buffer on Windows. + * This function will test the converter to see whether such mapping is + * required. You can sometimes avoid using this function by using the correct version + * of Shift-JIS. + * + * @param cnv The converter representing the target codepage. + * @param source the input buffer to be fixed + * @param sourceLen the length of the input buffer + * @see ucnv_isAmbiguous + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_fixFileSeparator(const UConverter *cnv, UChar *source, int32_t sourceLen); + +/** + * Determines if the converter contains ambiguous mappings of the same + * character or not. + * @param cnv the converter to be tested + * @return true if the converter contains ambiguous mapping of the same + * character, false otherwise. + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucnv_isAmbiguous(const UConverter *cnv); + +/** + * Sets the converter to use fallback mappings or not. + * Regardless of this flag, the converter will always use + * fallbacks from Unicode Private Use code points, as well as + * reverse fallbacks (to Unicode). + * For details see ".ucm File Format" + * in the Conversion Data chapter of the ICU User Guide: + * https://unicode-org.github.io/icu/userguide/conversion/data.html#ucm-file-format + * + * @param cnv The converter to set the fallback mapping usage on. + * @param usesFallback true if the user wants the converter to take advantage of the fallback + * mapping, false otherwise. + * @stable ICU 2.0 + * @see ucnv_usesFallback + */ +U_CAPI void U_EXPORT2 +ucnv_setFallback(UConverter *cnv, UBool usesFallback); + +/** + * Determines if the converter uses fallback mappings or not. + * This flag has restrictions, see ucnv_setFallback(). + * + * @param cnv The converter to be tested + * @return true if the converter uses fallback, false otherwise. + * @stable ICU 2.0 + * @see ucnv_setFallback + */ +U_CAPI UBool U_EXPORT2 +ucnv_usesFallback(const UConverter *cnv); + +/** + * Detects Unicode signature byte sequences at the start of the byte stream + * and returns the charset name of the indicated Unicode charset. + * NULL is returned when no Unicode signature is recognized. + * The number of bytes in the signature is output as well. + * + * The caller can ucnv_open() a converter using the charset name. + * The first code unit (UChar) from the start of the stream will be U+FEFF + * (the Unicode BOM/signature character) and can usually be ignored. + * + * For most Unicode charsets it is also possible to ignore the indicated + * number of initial stream bytes and start converting after them. + * However, there are stateful Unicode charsets (UTF-7 and BOCU-1) for which + * this will not work. Therefore, it is best to ignore the first output UChar + * instead of the input signature bytes. + *

+ * Usage: + * \snippet samples/ucnv/convsamp.cpp ucnv_detectUnicodeSignature + * + * @param source The source string in which the signature should be detected. + * @param sourceLength Length of the input string, or -1 if terminated with a NUL byte. + * @param signatureLength A pointer to int32_t to receive the number of bytes that make up the signature + * of the detected UTF. 0 if not detected. + * Can be a NULL pointer. + * @param pErrorCode ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return The name of the encoding detected. NULL if encoding is not detected. + * @stable ICU 2.4 + */ +U_CAPI const char* U_EXPORT2 +ucnv_detectUnicodeSignature(const char* source, + int32_t sourceLength, + int32_t *signatureLength, + UErrorCode *pErrorCode); + +/** + * Returns the number of UChars held in the converter's internal state + * because more input is needed for completing the conversion. This function is + * useful for mapping semantics of ICU's converter interface to those of iconv, + * and this information is not needed for normal conversion. + * @param cnv The converter in which the input is held + * @param status ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return The number of UChars in the state. -1 if an error is encountered. + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_fromUCountPending(const UConverter* cnv, UErrorCode* status); + +/** + * Returns the number of chars held in the converter's internal state + * because more input is needed for completing the conversion. This function is + * useful for mapping semantics of ICU's converter interface to those of iconv, + * and this information is not needed for normal conversion. + * @param cnv The converter in which the input is held as internal state + * @param status ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return The number of chars in the state. -1 if an error is encountered. + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ucnv_toUCountPending(const UConverter* cnv, UErrorCode* status); + +/** + * Returns whether or not the charset of the converter has a fixed number of bytes + * per charset character. + * An example of this are converters that are of the type UCNV_SBCS or UCNV_DBCS. + * Another example is UTF-32 which is always 4 bytes per character. + * A Unicode code point may be represented by more than one UTF-8 or UTF-16 code unit + * but a UTF-32 converter encodes each code point with 4 bytes. + * Note: This method is not intended to be used to determine whether the charset has a + * fixed ratio of bytes to Unicode codes units for any particular Unicode encoding form. + * false is returned with the UErrorCode if error occurs or cnv is NULL. + * @param cnv The converter to be tested + * @param status ICU error code in/out parameter + * @return true if the converter is fixed-width + * @stable ICU 4.8 + */ +U_CAPI UBool U_EXPORT2 +ucnv_isFixedWidth(UConverter *cnv, UErrorCode *status); + +#endif + +#endif +/*_UCNV*/ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_cb.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_cb.h new file mode 100644 index 0000000000000000000000000000000000000000..b4ef99208b15dd81eb082266231bf5c385f24a60 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_cb.h @@ -0,0 +1,164 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 2000-2004, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** + * ucnv_cb.h: + * External APIs for the ICU's codeset conversion library + * Helena Shih + * + * Modification History: + * + * Date Name Description + */ + +/** + * \file + * \brief C API: UConverter functions to aid the writers of callbacks + * + *

Callback API for UConverter

+ * + * These functions are provided here for the convenience of the callback + * writer. If you are just looking for callback functions to use, please + * see ucnv_err.h. DO NOT call these functions directly when you are + * working with converters, unless your code has been called as a callback + * via ucnv_setFromUCallback or ucnv_setToUCallback !! + * + * A note about error codes and overflow. Unlike other ICU functions, + * these functions do not expect the error status to be U_ZERO_ERROR. + * Callbacks must be much more careful about their error codes. + * The error codes used here are in/out parameters, which should be passed + * back in the callback's error parameter. + * + * For example, if you call ucnv_cbfromUWriteBytes to write data out + * to the output codepage, it may return U_BUFFER_OVERFLOW_ERROR if + * the data did not fit in the target. But this isn't a failing error, + * in fact, ucnv_cbfromUWriteBytes may be called AGAIN with the error + * status still U_BUFFER_OVERFLOW_ERROR to attempt to write further bytes, + * which will also go into the internal overflow buffers. + * + * Concerning offsets, the 'offset' parameters here are relative to the start + * of SOURCE. For example, Suppose the string "ABCD" was being converted + * from Unicode into a codepage which doesn't have a mapping for 'B'. + * 'A' will be written out correctly, but + * The FromU Callback will be called on an unassigned character for 'B'. + * At this point, this is the state of the world: + * Target: A [..] [points after A] + * Source: A B [C] D [points to C - B has been consumed] + * 0 1 2 3 + * codePoint = "B" [the unassigned codepoint] + * + * Now, suppose a callback wants to write the substitution character '?' to + * the target. It calls ucnv_cbFromUWriteBytes() to write the ?. + * It should pass ZERO as the offset, because the offset as far as the + * callback is concerned is relative to the SOURCE pointer [which points + * before 'C'.] If the callback goes into the args and consumes 'C' also, + * it would call FromUWriteBytes with an offset of 1 (and advance the source + * pointer). + * + */ + +#ifndef UCNV_CB_H +#define UCNV_CB_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_CONVERSION + +#include "unicode/ucnv.h" +#include "unicode/ucnv_err.h" + +/** + * ONLY used by FromU callback functions. + * Writes out the specified byte output bytes to the target byte buffer or to converter internal buffers. + * + * @param args callback fromUnicode arguments + * @param source source bytes to write + * @param length length of bytes to write + * @param offsetIndex the relative offset index from callback. + * @param err error status. If U_BUFFER_OVERFLOW is returned, then U_BUFFER_OVERFLOW must + * be returned to the user, because it means that not all data could be written into the target buffer, and some is + * in the converter error buffer. + * @see ucnv_cbFromUWriteSub + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_cbFromUWriteBytes (UConverterFromUnicodeArgs *args, + const char* source, + int32_t length, + int32_t offsetIndex, + UErrorCode * err); + +/** + * ONLY used by FromU callback functions. + * This function will write out the correct substitution character sequence + * to the target. + * + * @param args callback fromUnicode arguments + * @param offsetIndex the relative offset index from the current source pointer to be used + * @param err error status. If U_BUFFER_OVERFLOW is returned, then U_BUFFER_OVERFLOW must + * be returned to the user, because it means that not all data could be written into the target buffer, and some is + * in the converter error buffer. + * @see ucnv_cbFromUWriteBytes + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucnv_cbFromUWriteSub (UConverterFromUnicodeArgs *args, + int32_t offsetIndex, + UErrorCode * err); + +/** + * ONLY used by fromU callback functions. + * This function will write out the error character(s) to the target UChar buffer. + * + * @param args callback fromUnicode arguments + * @param source pointer to pointer to first UChar to write [on exit: 1 after last UChar processed] + * @param sourceLimit pointer after last UChar to write + * @param offsetIndex the relative offset index from callback which will be set + * @param err error status U_BUFFER_OVERFLOW + * @see ucnv_cbToUWriteSub + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 ucnv_cbFromUWriteUChars(UConverterFromUnicodeArgs *args, + const UChar** source, + const UChar* sourceLimit, + int32_t offsetIndex, + UErrorCode * err); + +/** + * ONLY used by ToU callback functions. + * This function will write out the specified characters to the target + * UChar buffer. + * + * @param args callback toUnicode arguments + * @param source source string to write + * @param length the length of source string + * @param offsetIndex the relative offset index which will be written. + * @param err error status U_BUFFER_OVERFLOW + * @see ucnv_cbToUWriteSub + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 ucnv_cbToUWriteUChars (UConverterToUnicodeArgs *args, + const UChar* source, + int32_t length, + int32_t offsetIndex, + UErrorCode * err); + +/** + * ONLY used by ToU callback functions. + * This function will write out the Unicode substitution character (U+FFFD). + * + * @param args callback fromUnicode arguments + * @param offsetIndex the relative offset index from callback. + * @param err error status U_BUFFER_OVERFLOW + * @see ucnv_cbToUWriteUChars + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 ucnv_cbToUWriteSub (UConverterToUnicodeArgs *args, + int32_t offsetIndex, + UErrorCode * err); +#endif + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_err.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_err.h new file mode 100644 index 0000000000000000000000000000000000000000..c743e5614f4ade2986544370eac038805f27d4bf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnv_err.h @@ -0,0 +1,465 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2009, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** + * + * + * ucnv_err.h: + */ + +/** + * \file + * \brief C API: UConverter predefined error callbacks + * + *

Error Behaviour Functions

+ * Defines some error behaviour functions called by ucnv_{from,to}Unicode + * These are provided as part of ICU and many are stable, but they + * can also be considered only as an example of what can be done with + * callbacks. You may of course write your own. + * + * If you want to write your own, you may also find the functions from + * ucnv_cb.h useful when writing your own callbacks. + * + * These functions, although public, should NEVER be called directly. + * They should be used as parameters to the ucnv_setFromUCallback + * and ucnv_setToUCallback functions, to set the behaviour of a converter + * when it encounters ILLEGAL/UNMAPPED/INVALID sequences. + * + * usage example: 'STOP' doesn't need any context, but newContext + * could be set to something other than 'NULL' if needed. The available + * contexts in this header can modify the default behavior of the callback. + * + * \code + * UErrorCode err = U_ZERO_ERROR; + * UConverter *myConverter = ucnv_open("ibm-949", &err); + * const void *oldContext; + * UConverterFromUCallback oldAction; + * + * + * if (U_SUCCESS(err)) + * { + * ucnv_setFromUCallBack(myConverter, + * UCNV_FROM_U_CALLBACK_STOP, + * NULL, + * &oldAction, + * &oldContext, + * &status); + * } + * \endcode + * + * The code above tells "myConverter" to stop when it encounters an + * ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from + * Unicode -> Codepage. The behavior from Codepage to Unicode is not changed, + * and ucnv_setToUCallBack would need to be called in order to change + * that behavior too. + * + * Here is an example with a context: + * + * \code + * UErrorCode err = U_ZERO_ERROR; + * UConverter *myConverter = ucnv_open("ibm-949", &err); + * const void *oldContext; + * UConverterFromUCallback oldAction; + * + * + * if (U_SUCCESS(err)) + * { + * ucnv_setToUCallBack(myConverter, + * UCNV_TO_U_CALLBACK_SUBSTITUTE, + * UCNV_SUB_STOP_ON_ILLEGAL, + * &oldAction, + * &oldContext, + * &status); + * } + * \endcode + * + * The code above tells "myConverter" to stop when it encounters an + * ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from + * Codepage -> Unicode. Any unmapped and legal characters will be + * substituted to be the default substitution character. + */ + +#ifndef UCNV_ERR_H +#define UCNV_ERR_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_CONVERSION + +/** Forward declaring the UConverter structure. @stable ICU 2.0 */ +struct UConverter; + +/** @stable ICU 2.0 */ +typedef struct UConverter UConverter; + +/** + * FROM_U, TO_U context options for sub callback + * @stable ICU 2.0 + */ +#define UCNV_SUB_STOP_ON_ILLEGAL "i" + +/** + * FROM_U, TO_U context options for skip callback + * @stable ICU 2.0 + */ +#define UCNV_SKIP_STOP_ON_ILLEGAL "i" + +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to ICU (%UXXXX) + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_ICU NULL +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to JAVA (\\uXXXX) + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_JAVA "J" +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to C (\\uXXXX \\UXXXXXXXX) + * TO_U_CALLBACK_ESCAPE option to escape the character value according to C (\\xXXXX) + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_C "C" +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Decimal escape \htmlonly(&#DDDD;)\endhtmlonly + * TO_U_CALLBACK_ESCAPE context option to escape the character value according to XML Decimal escape \htmlonly(&#DDDD;)\endhtmlonly + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_XML_DEC "D" +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Hex escape \htmlonly(&#xXXXX;)\endhtmlonly + * TO_U_CALLBACK_ESCAPE context option to escape the character value according to XML Hex escape \htmlonly(&#xXXXX;)\endhtmlonly + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_XML_HEX "X" +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to Unicode (U+XXXXX) + * @stable ICU 2.0 + */ +#define UCNV_ESCAPE_UNICODE "U" + +/** + * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to CSS2 conventions (\\HH..H, that is, + * a backslash, 1..6 hex digits, and a space) + * @stable ICU 4.0 + */ +#define UCNV_ESCAPE_CSS2 "S" + +/** + * The process condition code to be used with the callbacks. + * Codes which are greater than UCNV_IRREGULAR should be + * passed on to any chained callbacks. + * @stable ICU 2.0 + */ +typedef enum { + UCNV_UNASSIGNED = 0, /**< The code point is unassigned. + The error code U_INVALID_CHAR_FOUND will be set. */ + UCNV_ILLEGAL = 1, /**< The code point is illegal. For example, + \\x81\\x2E is illegal in SJIS because \\x2E + is not a valid trail byte for the \\x81 + lead byte. + Also, starting with Unicode 3.0.1, non-shortest byte sequences + in UTF-8 (like \\xC1\\xA1 instead of \\x61 for U+0061) + are also illegal, not just irregular. + The error code U_ILLEGAL_CHAR_FOUND will be set. */ + UCNV_IRREGULAR = 2, /**< The codepoint is not a regular sequence in + the encoding. For example, \\xED\\xA0\\x80..\\xED\\xBF\\xBF + are irregular UTF-8 byte sequences for single surrogate + code points. + The error code U_INVALID_CHAR_FOUND will be set. */ + UCNV_RESET = 3, /**< The callback is called with this reason when a + 'reset' has occurred. Callback should reset all + state. */ + UCNV_CLOSE = 4, /**< Called when the converter is closed. The + callback should release any allocated memory.*/ + UCNV_CLONE = 5 /**< Called when ucnv_safeClone() is called on the + converter. the pointer available as the + 'context' is an alias to the original converters' + context pointer. If the context must be owned + by the new converter, the callback must clone + the data and call ucnv_setFromUCallback + (or setToUCallback) with the correct pointer. + @stable ICU 2.2 + */ +} UConverterCallbackReason; + + +/** + * The structure for the fromUnicode callback function parameter. + * @stable ICU 2.0 + */ +typedef struct { + uint16_t size; /**< The size of this struct. @stable ICU 2.0 */ + UBool flush; /**< The internal state of converter will be reset and data flushed if set to true. @stable ICU 2.0 */ + UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */ + const UChar *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */ + const UChar *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */ + char *target; /**< Pointer to the target buffer. @stable ICU 2.0 */ + const char *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */ + int32_t *offsets; /**< Pointer to the buffer that receives the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */ +} UConverterFromUnicodeArgs; + + +/** + * The structure for the toUnicode callback function parameter. + * @stable ICU 2.0 + */ +typedef struct { + uint16_t size; /**< The size of this struct @stable ICU 2.0 */ + UBool flush; /**< The internal state of converter will be reset and data flushed if set to true. @stable ICU 2.0 */ + UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */ + const char *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */ + const char *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */ + UChar *target; /**< Pointer to the target buffer. @stable ICU 2.0 */ + const UChar *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */ + int32_t *offsets; /**< Pointer to the buffer that receives the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */ +} UConverterToUnicodeArgs; + + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This From Unicode callback STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * + * @param context Pointer to the callback's private data + * @param fromUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. + * @param reason Defines the reason the callback was invoked + * @param err This should always be set to a failure status prior to calling. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_FROM_U_CALLBACK_STOP ( + const void *context, + UConverterFromUnicodeArgs *fromUArgs, + const UChar* codeUnits, + int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode * err); + + + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This To Unicode callback STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * + * @param context Pointer to the callback's private data + * @param toUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' bytes of the concerned codepage sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param reason Defines the reason the callback was invoked + * @param err This should always be set to a failure status prior to calling. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_TO_U_CALLBACK_STOP ( + const void *context, + UConverterToUnicodeArgs *toUArgs, + const char* codeUnits, + int32_t length, + UConverterCallbackReason reason, + UErrorCode * err); + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This From Unicode callback skips any ILLEGAL_SEQUENCE, or + * skips only UNASSIGNED_SEQUENCE depending on the context parameter + * simply ignoring those characters. + * + * @param context The function currently recognizes the callback options: + * UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * NULL: Skips any ILLEGAL_SEQUENCE + * @param fromUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_FROM_U_CALLBACK_SKIP ( + const void *context, + UConverterFromUnicodeArgs *fromUArgs, + const UChar* codeUnits, + int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode * err); + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This From Unicode callback will Substitute the ILLEGAL SEQUENCE, or + * UNASSIGNED_SEQUENCE depending on context parameter, with the + * current substitution string for the converter. This is the default + * callback. + * + * @param context The function currently recognizes the callback options: + * UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * NULL: Substitutes any ILLEGAL_SEQUENCE + * @param fromUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @see ucnv_setSubstChars + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_FROM_U_CALLBACK_SUBSTITUTE ( + const void *context, + UConverterFromUnicodeArgs *fromUArgs, + const UChar* codeUnits, + int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode * err); + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This From Unicode callback will Substitute the ILLEGAL SEQUENCE with the + * hexadecimal representation of the illegal codepoints + * + * @param context The function currently recognizes the callback options: + *
    + *
  • UCNV_ESCAPE_ICU: Substitutes the ILLEGAL SEQUENCE with the hexadecimal + * representation in the format %UXXXX, e.g. "%uFFFE%u00AC%uC8FE"). + * In the Event the converter doesn't support the characters {%,U}[A-F][0-9], + * it will substitute the illegal sequence with the substitution characters. + * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as + * %UD84D%UDC56
  • + *
  • UCNV_ESCAPE_JAVA: Substitutes the ILLEGAL SEQUENCE with the hexadecimal + * representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). + * In the Event the converter doesn't support the characters {\,u}[A-F][0-9], + * it will substitute the illegal sequence with the substitution characters. + * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as + * \\uD84D\\uDC56
  • + *
  • UCNV_ESCAPE_C: Substitutes the ILLEGAL SEQUENCE with the hexadecimal + * representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). + * In the Event the converter doesn't support the characters {\,u,U}[A-F][0-9], + * it will substitute the illegal sequence with the substitution characters. + * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as + * \\U00023456
  • + *
  • UCNV_ESCAPE_XML_DEC: Substitutes the ILLEGAL SEQUENCE with the decimal + * representation in the format \htmlonly&#DDDDDDDD;, e.g. "&#65534;&#172;&#51454;")\endhtmlonly. + * In the Event the converter doesn't support the characters {&,#}[0-9], + * it will substitute the illegal sequence with the substitution characters. + * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as + * &#144470; and Zero padding is ignored.
  • + *
  • UCNV_ESCAPE_XML_HEX:Substitutes the ILLEGAL SEQUENCE with the decimal + * representation in the format \htmlonly&#xXXXX; e.g. "&#xFFFE;&#x00AC;&#xC8FE;")\endhtmlonly. + * In the Event the converter doesn't support the characters {&,#,x}[0-9], + * it will substitute the illegal sequence with the substitution characters. + * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as + * \htmlonly&#x23456;\endhtmlonly
  • + *
+ * @param fromUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_FROM_U_CALLBACK_ESCAPE ( + const void *context, + UConverterFromUnicodeArgs *fromUArgs, + const UChar* codeUnits, + int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode * err); + + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This To Unicode callback skips any ILLEGAL_SEQUENCE, or + * skips only UNASSIGNED_SEQUENCE depending on the context parameter + * simply ignoring those characters. + * + * @param context The function currently recognizes the callback options: + * UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * NULL: Skips any ILLEGAL_SEQUENCE + * @param toUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' bytes of the concerned codepage sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_TO_U_CALLBACK_SKIP ( + const void *context, + UConverterToUnicodeArgs *toUArgs, + const char* codeUnits, + int32_t length, + UConverterCallbackReason reason, + UErrorCode * err); + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This To Unicode callback will Substitute the ILLEGAL SEQUENCE,or + * UNASSIGNED_SEQUENCE depending on context parameter, with the + * Unicode substitution character, U+FFFD. + * + * @param context The function currently recognizes the callback options: + * UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, + * returning the error code back to the caller immediately. + * NULL: Substitutes any ILLEGAL_SEQUENCE + * @param toUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' bytes of the concerned codepage sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 UCNV_TO_U_CALLBACK_SUBSTITUTE ( + const void *context, + UConverterToUnicodeArgs *toUArgs, + const char* codeUnits, + int32_t length, + UConverterCallbackReason reason, + UErrorCode * err); + +/** + * DO NOT CALL THIS FUNCTION DIRECTLY! + * This To Unicode callback will Substitute the ILLEGAL SEQUENCE with the + * hexadecimal representation of the illegal bytes + * (in the format %XNN, e.g. "%XFF%X0A%XC8%X03"). + * + * @param context This function currently recognizes the callback options: + * UCNV_ESCAPE_ICU, UCNV_ESCAPE_JAVA, UCNV_ESCAPE_C, UCNV_ESCAPE_XML_DEC, + * UCNV_ESCAPE_XML_HEX and UCNV_ESCAPE_UNICODE. + * @param toUArgs Information about the conversion in progress + * @param codeUnits Points to 'length' bytes of the concerned codepage sequence + * @param length Size (in bytes) of the concerned codepage sequence + * @param reason Defines the reason the callback was invoked + * @param err Return value will be set to success if the callback was handled, + * otherwise this value will be set to a failure status. + * @stable ICU 2.0 + */ + +U_CAPI void U_EXPORT2 UCNV_TO_U_CALLBACK_ESCAPE ( + const void *context, + UConverterToUnicodeArgs *toUArgs, + const char* codeUnits, + int32_t length, + UConverterCallbackReason reason, + UErrorCode * err); + +#endif + +#endif + +/*UCNV_ERR_H*/ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnvsel.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnvsel.h new file mode 100644 index 0000000000000000000000000000000000000000..9373ec951bf83a65fe47abc277639e89ff09b22c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucnvsel.h @@ -0,0 +1,193 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2008-2011, International Business Machines +* Corporation, Google and others. All Rights Reserved. +* +******************************************************************************* +*/ +/* + * Author : eldawy@google.com (Mohamed Eldawy) + * ucnvsel.h + * + * Purpose: To generate a list of encodings capable of handling + * a given Unicode text + * + * Started 09-April-2008 + */ + +#ifndef __ICU_UCNV_SEL_H__ +#define __ICU_UCNV_SEL_H__ + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_CONVERSION + +#include "unicode/uset.h" +#include "unicode/utf16.h" +#include "unicode/uenum.h" +#include "unicode/ucnv.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Encoding/charset encoding selector + * + * A converter selector is built with a set of encoding/charset names + * and given an input string returns the set of names of the + * corresponding converters which can convert the string. + * + * A converter selector can be serialized into a buffer and reopened + * from the serialized form. + */ + +struct UConverterSelector; +/** + * @{ + * Typedef for selector data structure. + */ +typedef struct UConverterSelector UConverterSelector; +/** @} */ + +/** + * Open a selector. + * If converterListSize is 0, build for all available converters. + * If excludedCodePoints is NULL, don't exclude any code points. + * + * @param converterList a pointer to encoding names needed to be involved. + * Can be NULL if converterListSize==0. + * The list and the names will be cloned, and the caller + * retains ownership of the original. + * @param converterListSize number of encodings in above list. + * If 0, builds a selector for all available converters. + * @param excludedCodePoints a set of code points to be excluded from consideration. + * That is, excluded code points in a string do not change + * the selection result. (They might be handled by a callback.) + * Use NULL to exclude nothing. + * @param whichSet what converter set to use? Use this to determine whether + * to consider only roundtrip mappings or also fallbacks. + * @param status an in/out ICU UErrorCode + * @return the new selector + * + * @stable ICU 4.2 + */ +U_CAPI UConverterSelector* U_EXPORT2 +ucnvsel_open(const char* const* converterList, int32_t converterListSize, + const USet* excludedCodePoints, + const UConverterUnicodeSet whichSet, UErrorCode* status); + +/** + * Closes a selector. + * If any Enumerations were returned by ucnv_select*, they become invalid. + * They can be closed before or after calling ucnv_closeSelector, + * but should never be used after the selector is closed. + * + * @see ucnv_selectForString + * @see ucnv_selectForUTF8 + * + * @param sel selector to close + * + * @stable ICU 4.2 + */ +U_CAPI void U_EXPORT2 +ucnvsel_close(UConverterSelector *sel); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUConverterSelectorPointer + * "Smart pointer" class, closes a UConverterSelector via ucnvsel_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterSelectorPointer, UConverterSelector, ucnvsel_close); + +U_NAMESPACE_END + +#endif + +/** + * Open a selector from its serialized form. + * The buffer must remain valid and unchanged for the lifetime of the selector. + * This is much faster than creating a selector from scratch. + * Using a serialized form from a different machine (endianness/charset) is supported. + * + * @param buffer pointer to the serialized form of a converter selector; + * must be 32-bit-aligned + * @param length the capacity of this buffer (can be equal to or larger than + * the actual data length) + * @param status an in/out ICU UErrorCode + * @return the new selector + * + * @stable ICU 4.2 + */ +U_CAPI UConverterSelector* U_EXPORT2 +ucnvsel_openFromSerialized(const void* buffer, int32_t length, UErrorCode* status); + +/** + * Serialize a selector into a linear buffer. + * The serialized form is portable to different machines. + * + * @param sel selector to consider + * @param buffer pointer to 32-bit-aligned memory to be filled with the + * serialized form of this converter selector + * @param bufferCapacity the capacity of this buffer + * @param status an in/out ICU UErrorCode + * @return the required buffer capacity to hold serialize data (even if the call fails + * with a U_BUFFER_OVERFLOW_ERROR, it will return the required capacity) + * + * @stable ICU 4.2 + */ +U_CAPI int32_t U_EXPORT2 +ucnvsel_serialize(const UConverterSelector* sel, + void* buffer, int32_t bufferCapacity, UErrorCode* status); + +/** + * Select converters that can map all characters in a UTF-16 string, + * ignoring the excluded code points. + * + * @param sel a selector + * @param s UTF-16 string + * @param length length of the string, or -1 if NUL-terminated + * @param status an in/out ICU UErrorCode + * @return an enumeration containing encoding names. + * The returned encoding names and their order will be the same as + * supplied when building the selector. + * + * @stable ICU 4.2 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucnvsel_selectForString(const UConverterSelector* sel, + const UChar *s, int32_t length, UErrorCode *status); + +/** + * Select converters that can map all characters in a UTF-8 string, + * ignoring the excluded code points. + * + * @param sel a selector + * @param s UTF-8 string + * @param length length of the string, or -1 if NUL-terminated + * @param status an in/out ICU UErrorCode + * @return an enumeration containing encoding names. + * The returned encoding names and their order will be the same as + * supplied when building the selector. + * + * @stable ICU 4.2 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucnvsel_selectForUTF8(const UConverterSelector* sel, + const char *s, int32_t length, UErrorCode *status); + +#endif /* !UCONFIG_NO_CONVERSION */ + +#endif /* __ICU_UCNV_SEL_H__ */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucol.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucol.h new file mode 100644 index 0000000000000000000000000000000000000000..24963312216941c2098df20160e37b5e8ab75c66 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucol.h @@ -0,0 +1,1515 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (c) 1996-2015, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************* +*/ + +#ifndef UCOL_H +#define UCOL_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_COLLATION + +#include "unicode/unorm.h" +#include "unicode/parseerr.h" +#include "unicode/uloc.h" +#include "unicode/uset.h" +#include "unicode/uscript.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Collator + * + *

Collator C API

+ * + * The C API for Collator performs locale-sensitive + * string comparison. You use this service to build + * searching and sorting routines for natural language text. + *

+ * For more information about the collation service see + * the User Guide. + *

+ * Collation service provides correct sorting orders for most locales supported in ICU. + * If specific data for a locale is not available, the orders eventually falls back + * to the CLDR root sort order. + *

+ * Sort ordering may be customized by providing your own set of rules. For more on + * this subject see the + * Collation Customization section of the User Guide. + *

+ * @see UCollationResult + * @see UNormalizationMode + * @see UCollationStrength + * @see UCollationElements + */ + +/** A collator. +* For usage in C programs. +*/ +struct UCollator; +/** structure representing a collator object instance + * @stable ICU 2.0 + */ +typedef struct UCollator UCollator; + + +/** + * UCOL_LESS is returned if source string is compared to be less than target + * string in the ucol_strcoll() method. + * UCOL_EQUAL is returned if source string is compared to be equal to target + * string in the ucol_strcoll() method. + * UCOL_GREATER is returned if source string is compared to be greater than + * target string in the ucol_strcoll() method. + * @see ucol_strcoll() + *

+ * Possible values for a comparison result + * @stable ICU 2.0 + */ +typedef enum { + /** string a == string b */ + UCOL_EQUAL = 0, + /** string a > string b */ + UCOL_GREATER = 1, + /** string a < string b */ + UCOL_LESS = -1 +} UCollationResult ; + + +/** Enum containing attribute values for controlling collation behavior. + * Here are all the allowable values. Not every attribute can take every value. The only + * universal value is UCOL_DEFAULT, which resets the attribute value to the predefined + * value for that locale + * @stable ICU 2.0 + */ +typedef enum { + /** accepted by most attributes */ + UCOL_DEFAULT = -1, + + /** Primary collation strength */ + UCOL_PRIMARY = 0, + /** Secondary collation strength */ + UCOL_SECONDARY = 1, + /** Tertiary collation strength */ + UCOL_TERTIARY = 2, + /** Default collation strength */ + UCOL_DEFAULT_STRENGTH = UCOL_TERTIARY, + UCOL_CE_STRENGTH_LIMIT, + /** Quaternary collation strength */ + UCOL_QUATERNARY=3, + /** Identical collation strength */ + UCOL_IDENTICAL=15, + UCOL_STRENGTH_LIMIT, + + /** Turn the feature off - works for UCOL_FRENCH_COLLATION, + UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE + & UCOL_DECOMPOSITION_MODE*/ + UCOL_OFF = 16, + /** Turn the feature on - works for UCOL_FRENCH_COLLATION, + UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE + & UCOL_DECOMPOSITION_MODE*/ + UCOL_ON = 17, + + /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be shifted */ + UCOL_SHIFTED = 20, + /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be non ignorable */ + UCOL_NON_IGNORABLE = 21, + + /** Valid for UCOL_CASE_FIRST - + lower case sorts before upper case */ + UCOL_LOWER_FIRST = 24, + /** upper case sorts before lower case */ + UCOL_UPPER_FIRST = 25, + +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UColAttributeValue value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCOL_ATTRIBUTE_VALUE_COUNT +#endif /* U_HIDE_DEPRECATED_API */ +} UColAttributeValue; + +/** + * Enum containing the codes for reordering segments of the collation table that are not script + * codes. These reordering codes are to be used in conjunction with the script codes. + * @see ucol_getReorderCodes + * @see ucol_setReorderCodes + * @see ucol_getEquivalentReorderCodes + * @see UScriptCode + * @stable ICU 4.8 + */ + typedef enum { + /** + * A special reordering code that is used to specify the default + * reordering codes for a locale. + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_DEFAULT = -1, + /** + * A special reordering code that is used to specify no reordering codes. + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_NONE = USCRIPT_UNKNOWN, + /** + * A special reordering code that is used to specify all other codes used for + * reordering except for the codes lised as UColReorderCode values and those + * listed explicitly in a reordering. + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_OTHERS = USCRIPT_UNKNOWN, + /** + * Characters with the space property. + * This is equivalent to the rule value "space". + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_SPACE = 0x1000, + /** + * The first entry in the enumeration of reordering groups. This is intended for use in + * range checking and enumeration of the reorder codes. + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_FIRST = UCOL_REORDER_CODE_SPACE, + /** + * Characters with the punctuation property. + * This is equivalent to the rule value "punct". + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_PUNCTUATION = 0x1001, + /** + * Characters with the symbol property. + * This is equivalent to the rule value "symbol". + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_SYMBOL = 0x1002, + /** + * Characters with the currency property. + * This is equivalent to the rule value "currency". + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_CURRENCY = 0x1003, + /** + * Characters with the digit property. + * This is equivalent to the rule value "digit". + * @stable ICU 4.8 + */ + UCOL_REORDER_CODE_DIGIT = 0x1004, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UColReorderCode value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCOL_REORDER_CODE_LIMIT = 0x1005 +#endif /* U_HIDE_DEPRECATED_API */ +} UColReorderCode; + +/** + * Base letter represents a primary difference. Set comparison + * level to UCOL_PRIMARY to ignore secondary and tertiary differences. + * Use this to set the strength of a Collator object. + * Example of primary difference, "abc" < "abd" + * + * Diacritical differences on the same base letter represent a secondary + * difference. Set comparison level to UCOL_SECONDARY to ignore tertiary + * differences. Use this to set the strength of a Collator object. + * Example of secondary difference, "ä" >> "a". + * + * Uppercase and lowercase versions of the same character represents a + * tertiary difference. Set comparison level to UCOL_TERTIARY to include + * all comparison differences. Use this to set the strength of a Collator + * object. + * Example of tertiary difference, "abc" <<< "ABC". + * + * Two characters are considered "identical" when they have the same + * unicode spellings. UCOL_IDENTICAL. + * For example, "ä" == "ä". + * + * UCollationStrength is also used to determine the strength of sort keys + * generated from UCollator objects + * These values can be now found in the UColAttributeValue enum. + * @stable ICU 2.0 + **/ +typedef UColAttributeValue UCollationStrength; + +/** Attributes that collation service understands. All the attributes can take UCOL_DEFAULT + * value, as well as the values specific to each one. + * @stable ICU 2.0 + */ +typedef enum { + /** Attribute for direction of secondary weights - used in Canadian French. + * Acceptable values are UCOL_ON, which results in secondary weights + * being considered backwards and UCOL_OFF which treats secondary + * weights in the order they appear. + * @stable ICU 2.0 + */ + UCOL_FRENCH_COLLATION, + /** Attribute for handling variable elements. + * Acceptable values are UCOL_NON_IGNORABLE (default) + * which treats all the codepoints with non-ignorable + * primary weights in the same way, + * and UCOL_SHIFTED which causes codepoints with primary + * weights that are equal or below the variable top value + * to be ignored on primary level and moved to the quaternary + * level. + * @stable ICU 2.0 + */ + UCOL_ALTERNATE_HANDLING, + /** Controls the ordering of upper and lower case letters. + * Acceptable values are UCOL_OFF (default), which orders + * upper and lower case letters in accordance to their tertiary + * weights, UCOL_UPPER_FIRST which forces upper case letters to + * sort before lower case letters, and UCOL_LOWER_FIRST which does + * the opposite. + * @stable ICU 2.0 + */ + UCOL_CASE_FIRST, + /** Controls whether an extra case level (positioned before the third + * level) is generated or not. Acceptable values are UCOL_OFF (default), + * when case level is not generated, and UCOL_ON which causes the case + * level to be generated. Contents of the case level are affected by + * the value of UCOL_CASE_FIRST attribute. A simple way to ignore + * accent differences in a string is to set the strength to UCOL_PRIMARY + * and enable case level. + * @stable ICU 2.0 + */ + UCOL_CASE_LEVEL, + /** Controls whether the normalization check and necessary normalizations + * are performed. When set to UCOL_OFF (default) no normalization check + * is performed. The correctness of the result is guaranteed only if the + * input data is in so-called FCD form (see users manual for more info). + * When set to UCOL_ON, an incremental check is performed to see whether + * the input data is in the FCD form. If the data is not in the FCD form, + * incremental NFD normalization is performed. + * @stable ICU 2.0 + */ + UCOL_NORMALIZATION_MODE, + /** An alias for UCOL_NORMALIZATION_MODE attribute. + * @stable ICU 2.0 + */ + UCOL_DECOMPOSITION_MODE = UCOL_NORMALIZATION_MODE, + /** The strength attribute. Can be either UCOL_PRIMARY, UCOL_SECONDARY, + * UCOL_TERTIARY, UCOL_QUATERNARY or UCOL_IDENTICAL. The usual strength + * for most locales (except Japanese) is tertiary. + * + * Quaternary strength + * is useful when combined with shifted setting for alternate handling + * attribute and for JIS X 4061 collation, when it is used to distinguish + * between Katakana and Hiragana. + * Otherwise, quaternary level + * is affected only by the number of non-ignorable code points in + * the string. + * + * Identical strength is rarely useful, as it amounts + * to codepoints of the NFD form of the string. + * @stable ICU 2.0 + */ + UCOL_STRENGTH, +#ifndef U_HIDE_DEPRECATED_API + /** When turned on, this attribute positions Hiragana before all + * non-ignorables on quaternary level This is a sneaky way to produce JIS + * sort order. + * + * This attribute was an implementation detail of the CLDR Japanese tailoring. + * Since ICU 50, this attribute is not settable any more via API functions. + * Since CLDR 25/ICU 53, explicit quaternary relations are used + * to achieve the same Japanese sort order. + * + * @deprecated ICU 50 Implementation detail, cannot be set via API, was removed from implementation. + */ + UCOL_HIRAGANA_QUATERNARY_MODE = UCOL_STRENGTH + 1, +#endif /* U_HIDE_DEPRECATED_API */ + /** + * When turned on, this attribute makes + * substrings of digits sort according to their numeric values. + * + * This is a way to get '100' to sort AFTER '2'. Note that the longest + * digit substring that can be treated as a single unit is + * 254 digits (not counting leading zeros). If a digit substring is + * longer than that, the digits beyond the limit will be treated as a + * separate digit substring. + * + * A "digit" in this sense is a code point with General_Category=Nd, + * which does not include circled numbers, roman numerals, etc. + * Only a contiguous digit substring is considered, that is, + * non-negative integers without separators. + * There is no support for plus/minus signs, decimals, exponents, etc. + * + * @stable ICU 2.8 + */ + UCOL_NUMERIC_COLLATION = UCOL_STRENGTH + 2, + + /* Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, + * it is needed for layout of RuleBasedCollator object. */ +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * One more than the highest normal UColAttribute value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCOL_ATTRIBUTE_COUNT +#endif // U_FORCE_HIDE_DEPRECATED_API +} UColAttribute; + +/** Options for retrieving the rule string + * @stable ICU 2.0 + */ +typedef enum { + /** + * Retrieves the tailoring rules only. + * Same as calling the version of getRules() without UColRuleOption. + * @stable ICU 2.0 + */ + UCOL_TAILORING_ONLY, + /** + * Retrieves the "UCA rules" concatenated with the tailoring rules. + * The "UCA rules" are an approximation of the root collator's sort order. + * They are almost never used or useful at runtime and can be removed from the data. + * See https://unicode-org.github.io/icu/userguide/collation/customization#building-on-existing-locales + * @stable ICU 2.0 + */ + UCOL_FULL_RULES +} UColRuleOption ; + +/** + * Open a UCollator for comparing strings. + * + * For some languages, multiple collation types are available; + * for example, "de@collation=phonebook". + * Starting with ICU 54, collation attributes can be specified via locale keywords as well, + * in the old locale extension syntax ("el@colCaseFirst=upper") + * or in language tag syntax ("el-u-kf-upper"). + * See User Guide: Collation API. + * + * The UCollator pointer is used in all the calls to the Collation + * service. After finished, collator must be disposed of by calling + * {@link #ucol_close }. + * @param loc The locale containing the required collation rules. + * Special values for locales can be passed in - + * if NULL is passed for the locale, the default locale + * collation rules will be used. If empty string ("") or + * "root" are passed, the root collator will be returned. + * @param status A pointer to a UErrorCode to receive any errors + * @return A pointer to a UCollator, or 0 if an error occurred. + * @see ucol_openRules + * @see ucol_clone + * @see ucol_close + * @stable ICU 2.0 + */ +U_CAPI UCollator* U_EXPORT2 +ucol_open(const char *loc, UErrorCode *status); + +/** + * Produce a UCollator instance according to the rules supplied. + * The rules are used to change the default ordering, defined in the + * UCA in a process called tailoring. The resulting UCollator pointer + * can be used in the same way as the one obtained by {@link #ucol_strcoll }. + * @param rules A string describing the collation rules. For the syntax + * of the rules please see users guide. + * @param rulesLength The length of rules, or -1 if null-terminated. + * @param normalizationMode The normalization mode: One of + * UCOL_OFF (expect the text to not need normalization), + * UCOL_ON (normalize), or + * UCOL_DEFAULT (set the mode according to the rules) + * @param strength The default collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY, + * UCOL_TERTIARY, UCOL_IDENTICAL,UCOL_DEFAULT_STRENGTH - can be also set in the rules. + * @param parseError A pointer to UParseError to receive information about errors + * occurred during parsing. This argument can currently be set + * to NULL, but at users own risk. Please provide a real structure. + * @param status A pointer to a UErrorCode to receive any errors + * @return A pointer to a UCollator. It is not guaranteed that NULL be returned in case + * of error - please use status argument to check for errors. + * @see ucol_open + * @see ucol_clone + * @see ucol_close + * @stable ICU 2.0 + */ +U_CAPI UCollator* U_EXPORT2 +ucol_openRules( const UChar *rules, + int32_t rulesLength, + UColAttributeValue normalizationMode, + UCollationStrength strength, + UParseError *parseError, + UErrorCode *status); + +#ifndef U_HIDE_DEPRECATED_API +/** + * Open a collator defined by a short form string. + * The structure and the syntax of the string is defined in the "Naming collators" + * section of the users guide: + * https://unicode-org.github.io/icu/userguide/collation/concepts#collator-naming-scheme + * Attributes are overridden by the subsequent attributes. So, for "S2_S3", final + * strength will be 3. 3066bis locale overrides individual locale parts. + * The call to this function is equivalent to a call to ucol_open, followed by a + * series of calls to ucol_setAttribute and ucol_setVariableTop. + * @param definition A short string containing a locale and a set of attributes. + * Attributes not explicitly mentioned are left at the default + * state for a locale. + * @param parseError if not NULL, structure that will get filled with error's pre + * and post context in case of error. + * @param forceDefaults if false, the settings that are the same as the collator + * default settings will not be applied (for example, setting + * French secondary on a French collator would not be executed). + * If true, all the settings will be applied regardless of the + * collator default value. If the definition + * strings are to be cached, should be set to false. + * @param status Error code. Apart from regular error conditions connected to + * instantiating collators (like out of memory or similar), this + * API will return an error if an invalid attribute or attribute/value + * combination is specified. + * @return A pointer to a UCollator or 0 if an error occurred (including an + * invalid attribute). + * @see ucol_open + * @see ucol_setAttribute + * @see ucol_setVariableTop + * @see ucol_getShortDefinitionString + * @see ucol_normalizeShortDefinitionString + * @deprecated ICU 54 Use ucol_open() with language tag collation keywords instead. + */ +U_DEPRECATED UCollator* U_EXPORT2 +ucol_openFromShortString( const char *definition, + UBool forceDefaults, + UParseError *parseError, + UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_HIDE_DEPRECATED_API +/** + * Get a set containing the contractions defined by the collator. The set includes + * both the root collator's contractions and the contractions defined by the collator. This set + * will contain only strings. If a tailoring explicitly suppresses contractions from + * the root collator (like Russian), removed contractions will not be in the resulting set. + * @param coll collator + * @param conts the set to hold the result. It gets emptied before + * contractions are added. + * @param status to hold the error code + * @return the size of the contraction set + * + * @deprecated ICU 3.4, use ucol_getContractionsAndExpansions instead + */ +U_DEPRECATED int32_t U_EXPORT2 +ucol_getContractions( const UCollator *coll, + USet *conts, + UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Get a set containing the expansions defined by the collator. The set includes + * both the root collator's expansions and the expansions defined by the tailoring + * @param coll collator + * @param contractions if not NULL, the set to hold the contractions + * @param expansions if not NULL, the set to hold the expansions + * @param addPrefixes add the prefix contextual elements to contractions + * @param status to hold the error code + * + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ucol_getContractionsAndExpansions( const UCollator *coll, + USet *contractions, USet *expansions, + UBool addPrefixes, UErrorCode *status); + +/** + * Close a UCollator. + * Once closed, a UCollator should not be used. Every open collator should + * be closed. Otherwise, a memory leak will result. + * @param coll The UCollator to close. + * @see ucol_open + * @see ucol_openRules + * @see ucol_clone + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_close(UCollator *coll); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUCollatorPointer + * "Smart pointer" class, closes a UCollator via ucol_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUCollatorPointer, UCollator, ucol_close); + +U_NAMESPACE_END + +#endif + +/** + * Compare two strings. + * The strings will be compared using the options already specified. + * @param coll The UCollator containing the comparison rules. + * @param source The source string. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param target The target string. + * @param targetLength The length of target, or -1 if null-terminated. + * @return The result of comparing the strings; one of UCOL_EQUAL, + * UCOL_GREATER, UCOL_LESS + * @see ucol_greater + * @see ucol_greaterOrEqual + * @see ucol_equal + * @stable ICU 2.0 + */ +U_CAPI UCollationResult U_EXPORT2 +ucol_strcoll( const UCollator *coll, + const UChar *source, + int32_t sourceLength, + const UChar *target, + int32_t targetLength); + +/** +* Compare two strings in UTF-8. +* The strings will be compared using the options already specified. +* Note: When input string contains malformed a UTF-8 byte sequence, +* this function treats these bytes as REPLACEMENT CHARACTER (U+FFFD). +* @param coll The UCollator containing the comparison rules. +* @param source The source UTF-8 string. +* @param sourceLength The length of source, or -1 if null-terminated. +* @param target The target UTF-8 string. +* @param targetLength The length of target, or -1 if null-terminated. +* @param status A pointer to a UErrorCode to receive any errors +* @return The result of comparing the strings; one of UCOL_EQUAL, +* UCOL_GREATER, UCOL_LESS +* @see ucol_greater +* @see ucol_greaterOrEqual +* @see ucol_equal +* @stable ICU 50 +*/ +U_CAPI UCollationResult U_EXPORT2 +ucol_strcollUTF8( + const UCollator *coll, + const char *source, + int32_t sourceLength, + const char *target, + int32_t targetLength, + UErrorCode *status); + +/** + * Determine if one string is greater than another. + * This function is equivalent to {@link #ucol_strcoll } == UCOL_GREATER + * @param coll The UCollator containing the comparison rules. + * @param source The source string. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param target The target string. + * @param targetLength The length of target, or -1 if null-terminated. + * @return true if source is greater than target, false otherwise. + * @see ucol_strcoll + * @see ucol_greaterOrEqual + * @see ucol_equal + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucol_greater(const UCollator *coll, + const UChar *source, int32_t sourceLength, + const UChar *target, int32_t targetLength); + +/** + * Determine if one string is greater than or equal to another. + * This function is equivalent to {@link #ucol_strcoll } != UCOL_LESS + * @param coll The UCollator containing the comparison rules. + * @param source The source string. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param target The target string. + * @param targetLength The length of target, or -1 if null-terminated. + * @return true if source is greater than or equal to target, false otherwise. + * @see ucol_strcoll + * @see ucol_greater + * @see ucol_equal + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucol_greaterOrEqual(const UCollator *coll, + const UChar *source, int32_t sourceLength, + const UChar *target, int32_t targetLength); + +/** + * Compare two strings for equality. + * This function is equivalent to {@link #ucol_strcoll } == UCOL_EQUAL + * @param coll The UCollator containing the comparison rules. + * @param source The source string. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param target The target string. + * @param targetLength The length of target, or -1 if null-terminated. + * @return true if source is equal to target, false otherwise + * @see ucol_strcoll + * @see ucol_greater + * @see ucol_greaterOrEqual + * @stable ICU 2.0 + */ +U_CAPI UBool U_EXPORT2 +ucol_equal(const UCollator *coll, + const UChar *source, int32_t sourceLength, + const UChar *target, int32_t targetLength); + +/** + * Compare two UTF-8 encoded strings. + * The strings will be compared using the options already specified. + * @param coll The UCollator containing the comparison rules. + * @param sIter The source string iterator. + * @param tIter The target string iterator. + * @return The result of comparing the strings; one of UCOL_EQUAL, + * UCOL_GREATER, UCOL_LESS + * @param status A pointer to a UErrorCode to receive any errors + * @see ucol_strcoll + * @stable ICU 2.6 + */ +U_CAPI UCollationResult U_EXPORT2 +ucol_strcollIter( const UCollator *coll, + UCharIterator *sIter, + UCharIterator *tIter, + UErrorCode *status); + +/** + * Get the collation strength used in a UCollator. + * The strength influences how strings are compared. + * @param coll The UCollator to query. + * @return The collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY, + * UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL + * @see ucol_setStrength + * @stable ICU 2.0 + */ +U_CAPI UCollationStrength U_EXPORT2 +ucol_getStrength(const UCollator *coll); + +/** + * Set the collation strength used in a UCollator. + * The strength influences how strings are compared. + * @param coll The UCollator to set. + * @param strength The desired collation strength; one of UCOL_PRIMARY, + * UCOL_SECONDARY, UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL, UCOL_DEFAULT + * @see ucol_getStrength + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_setStrength(UCollator *coll, + UCollationStrength strength); + +/** + * Retrieves the reordering codes for this collator. + * These reordering codes are a combination of UScript codes and UColReorderCode entries. + * @param coll The UCollator to query. + * @param dest The array to fill with the script ordering. + * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function + * will only return the length of the result without writing any codes (pre-flighting). + * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate a + * failure before the function call. + * @return The number of reordering codes written to the dest array. + * @see ucol_setReorderCodes + * @see ucol_getEquivalentReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getReorderCodes(const UCollator* coll, + int32_t* dest, + int32_t destCapacity, + UErrorCode *pErrorCode); +/** + * Sets the reordering codes for this collator. + * Collation reordering allows scripts and some other groups of characters + * to be moved relative to each other. This reordering is done on top of + * the DUCET/CLDR standard collation order. Reordering can specify groups to be placed + * at the start and/or the end of the collation order. These groups are specified using + * UScript codes and UColReorderCode entries. + * + *

By default, reordering codes specified for the start of the order are placed in the + * order given after several special non-script blocks. These special groups of characters + * are space, punctuation, symbol, currency, and digit. These special groups are represented with + * UColReorderCode entries. Script groups can be intermingled with + * these special non-script groups if those special groups are explicitly specified in the reordering. + * + *

The special code OTHERS stands for any script that is not explicitly + * mentioned in the list of reordering codes given. Anything that is after OTHERS + * will go at the very end of the reordering in the order given. + * + *

The special reorder code DEFAULT will reset the reordering for this collator + * to the default for this collator. The default reordering may be the DUCET/CLDR order or may be a reordering that + * was specified when this collator was created from resource data or from rules. The + * DEFAULT code must be the sole code supplied when it is used. + * If not, then U_ILLEGAL_ARGUMENT_ERROR will be set. + * + *

The special reorder code NONE will remove any reordering for this collator. + * The result of setting no reordering will be to have the DUCET/CLDR ordering used. The + * NONE code must be the sole code supplied when it is used. + * + * @param coll The UCollator to set. + * @param reorderCodes An array of script codes in the new order. This can be NULL if the + * length is also set to 0. An empty array will clear any reordering codes on the collator. + * @param reorderCodesLength The length of reorderCodes. + * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate a + * failure before the function call. + * @see ucol_getReorderCodes + * @see ucol_getEquivalentReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ +U_CAPI void U_EXPORT2 +ucol_setReorderCodes(UCollator* coll, + const int32_t* reorderCodes, + int32_t reorderCodesLength, + UErrorCode *pErrorCode); + +/** + * Retrieves the reorder codes that are grouped with the given reorder code. Some reorder + * codes will be grouped and must reorder together. + * Beginning with ICU 55, scripts only reorder together if they are primary-equal, + * for example Hiragana and Katakana. + * + * @param reorderCode The reorder code to determine equivalence for. + * @param dest The array to fill with the script ordering. + * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function + * will only return the length of the result without writing any codes (pre-flighting). + * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate + * a failure before the function call. + * @return The number of reordering codes written to the dest array. + * @see ucol_setReorderCodes + * @see ucol_getReorderCodes + * @see UScriptCode + * @see UColReorderCode + * @stable ICU 4.8 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getEquivalentReorderCodes(int32_t reorderCode, + int32_t* dest, + int32_t destCapacity, + UErrorCode *pErrorCode); + +/** + * Get the display name for a UCollator. + * The display name is suitable for presentation to a user. + * @param objLoc The locale of the collator in question. + * @param dispLoc The locale for display. + * @param result A pointer to a buffer to receive the attribute. + * @param resultLength The maximum size of result. + * @param status A pointer to a UErrorCode to receive any errors + * @return The total buffer size needed; if greater than resultLength, + * the output was truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getDisplayName( const char *objLoc, + const char *dispLoc, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** + * Get a locale for which collation rules are available. + * A UCollator in a locale returned by this function will perform the correct + * collation for the locale. + * @param localeIndex The index of the desired locale. + * @return A locale for which collation rules are available, or 0 if none. + * @see ucol_countAvailable + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +ucol_getAvailable(int32_t localeIndex); + +/** + * Determine how many locales have collation rules available. + * This function is most useful as determining the loop ending condition for + * calls to {@link #ucol_getAvailable }. + * @return The number of locales for which collation rules are available. + * @see ucol_getAvailable + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_countAvailable(void); + +#if !UCONFIG_NO_SERVICE +/** + * Create a string enumerator of all locales for which a valid + * collator may be opened. + * @param status input-output error code + * @return a string enumeration over locale strings. The caller is + * responsible for closing the result. + * @stable ICU 3.0 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucol_openAvailableLocales(UErrorCode *status); +#endif + +/** + * Create a string enumerator of all possible keywords that are relevant to + * collation. At this point, the only recognized keyword for this + * service is "collation". + * @param status input-output error code + * @return a string enumeration over locale strings. The caller is + * responsible for closing the result. + * @stable ICU 3.0 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucol_getKeywords(UErrorCode *status); + +/** + * Given a keyword, create a string enumeration of all values + * for that keyword that are currently in use. + * @param keyword a particular keyword as enumerated by + * ucol_getKeywords. If any other keyword is passed in, *status is set + * to U_ILLEGAL_ARGUMENT_ERROR. + * @param status input-output error code + * @return a string enumeration over collation keyword values, or NULL + * upon error. The caller is responsible for closing the result. + * @stable ICU 3.0 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucol_getKeywordValues(const char *keyword, UErrorCode *status); + +/** + * Given a key and a locale, returns an array of string values in a preferred + * order that would make a difference. These are all and only those values where + * the open (creation) of the service with the locale formed from the input locale + * plus input keyword and that value has different behavior than creation with the + * input locale alone. + * @param key one of the keys supported by this service. For now, only + * "collation" is supported. + * @param locale the locale + * @param commonlyUsed if set to true it will return only commonly used values + * with the given locale in preferred order. Otherwise, + * it will return all the available values for the locale. + * @param status error status + * @return a string enumeration over keyword values for the given key and the locale. + * @stable ICU 4.2 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucol_getKeywordValuesForLocale(const char* key, + const char* locale, + UBool commonlyUsed, + UErrorCode* status); + +/** + * Return the functionally equivalent locale for the specified + * input locale, with respect to given keyword, for the + * collation service. If two different input locale + keyword + * combinations produce the same result locale, then collators + * instantiated for these two different input locales will behave + * equivalently. The converse is not always true; two collators + * may in fact be equivalent, but return different results, due to + * internal details. The return result has no other meaning than + * that stated above, and implies nothing as to the relationship + * between the two locales. This is intended for use by + * applications who wish to cache collators, or otherwise reuse + * collators when possible. The functional equivalent may change + * over time. For more information, please see the + * Locales and Services section of the ICU User Guide. + * @param result fillin for the functionally equivalent result locale + * @param resultCapacity capacity of the fillin buffer + * @param keyword a particular keyword as enumerated by + * ucol_getKeywords. + * @param locale the specified input locale + * @param isAvailable if non-NULL, pointer to a fillin parameter that + * on return indicates whether the specified input locale was 'available' + * to the collation service. A locale is defined as 'available' if it + * physically exists within the collation locale data. + * @param status pointer to input-output error code + * @return the actual buffer size needed for the locale. If greater + * than resultCapacity, the returned full name will be truncated and + * an error code will be returned. + * @stable ICU 3.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getFunctionalEquivalent(char* result, int32_t resultCapacity, + const char* keyword, const char* locale, + UBool* isAvailable, UErrorCode* status); + +/** + * Get the collation tailoring rules from a UCollator. + * The rules will follow the rule syntax. + * @param coll The UCollator to query. + * @param length + * @return The collation tailoring rules. + * @stable ICU 2.0 + */ +U_CAPI const UChar* U_EXPORT2 +ucol_getRules( const UCollator *coll, + int32_t *length); + +#ifndef U_HIDE_DEPRECATED_API +/** Get the short definition string for a collator. This API harvests the collator's + * locale and the attribute set and produces a string that can be used for opening + * a collator with the same attributes using the ucol_openFromShortString API. + * This string will be normalized. + * The structure and the syntax of the string is defined in the "Naming collators" + * section of the users guide: + * https://unicode-org.github.io/icu/userguide/collation/concepts#collator-naming-scheme + * This API supports preflighting. + * @param coll a collator + * @param locale a locale that will appear as a collators locale in the resulting + * short string definition. If NULL, the locale will be harvested + * from the collator. + * @param buffer space to hold the resulting string + * @param capacity capacity of the buffer + * @param status for returning errors. All the preflighting errors are featured + * @return length of the resulting string + * @see ucol_openFromShortString + * @see ucol_normalizeShortDefinitionString + * @deprecated ICU 54 + */ +U_DEPRECATED int32_t U_EXPORT2 +ucol_getShortDefinitionString(const UCollator *coll, + const char *locale, + char *buffer, + int32_t capacity, + UErrorCode *status); + +/** Verifies and normalizes short definition string. + * Normalized short definition string has all the option sorted by the argument name, + * so that equivalent definition strings are the same. + * This API supports preflighting. + * @param source definition string + * @param destination space to hold the resulting string + * @param capacity capacity of the buffer + * @param parseError if not NULL, structure that will get filled with error's pre + * and post context in case of error. + * @param status Error code. This API will return an error if an invalid attribute + * or attribute/value combination is specified. All the preflighting + * errors are also featured + * @return length of the resulting normalized string. + * + * @see ucol_openFromShortString + * @see ucol_getShortDefinitionString + * + * @deprecated ICU 54 + */ +U_DEPRECATED int32_t U_EXPORT2 +ucol_normalizeShortDefinitionString(const char *source, + char *destination, + int32_t capacity, + UParseError *parseError, + UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + + +/** + * Get a sort key for a string from a UCollator. + * Sort keys may be compared using strcmp. + * + * Note that sort keys are often less efficient than simply doing comparison. + * For more details, see the ICU User Guide. + * + * Like ICU functions that write to an output buffer, the buffer contents + * is undefined if the buffer capacity (resultLength parameter) is too small. + * Unlike ICU functions that write a string to an output buffer, + * the terminating zero byte is counted in the sort key length. + * @param coll The UCollator containing the collation rules. + * @param source The string to transform. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param result A pointer to a buffer to receive the attribute. + * @param resultLength The maximum size of result. + * @return The size needed to fully store the sort key. + * If there was an internal error generating the sort key, + * a zero value is returned. + * @see ucol_keyHashCode + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getSortKey(const UCollator *coll, + const UChar *source, + int32_t sourceLength, + uint8_t *result, + int32_t resultLength); + + +/** Gets the next count bytes of a sort key. Caller needs + * to preserve state array between calls and to provide + * the same type of UCharIterator set with the same string. + * The destination buffer provided must be big enough to store + * the number of requested bytes. + * + * The generated sort key may or may not be compatible with + * sort keys generated using ucol_getSortKey(). + * @param coll The UCollator containing the collation rules. + * @param iter UCharIterator containing the string we need + * the sort key to be calculated for. + * @param state Opaque state of sortkey iteration. + * @param dest Buffer to hold the resulting sortkey part + * @param count number of sort key bytes required. + * @param status error code indicator. + * @return the actual number of bytes of a sortkey. It can be + * smaller than count if we have reached the end of + * the sort key. + * @stable ICU 2.6 + */ +U_CAPI int32_t U_EXPORT2 +ucol_nextSortKeyPart(const UCollator *coll, + UCharIterator *iter, + uint32_t state[2], + uint8_t *dest, int32_t count, + UErrorCode *status); + +/** enum that is taken by ucol_getBound API + * See below for explanation + * do not change the values assigned to the + * members of this enum. Underlying code + * depends on them having these numbers + * @stable ICU 2.0 + */ +typedef enum { + /** lower bound */ + UCOL_BOUND_LOWER = 0, + /** upper bound that will match strings of exact size */ + UCOL_BOUND_UPPER = 1, + /** upper bound that will match all the strings that have the same initial substring as the given string */ + UCOL_BOUND_UPPER_LONG = 2, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UColBoundMode value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCOL_BOUND_VALUE_COUNT +#endif /* U_HIDE_DEPRECATED_API */ +} UColBoundMode; + +/** + * Produce a bound for a given sortkey and a number of levels. + * Return value is always the number of bytes needed, regardless of + * whether the result buffer was big enough or even valid.
+ * Resulting bounds can be used to produce a range of strings that are + * between upper and lower bounds. For example, if bounds are produced + * for a sortkey of string "smith", strings between upper and lower + * bounds with one level would include "Smith", "SMITH", "sMiTh".
+ * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER + * is produced, strings matched would be as above. However, if bound + * produced using UCOL_BOUND_UPPER_LONG is used, the above example will + * also match "Smithsonian" and similar.
+ * For more on usage, see example in cintltst/capitst.c in procedure + * TestBounds. + * Sort keys may be compared using strcmp. + * @param source The source sortkey. + * @param sourceLength The length of source, or -1 if null-terminated. + * (If an unmodified sortkey is passed, it is always null + * terminated). + * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which + * produces a lower inclusive bound, UCOL_BOUND_UPPER, that + * produces upper bound that matches strings of the same length + * or UCOL_BOUND_UPPER_LONG that matches strings that have the + * same starting substring as the source string. + * @param noOfLevels Number of levels required in the resulting bound (for most + * uses, the recommended value is 1). See users guide for + * explanation on number of levels a sortkey can have. + * @param result A pointer to a buffer to receive the resulting sortkey. + * @param resultLength The maximum size of result. + * @param status Used for returning error code if something went wrong. If the + * number of levels requested is higher than the number of levels + * in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is + * issued. + * @return The size needed to fully store the bound. + * @see ucol_keyHashCode + * @stable ICU 2.1 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getBound(const uint8_t *source, + int32_t sourceLength, + UColBoundMode boundType, + uint32_t noOfLevels, + uint8_t *result, + int32_t resultLength, + UErrorCode *status); + +/** + * Gets the version information for a Collator. Version is currently + * an opaque 32-bit number which depends, among other things, on major + * versions of the collator tailoring and UCA. + * @param coll The UCollator to query. + * @param info the version # information, the result will be filled in + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_getVersion(const UCollator* coll, UVersionInfo info); + +/** + * Gets the UCA version information for a Collator. Version is the + * UCA version number (3.1.1, 4.0). + * @param coll The UCollator to query. + * @param info the version # information, the result will be filled in + * @stable ICU 2.8 + */ +U_CAPI void U_EXPORT2 +ucol_getUCAVersion(const UCollator* coll, UVersionInfo info); + +/** + * Merges two sort keys. The levels are merged with their corresponding counterparts + * (primaries with primaries, secondaries with secondaries etc.). Between the values + * from the same level a separator is inserted. + * + * This is useful, for example, for combining sort keys from first and last names + * to sort such pairs. + * See http://www.unicode.org/reports/tr10/#Merging_Sort_Keys + * + * The recommended way to achieve "merged" sorting is by + * concatenating strings with U+FFFE between them. + * The concatenation has the same sort order as the merged sort keys, + * but merge(getSortKey(str1), getSortKey(str2)) may differ from getSortKey(str1 + '\\uFFFE' + str2). + * Using strings with U+FFFE may yield shorter sort keys. + * + * For details about Sort Key Features see + * https://unicode-org.github.io/icu/userguide/collation/api#sort-key-features + * + * It is possible to merge multiple sort keys by consecutively merging + * another one with the intermediate result. + * + * The length of the merge result is the sum of the lengths of the input sort keys. + * + * Example (uncompressed): + *

191B1D 01 050505 01 910505 00
+ * 1F2123 01 050505 01 910505 00
+ * will be merged as + *
191B1D 02 1F2123 01 050505 02 050505 01 910505 02 910505 00
+ * + * If the destination buffer is not big enough, then its contents are undefined. + * If any of source lengths are zero or any of the source pointers are NULL/undefined, + * the result is of size zero. + * + * @param src1 the first sort key + * @param src1Length the length of the first sort key, including the zero byte at the end; + * can be -1 if the function is to find the length + * @param src2 the second sort key + * @param src2Length the length of the second sort key, including the zero byte at the end; + * can be -1 if the function is to find the length + * @param dest the buffer where the merged sort key is written, + * can be NULL if destCapacity==0 + * @param destCapacity the number of bytes in the dest buffer + * @return the length of the merged sort key, src1Length+src2Length; + * can be larger than destCapacity, or 0 if an error occurs (only for illegal arguments), + * in which cases the contents of dest is undefined + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_mergeSortkeys(const uint8_t *src1, int32_t src1Length, + const uint8_t *src2, int32_t src2Length, + uint8_t *dest, int32_t destCapacity); + +/** + * Universal attribute setter + * @param coll collator which attributes are to be changed + * @param attr attribute type + * @param value attribute value + * @param status to indicate whether the operation went on smoothly or there were errors + * @see UColAttribute + * @see UColAttributeValue + * @see ucol_getAttribute + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_setAttribute(UCollator *coll, UColAttribute attr, UColAttributeValue value, UErrorCode *status); + +/** + * Universal attribute getter + * @param coll collator which attributes are to be changed + * @param attr attribute type + * @return attribute value + * @param status to indicate whether the operation went on smoothly or there were errors + * @see UColAttribute + * @see UColAttributeValue + * @see ucol_setAttribute + * @stable ICU 2.0 + */ +U_CAPI UColAttributeValue U_EXPORT2 +ucol_getAttribute(const UCollator *coll, UColAttribute attr, UErrorCode *status); + +/** + * Sets the variable top to the top of the specified reordering group. + * The variable top determines the highest-sorting character + * which is affected by UCOL_ALTERNATE_HANDLING. + * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. + * @param coll the collator + * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, + * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; + * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @see ucol_getMaxVariable + * @stable ICU 53 + */ +U_CAPI void U_EXPORT2 +ucol_setMaxVariable(UCollator *coll, UColReorderCode group, UErrorCode *pErrorCode); + +/** + * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. + * @param coll the collator + * @return the maximum variable reordering group. + * @see ucol_setMaxVariable + * @stable ICU 53 + */ +U_CAPI UColReorderCode U_EXPORT2 +ucol_getMaxVariable(const UCollator *coll); + +#ifndef U_HIDE_DEPRECATED_API +/** + * Sets the variable top to the primary weight of the specified string. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See ucol_setMaxVariable(). + * @param coll the collator + * @param varTop one or more (if contraction) UChars to which the variable top should be set + * @param len length of variable top string. If -1 it is considered to be zero terminated. + * @param status error code. If error code is set, the return value is undefined. + * Errors set by this function are:
+ * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
+ * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond + * the last reordering group supported by ucol_setMaxVariable() + * @return variable top primary weight + * @see ucol_getVariableTop + * @see ucol_restoreVariableTop + * @deprecated ICU 53 Call ucol_setMaxVariable() instead. + */ +U_DEPRECATED uint32_t U_EXPORT2 +ucol_setVariableTop(UCollator *coll, + const UChar *varTop, int32_t len, + UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Gets the variable top value of a Collator. + * @param coll collator which variable top needs to be retrieved + * @param status error code (not changed by function). If error code is set, + * the return value is undefined. + * @return the variable top primary weight + * @see ucol_getMaxVariable + * @see ucol_setVariableTop + * @see ucol_restoreVariableTop + * @stable ICU 2.0 + */ +U_CAPI uint32_t U_EXPORT2 ucol_getVariableTop(const UCollator *coll, UErrorCode *status); + +#ifndef U_HIDE_DEPRECATED_API +/** + * Sets the variable top to the specified primary weight. + * + * Beginning with ICU 53, the variable top is pinned to + * the top of one of the supported reordering groups, + * and it must not be beyond the last of those groups. + * See ucol_setMaxVariable(). + * @param coll collator to be set + * @param varTop primary weight, as returned by ucol_setVariableTop or ucol_getVariableTop + * @param status error code + * @see ucol_getVariableTop + * @see ucol_setVariableTop + * @deprecated ICU 53 Call ucol_setMaxVariable() instead. + */ +U_DEPRECATED void U_EXPORT2 +ucol_restoreVariableTop(UCollator *coll, const uint32_t varTop, UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Thread safe cloning operation. The result is a clone of a given collator. + * @param coll collator to be cloned + * @param status to indicate whether the operation went on smoothly or there were errors + * @return pointer to the new clone + * @see ucol_open + * @see ucol_openRules + * @see ucol_close + * @stable ICU 71 + */ +U_CAPI UCollator* U_EXPORT2 ucol_clone(const UCollator *coll, UErrorCode *status); + +#ifndef U_HIDE_DEPRECATED_API + +/** + * Thread safe cloning operation. The result is a clone of a given collator. + * @param coll collator to be cloned + * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
+ * user allocated space for the new clone. + * If NULL new memory will be allocated. + * If buffer is not large enough, new memory will be allocated. + * Clients can use the U_COL_SAFECLONE_BUFFERSIZE. + * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
+ * pointer to size of allocated space. + * If *pBufferSize == 0, a sufficient size for use in cloning will + * be returned ('pre-flighting') + * If *pBufferSize is not enough for a stack-based safe clone, + * new memory will be allocated. + * @param status to indicate whether the operation went on smoothly or there were errors + * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used + * if pBufferSize != NULL and any allocations were necessary + * @return pointer to the new clone + * @see ucol_open + * @see ucol_openRules + * @see ucol_close + * @deprecated ICU 71 Use ucol_clone() instead. + */ +U_DEPRECATED UCollator* U_EXPORT2 +ucol_safeClone(const UCollator *coll, + void *stackBuffer, + int32_t *pBufferSize, + UErrorCode *status); + + +/** default memory size for the new clone. + * @deprecated ICU 52. Do not rely on ucol_safeClone() cloning into any provided buffer. + */ +#define U_COL_SAFECLONE_BUFFERSIZE 1 + +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * Returns current rules. Delta defines whether full rules are returned or just the tailoring. + * Returns number of UChars needed to store rules. If buffer is NULL or bufferLen is not enough + * to store rules, will store up to available space. + * + * ucol_getRules() should normally be used instead. + * See https://unicode-org.github.io/icu/userguide/collation/customization#building-on-existing-locales + * @param coll collator to get the rules from + * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES. + * @param buffer buffer to store the result in. If NULL, you'll get no rules. + * @param bufferLen length of buffer to store rules in. If less than needed you'll get only the part that fits in. + * @return current rules + * @stable ICU 2.0 + * @see UCOL_FULL_RULES + */ +U_CAPI int32_t U_EXPORT2 +ucol_getRulesEx(const UCollator *coll, UColRuleOption delta, UChar *buffer, int32_t bufferLen); + +#ifndef U_HIDE_DEPRECATED_API +/** + * gets the locale name of the collator. If the collator + * is instantiated from the rules, then this function returns + * NULL. + * @param coll The UCollator for which the locale is needed + * @param type You can choose between requested, valid and actual + * locale. For description see the definition of + * ULocDataLocaleType in uloc.h + * @param status error code of the operation + * @return real locale name from which the collation data comes. + * If the collator was instantiated from rules, returns + * NULL. + * @deprecated ICU 2.8 Use ucol_getLocaleByType instead + */ +U_DEPRECATED const char * U_EXPORT2 +ucol_getLocale(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status); +#endif /* U_HIDE_DEPRECATED_API */ + +/** + * gets the locale name of the collator. If the collator + * is instantiated from the rules, then this function returns + * NULL. + * @param coll The UCollator for which the locale is needed + * @param type You can choose between requested, valid and actual + * locale. For description see the definition of + * ULocDataLocaleType in uloc.h + * @param status error code of the operation + * @return real locale name from which the collation data comes. + * If the collator was instantiated from rules, returns + * NULL. + * @stable ICU 2.8 + */ +U_CAPI const char * U_EXPORT2 +ucol_getLocaleByType(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status); + +/** + * Get a Unicode set that contains all the characters and sequences tailored in + * this collator. The result must be disposed of by using uset_close. + * @param coll The UCollator for which we want to get tailored chars + * @param status error code of the operation + * @return a pointer to newly created USet. Must be be disposed by using uset_close + * @see ucol_openRules + * @see uset_close + * @stable ICU 2.4 + */ +U_CAPI USet * U_EXPORT2 +ucol_getTailoredSet(const UCollator *coll, UErrorCode *status); + +#ifndef U_HIDE_INTERNAL_API +/** Calculates the set of unsafe code points, given a collator. + * A character is unsafe if you could append any character and cause the ordering to alter significantly. + * Collation sorts in normalized order, so anything that rearranges in normalization can cause this. + * Thus if you have a character like a_umlaut, and you add a lower_dot to it, + * then it normalizes to a_lower_dot + umlaut, and sorts differently. + * @param coll Collator + * @param unsafe a fill-in set to receive the unsafe points + * @param status for catching errors + * @return number of elements in the set + * @internal ICU 3.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getUnsafeSet( const UCollator *coll, + USet *unsafe, + UErrorCode *status); + +/** Touches all resources needed for instantiating a collator from a short string definition, + * thus filling up the cache. + * @param definition A short string containing a locale and a set of attributes. + * Attributes not explicitly mentioned are left at the default + * state for a locale. + * @param parseError if not NULL, structure that will get filled with error's pre + * and post context in case of error. + * @param forceDefaults if false, the settings that are the same as the collator + * default settings will not be applied (for example, setting + * French secondary on a French collator would not be executed). + * If true, all the settings will be applied regardless of the + * collator default value. If the definition + * strings are to be cached, should be set to false. + * @param status Error code. Apart from regular error conditions connected to + * instantiating collators (like out of memory or similar), this + * API will return an error if an invalid attribute or attribute/value + * combination is specified. + * @see ucol_openFromShortString + * @internal ICU 3.2.1 + */ +U_CAPI void U_EXPORT2 +ucol_prepareShortStringOpen( const char *definition, + UBool forceDefaults, + UParseError *parseError, + UErrorCode *status); +#endif /* U_HIDE_INTERNAL_API */ + +/** Creates a binary image of a collator. This binary image can be stored and + * later used to instantiate a collator using ucol_openBinary. + * This API supports preflighting. + * @param coll Collator + * @param buffer a fill-in buffer to receive the binary image + * @param capacity capacity of the destination buffer + * @param status for catching errors + * @return size of the image + * @see ucol_openBinary + * @stable ICU 3.2 + */ +U_CAPI int32_t U_EXPORT2 +ucol_cloneBinary(const UCollator *coll, + uint8_t *buffer, int32_t capacity, + UErrorCode *status); + +/** Opens a collator from a collator binary image created using + * ucol_cloneBinary. Binary image used in instantiation of the + * collator remains owned by the user and should stay around for + * the lifetime of the collator. The API also takes a base collator + * which must be the root collator. + * @param bin binary image owned by the user and required through the + * lifetime of the collator + * @param length size of the image. If negative, the API will try to + * figure out the length of the image + * @param base Base collator, for lookup of untailored characters. + * Must be the root collator, must not be NULL. + * The base is required to be present through the lifetime of the collator. + * @param status for catching errors + * @return newly created collator + * @see ucol_cloneBinary + * @stable ICU 3.2 + */ +U_CAPI UCollator* U_EXPORT2 +ucol_openBinary(const uint8_t *bin, int32_t length, + const UCollator *base, + UErrorCode *status); + + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucoleitr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucoleitr.h new file mode 100644 index 0000000000000000000000000000000000000000..25efcf2a08e77ee8c4428111a86ef3e32601ef1f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucoleitr.h @@ -0,0 +1,276 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2001-2014, International Business Machines +* Corporation and others. All Rights Reserved. +******************************************************************************* +* +* File ucoleitr.h +* +* Modification History: +* +* Date Name Description +* 02/15/2001 synwee Modified all methods to process its own function +* instead of calling the equivalent c++ api (coleitr.h) +*******************************************************************************/ + +#ifndef UCOLEITR_H +#define UCOLEITR_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_COLLATION + +/** + * This indicates an error has occurred during processing or if no more CEs is + * to be returned. + * @stable ICU 2.0 + */ +#define UCOL_NULLORDER ((int32_t)0xFFFFFFFF) + +#include "unicode/ucol.h" + +/** + * The UCollationElements struct. + * For usage in C programs. + * @stable ICU 2.0 + */ +typedef struct UCollationElements UCollationElements; + +/** + * \file + * \brief C API: UCollationElements + * + * The UCollationElements API is used as an iterator to walk through each + * character of an international string. Use the iterator to return the + * ordering priority of the positioned character. The ordering priority of a + * character, which we refer to as a key, defines how a character is collated + * in the given collation object. + * For example, consider the following in Slovak and in traditional Spanish collation: + *
+ * .       "ca" -> the first key is key('c') and second key is key('a').
+ * .       "cha" -> the first key is key('ch') and second key is key('a').
+ * 
+ * And in German phonebook collation, + *
+ * .       "b"-> the first key is key('a'), the second key is key('e'), and
+ * .       the third key is key('b').
+ * 
+ *

Example of the iterator usage: (without error checking) + *

+ * .  void CollationElementIterator_Example()
+ * .  {
+ * .      UChar *s;
+ * .      t_int32 order, primaryOrder;
+ * .      UCollationElements *c;
+ * .      UCollatorOld *coll;
+ * .      UErrorCode success = U_ZERO_ERROR;
+ * .      str=(UChar*)malloc(sizeof(UChar) * (strlen("This is a test")+1) );
+ * .      u_uastrcpy(str, "This is a test");
+ * .      coll = ucol_open(NULL, &success);
+ * .      c = ucol_openElements(coll, str, u_strlen(str), &status);
+ * .      order = ucol_next(c, &success);
+ * .      ucol_reset(c);
+ * .      order = ucol_prev(c, &success);
+ * .      free(str);
+ * .      ucol_close(coll);
+ * .      ucol_closeElements(c);
+ * .  }
+ * 
+ *

+ * ucol_next() returns the collation order of the next. + * ucol_prev() returns the collation order of the previous character. + * The Collation Element Iterator moves only in one direction between calls to + * ucol_reset. That is, ucol_next() and ucol_prev can not be inter-used. + * Whenever ucol_prev is to be called after ucol_next() or vice versa, + * ucol_reset has to be called first to reset the status, shifting pointers to + * either the end or the start of the string. Hence at the next call of + * ucol_prev or ucol_next, the first or last collation order will be returned. + * If a change of direction is done without a ucol_reset, the result is + * undefined. + * The result of a forward iterate (ucol_next) and reversed result of the + * backward iterate (ucol_prev) on the same string are equivalent, if + * collation orders with the value 0 are ignored. + * Character based on the comparison level of the collator. A collation order + * consists of primary order, secondary order and tertiary order. The data + * type of the collation order is int32_t. + * + * @see UCollator + */ + +/** + * Open the collation elements for a string. + * + * The UCollationElements retains a pointer to the supplied text. + * The caller must not modify or delete the text while the UCollationElements + * object is used to iterate over this text. + * + * @param coll The collator containing the desired collation rules. + * @param text The text to iterate over. + * @param textLength The number of characters in text, or -1 if null-terminated + * @param status A pointer to a UErrorCode to receive any errors. + * @return a struct containing collation element information + * @stable ICU 2.0 + */ +U_CAPI UCollationElements* U_EXPORT2 +ucol_openElements(const UCollator *coll, + const UChar *text, + int32_t textLength, + UErrorCode *status); + +/** + * get a hash code for a key... Not very useful! + * @param key the given key. + * @param length the size of the key array. + * @return the hash code. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_keyHashCode(const uint8_t* key, int32_t length); + +/** + * Close a UCollationElements. + * Once closed, a UCollationElements may no longer be used. + * @param elems The UCollationElements to close. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_closeElements(UCollationElements *elems); + +/** + * Reset the collation elements to their initial state. + * This will move the 'cursor' to the beginning of the text. + * Property settings for collation will be reset to the current status. + * @param elems The UCollationElements to reset. + * @see ucol_next + * @see ucol_previous + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_reset(UCollationElements *elems); + +/** + * Get the ordering priority of the next collation element in the text. + * A single character may contain more than one collation element. + * @param elems The UCollationElements containing the text. + * @param status A pointer to a UErrorCode to receive any errors. + * @return The next collation elements ordering, otherwise returns UCOL_NULLORDER + * if an error has occurred or if the end of string has been reached + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_next(UCollationElements *elems, UErrorCode *status); + +/** + * Get the ordering priority of the previous collation element in the text. + * A single character may contain more than one collation element. + * Note that internally a stack is used to store buffered collation elements. + * @param elems The UCollationElements containing the text. + * @param status A pointer to a UErrorCode to receive any errors. Notably + * a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack + * buffer has been exhausted. + * @return The previous collation elements ordering, otherwise returns + * UCOL_NULLORDER if an error has occurred or if the start of string has + * been reached. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_previous(UCollationElements *elems, UErrorCode *status); + +/** + * Get the maximum length of any expansion sequences that end with the + * specified comparison order. + * This is useful for .... ? + * @param elems The UCollationElements containing the text. + * @param order A collation order returned by previous or next. + * @return maximum size of the expansion sequences ending with the collation + * element or 1 if collation element does not occur at the end of any + * expansion sequence + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getMaxExpansion(const UCollationElements *elems, int32_t order); + +/** + * Set the text containing the collation elements. + * Property settings for collation will remain the same. + * In order to reset the iterator to the current collation property settings, + * the API reset() has to be called. + * + * The UCollationElements retains a pointer to the supplied text. + * The caller must not modify or delete the text while the UCollationElements + * object is used to iterate over this text. + * + * @param elems The UCollationElements to set. + * @param text The source text containing the collation elements. + * @param textLength The length of text, or -1 if null-terminated. + * @param status A pointer to a UErrorCode to receive any errors. + * @see ucol_getText + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_setText( UCollationElements *elems, + const UChar *text, + int32_t textLength, + UErrorCode *status); + +/** + * Get the offset of the current source character. + * This is an offset into the text of the character containing the current + * collation elements. + * @param elems The UCollationElements to query. + * @return The offset of the current source character. + * @see ucol_setOffset + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +ucol_getOffset(const UCollationElements *elems); + +/** + * Set the offset of the current source character. + * This is an offset into the text of the character to be processed. + * Property settings for collation will remain the same. + * In order to reset the iterator to the current collation property settings, + * the API reset() has to be called. + * @param elems The UCollationElements to set. + * @param offset The desired character offset. + * @param status A pointer to a UErrorCode to receive any errors. + * @see ucol_getOffset + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +ucol_setOffset(UCollationElements *elems, + int32_t offset, + UErrorCode *status); + +/** +* Get the primary order of a collation order. +* @param order the collation order +* @return the primary order of a collation order. +* @stable ICU 2.6 +*/ +U_CAPI int32_t U_EXPORT2 +ucol_primaryOrder (int32_t order); + +/** +* Get the secondary order of a collation order. +* @param order the collation order +* @return the secondary order of a collation order. +* @stable ICU 2.6 +*/ +U_CAPI int32_t U_EXPORT2 +ucol_secondaryOrder (int32_t order); + +/** +* Get the tertiary order of a collation order. +* @param order the collation order +* @return the tertiary order of a collation order. +* @stable ICU 2.6 +*/ +U_CAPI int32_t U_EXPORT2 +ucol_tertiaryOrder (int32_t order); + +#endif /* #if !UCONFIG_NO_COLLATION */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uconfig.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uconfig.h new file mode 100644 index 0000000000000000000000000000000000000000..3818ca02ef85d2a90f1ce0a52fdb8bc7f01f5fc6 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uconfig.h @@ -0,0 +1,466 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 2002-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* file name: uconfig.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2002sep19 +* created by: Markus W. Scherer +*/ + +#ifndef __UCONFIG_H__ +#define __UCONFIG_H__ + + +/*! + * \file + * \brief User-configurable settings + * + * Miscellaneous switches: + * + * A number of macros affect a variety of minor aspects of ICU. + * Most of them used to be defined elsewhere (e.g., in utypes.h or platform.h) + * and moved here to make them easier to find. + * + * Switches for excluding parts of ICU library code modules: + * + * Changing these macros allows building partial, smaller libraries for special purposes. + * By default, all modules are built. + * The switches are fairly coarse, controlling large modules. + * Basic services cannot be turned off. + * + * Building with any of these options does not guarantee that the + * ICU build process will completely work. It is recommended that + * the ICU libraries and data be built using the normal build. + * At that time you should remove the data used by those services. + * After building the ICU data library, you should rebuild the ICU + * libraries with these switches customized to your needs. + * + * @stable ICU 2.4 + */ + +/** + * If this switch is defined, ICU will attempt to load a header file named "uconfig_local.h" + * prior to determining default settings for uconfig variables. + * + * @internal ICU 4.0 + */ +#if defined(UCONFIG_USE_LOCAL) +#include "uconfig_local.h" +#endif + +/** + * \def U_DEBUG + * Determines whether to include debugging code. + * Automatically set on Windows, but most compilers do not have + * related predefined macros. + * @internal + */ +#ifdef U_DEBUG + /* Use the predefined value. */ +#elif defined(_DEBUG) + /* + * _DEBUG is defined by Visual Studio debug compilation. + * Do *not* test for its NDEBUG macro: It is an orthogonal macro + * which disables assert(). + */ +# define U_DEBUG 1 +# else +# define U_DEBUG 0 +#endif + +/** + * Determines whether to enable auto cleanup of libraries. + * @internal + */ +#ifndef UCLN_NO_AUTO_CLEANUP +#define UCLN_NO_AUTO_CLEANUP 1 +#endif + +/** + * \def U_DISABLE_RENAMING + * Determines whether to disable renaming or not. + * @internal + */ +#ifndef U_DISABLE_RENAMING +#define U_DISABLE_RENAMING 0 +#endif + +/** + * \def U_NO_DEFAULT_INCLUDE_UTF_HEADERS + * Determines whether utypes.h includes utf.h, utf8.h, utf16.h and utf_old.h. + * utypes.h includes those headers if this macro is defined to 0. + * Otherwise, each those headers must be included explicitly when using one of their macros. + * Defaults to 0 for backward compatibility, except inside ICU. + * @stable ICU 49 + */ +#ifdef U_NO_DEFAULT_INCLUDE_UTF_HEADERS + /* Use the predefined value. */ +#elif defined(U_COMBINED_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION) || defined(U_I18N_IMPLEMENTATION) || \ + defined(U_IO_IMPLEMENTATION) || defined(U_LAYOUT_IMPLEMENTATION) || defined(U_LAYOUTEX_IMPLEMENTATION) || \ + defined(U_TOOLUTIL_IMPLEMENTATION) +# define U_NO_DEFAULT_INCLUDE_UTF_HEADERS 1 +#else +# define U_NO_DEFAULT_INCLUDE_UTF_HEADERS 0 +#endif + +/** + * \def U_OVERRIDE_CXX_ALLOCATION + * Determines whether to override new and delete. + * ICU is normally built such that all of its C++ classes, via their UMemory base, + * override operators new and delete to use its internal, customizable, + * non-exception-throwing memory allocation functions. (Default value 1 for this macro.) + * + * This is especially important when the application and its libraries use multiple heaps. + * For example, on Windows, this allows the ICU DLL to be used by + * applications that statically link the C Runtime library. + * + * @stable ICU 2.2 + */ +#ifndef U_OVERRIDE_CXX_ALLOCATION +#define U_OVERRIDE_CXX_ALLOCATION 1 +#endif + +/** + * \def U_ENABLE_TRACING + * Determines whether to enable tracing. + * @internal + */ +#ifndef U_ENABLE_TRACING +#define U_ENABLE_TRACING 0 +#endif + +/** + * \def UCONFIG_ENABLE_PLUGINS + * Determines whether to enable ICU plugins. + * @internal + */ +#ifndef UCONFIG_ENABLE_PLUGINS +#define UCONFIG_ENABLE_PLUGINS 0 +#endif + +/** + * \def U_ENABLE_DYLOAD + * Whether to enable Dynamic loading in ICU. + * @internal + */ +#ifndef U_ENABLE_DYLOAD +#define U_ENABLE_DYLOAD 1 +#endif + +/** + * \def U_CHECK_DYLOAD + * Whether to test Dynamic loading as an OS capability. + * @internal + */ +#ifndef U_CHECK_DYLOAD +#define U_CHECK_DYLOAD 1 +#endif + +/** + * \def U_DEFAULT_SHOW_DRAFT + * Do we allow ICU users to use the draft APIs by default? + * @internal + */ +#ifndef U_DEFAULT_SHOW_DRAFT +#define U_DEFAULT_SHOW_DRAFT 1 +#endif + +/*===========================================================================*/ +/* Custom icu entry point renaming */ +/*===========================================================================*/ + +/** + * \def U_HAVE_LIB_SUFFIX + * 1 if a custom library suffix is set. + * @internal + */ +#ifdef U_HAVE_LIB_SUFFIX + /* Use the predefined value. */ +#elif defined(U_LIB_SUFFIX_C_NAME) || defined(U_IN_DOXYGEN) +# define U_HAVE_LIB_SUFFIX 1 +#endif + +/** + * \def U_LIB_SUFFIX_C_NAME_STRING + * Defines the library suffix as a string with C syntax. + * @internal + */ +#ifdef U_LIB_SUFFIX_C_NAME_STRING + /* Use the predefined value. */ +#elif defined(U_LIB_SUFFIX_C_NAME) +# define CONVERT_TO_STRING(s) #s +# define U_LIB_SUFFIX_C_NAME_STRING CONVERT_TO_STRING(U_LIB_SUFFIX_C_NAME) +#else +# define U_LIB_SUFFIX_C_NAME_STRING "" +#endif + +/* common/i18n library switches --------------------------------------------- */ + +/** + * \def UCONFIG_ONLY_COLLATION + * This switch turns off modules that are not needed for collation. + * + * It does not turn off legacy conversion because that is necessary + * for ICU to work on EBCDIC platforms (for the default converter). + * If you want "only collation" and do not build for EBCDIC, + * then you can define UCONFIG_NO_CONVERSION or UCONFIG_NO_LEGACY_CONVERSION to 1 as well. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_ONLY_COLLATION +# define UCONFIG_ONLY_COLLATION 0 +#endif + +#if UCONFIG_ONLY_COLLATION + /* common library */ +# define UCONFIG_NO_BREAK_ITERATION 1 +# define UCONFIG_NO_IDNA 1 + + /* i18n library */ +# if UCONFIG_NO_COLLATION +# error Contradictory collation switches in uconfig.h. +# endif +# define UCONFIG_NO_FORMATTING 1 +# define UCONFIG_NO_TRANSLITERATION 1 +# define UCONFIG_NO_REGULAR_EXPRESSIONS 1 +#endif + +/* common library switches -------------------------------------------------- */ + +/** + * \def UCONFIG_NO_FILE_IO + * This switch turns off all file access in the common library + * where file access is only used for data loading. + * ICU data must then be provided in the form of a data DLL (or with an + * equivalent way to link to the data residing in an executable, + * as in building a combined library with both the common library's code and + * the data), or via udata_setCommonData(). + * Application data must be provided via udata_setAppData() or by using + * "open" functions that take pointers to data, for example ucol_openBinary(). + * + * File access is not used at all in the i18n library. + * + * File access cannot be turned off for the icuio library or for the ICU + * test suites and ICU tools. + * + * @stable ICU 3.6 + */ +#ifndef UCONFIG_NO_FILE_IO +# define UCONFIG_NO_FILE_IO 0 +#endif + +#if UCONFIG_NO_FILE_IO && defined(U_TIMEZONE_FILES_DIR) +# error Contradictory file io switches in uconfig.h. +#endif + +/** + * \def UCONFIG_NO_CONVERSION + * ICU will not completely build (compiling the tools fails) with this + * switch turned on. + * This switch turns off all converters. + * + * You may want to use this together with U_CHARSET_IS_UTF8 defined to 1 + * in utypes.h if char* strings in your environment are always in UTF-8. + * + * @stable ICU 3.2 + * @see U_CHARSET_IS_UTF8 + */ +#ifndef UCONFIG_NO_CONVERSION +# define UCONFIG_NO_CONVERSION 0 +#endif + +#if UCONFIG_NO_CONVERSION +# define UCONFIG_NO_LEGACY_CONVERSION 1 +#endif + +/** + * \def UCONFIG_ONLY_HTML_CONVERSION + * This switch turns off all of the converters NOT listed in + * the HTML encoding standard: + * http://www.w3.org/TR/encoding/#names-and-labels + * + * This is not possible on EBCDIC platforms + * because they need ibm-37 or ibm-1047 default converters. + * + * @stable ICU 55 + */ +#ifndef UCONFIG_ONLY_HTML_CONVERSION +# define UCONFIG_ONLY_HTML_CONVERSION 0 +#endif + +/** + * \def UCONFIG_NO_LEGACY_CONVERSION + * This switch turns off all converters except for + * - Unicode charsets (UTF-7/8/16/32, CESU-8, SCSU, BOCU-1) + * - US-ASCII + * - ISO-8859-1 + * + * Turning off legacy conversion is not possible on EBCDIC platforms + * because they need ibm-37 or ibm-1047 default converters. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_LEGACY_CONVERSION +# define UCONFIG_NO_LEGACY_CONVERSION 0 +#endif + +/** + * \def UCONFIG_NO_NORMALIZATION + * This switch turns off normalization. + * It implies turning off several other services as well, for example + * collation and IDNA. + * + * @stable ICU 2.6 + */ +#ifndef UCONFIG_NO_NORMALIZATION +# define UCONFIG_NO_NORMALIZATION 0 +#endif + +/** + * \def UCONFIG_USE_ML_PHRASE_BREAKING + * This switch turns on BudouX ML phrase-based line breaking, rather than using the dictionary. + * + * @internal + */ +#ifndef UCONFIG_USE_ML_PHRASE_BREAKING +# define UCONFIG_USE_ML_PHRASE_BREAKING 0 +#endif + +#if UCONFIG_NO_NORMALIZATION + /* common library */ + /* ICU 50 CJK dictionary BreakIterator uses normalization */ +# define UCONFIG_NO_BREAK_ITERATION 1 + /* IDNA (UTS #46) is implemented via normalization */ +# define UCONFIG_NO_IDNA 1 + + /* i18n library */ +# if UCONFIG_ONLY_COLLATION +# error Contradictory collation switches in uconfig.h. +# endif +# define UCONFIG_NO_COLLATION 1 +# define UCONFIG_NO_TRANSLITERATION 1 +#endif + +/** + * \def UCONFIG_NO_BREAK_ITERATION + * This switch turns off break iteration. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_BREAK_ITERATION +# define UCONFIG_NO_BREAK_ITERATION 0 +#endif + +/** + * \def UCONFIG_NO_IDNA + * This switch turns off IDNA. + * + * @stable ICU 2.6 + */ +#ifndef UCONFIG_NO_IDNA +# define UCONFIG_NO_IDNA 0 +#endif + +/** + * \def UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE + * Determines the default UMessagePatternApostropheMode. + * See the documentation for that enum. + * + * @stable ICU 4.8 + */ +#ifndef UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE +# define UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE UMSGPAT_APOS_DOUBLE_OPTIONAL +#endif + +/** + * \def UCONFIG_USE_WINDOWS_LCID_MAPPING_API + * On platforms where U_PLATFORM_HAS_WIN32_API is true, this switch determines + * if the Windows platform APIs are used for LCID<->Locale Name conversions. + * Otherwise, only the built-in ICU tables are used. + * + * @internal ICU 64 + */ +#ifndef UCONFIG_USE_WINDOWS_LCID_MAPPING_API +# define UCONFIG_USE_WINDOWS_LCID_MAPPING_API 1 +#endif + +/* i18n library switches ---------------------------------------------------- */ + +/** + * \def UCONFIG_NO_COLLATION + * This switch turns off collation and collation-based string search. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_COLLATION +# define UCONFIG_NO_COLLATION 0 +#endif + +/** + * \def UCONFIG_NO_FORMATTING + * This switch turns off formatting and calendar/timezone services. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_FORMATTING +# define UCONFIG_NO_FORMATTING 0 +#endif + +/** + * \def UCONFIG_NO_TRANSLITERATION + * This switch turns off transliteration. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_TRANSLITERATION +# define UCONFIG_NO_TRANSLITERATION 0 +#endif + +/** + * \def UCONFIG_NO_REGULAR_EXPRESSIONS + * This switch turns off regular expressions. + * + * @stable ICU 2.4 + */ +#ifndef UCONFIG_NO_REGULAR_EXPRESSIONS +# define UCONFIG_NO_REGULAR_EXPRESSIONS 0 +#endif + +/** + * \def UCONFIG_NO_SERVICE + * This switch turns off service registration. + * + * @stable ICU 3.2 + */ +#ifndef UCONFIG_NO_SERVICE +# define UCONFIG_NO_SERVICE 0 +#endif + +/** + * \def UCONFIG_HAVE_PARSEALLINPUT + * This switch turns on the "parse all input" attribute. Binary incompatible. + * + * @internal + */ +#ifndef UCONFIG_HAVE_PARSEALLINPUT +# define UCONFIG_HAVE_PARSEALLINPUT 1 +#endif + +/** + * \def UCONFIG_NO_FILTERED_BREAK_ITERATION + * This switch turns off filtered break iteration code. + * + * @internal + */ +#ifndef UCONFIG_NO_FILTERED_BREAK_ITERATION +# define UCONFIG_NO_FILTERED_BREAK_ITERATION 0 +#endif + +#endif // __UCONFIG_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucpmap.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucpmap.h new file mode 100644 index 0000000000000000000000000000000000000000..a740bd160fc155367d54439eccc8af02fb62d885 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucpmap.h @@ -0,0 +1,158 @@ +// © 2018 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// ucpmap.h +// created: 2018sep03 Markus W. Scherer + +#ifndef __UCPMAP_H__ +#define __UCPMAP_H__ + +#include "unicode/utypes.h" + +U_CDECL_BEGIN + +/** + * \file + * \brief C API: This file defines an abstract map from Unicode code points to integer values. + * + * @see UCPMap + * @see UCPTrie + * @see UMutableCPTrie + */ + +/** + * Abstract map from Unicode code points (U+0000..U+10FFFF) to integer values. + * + * @see UCPTrie + * @see UMutableCPTrie + * @stable ICU 63 + */ +typedef struct UCPMap UCPMap; + +/** + * Selectors for how ucpmap_getRange() etc. should report value ranges overlapping with surrogates. + * Most users should use UCPMAP_RANGE_NORMAL. + * + * @see ucpmap_getRange + * @see ucptrie_getRange + * @see umutablecptrie_getRange + * @stable ICU 63 + */ +enum UCPMapRangeOption { + /** + * ucpmap_getRange() enumerates all same-value ranges as stored in the map. + * Most users should use this option. + * @stable ICU 63 + */ + UCPMAP_RANGE_NORMAL, + /** + * ucpmap_getRange() enumerates all same-value ranges as stored in the map, + * except that lead surrogates (U+D800..U+DBFF) are treated as having the + * surrogateValue, which is passed to getRange() as a separate parameter. + * The surrogateValue is not transformed via filter(). + * See U_IS_LEAD(c). + * + * Most users should use UCPMAP_RANGE_NORMAL instead. + * + * This option is useful for maps that map surrogate code *units* to + * special values optimized for UTF-16 string processing + * or for special error behavior for unpaired surrogates, + * but those values are not to be associated with the lead surrogate code *points*. + * @stable ICU 63 + */ + UCPMAP_RANGE_FIXED_LEAD_SURROGATES, + /** + * ucpmap_getRange() enumerates all same-value ranges as stored in the map, + * except that all surrogates (U+D800..U+DFFF) are treated as having the + * surrogateValue, which is passed to getRange() as a separate parameter. + * The surrogateValue is not transformed via filter(). + * See U_IS_SURROGATE(c). + * + * Most users should use UCPMAP_RANGE_NORMAL instead. + * + * This option is useful for maps that map surrogate code *units* to + * special values optimized for UTF-16 string processing + * or for special error behavior for unpaired surrogates, + * but those values are not to be associated with the lead surrogate code *points*. + * @stable ICU 63 + */ + UCPMAP_RANGE_FIXED_ALL_SURROGATES +}; +#ifndef U_IN_DOXYGEN +typedef enum UCPMapRangeOption UCPMapRangeOption; +#endif + +/** + * Returns the value for a code point as stored in the map, with range checking. + * Returns an implementation-defined error value if c is not in the range 0..U+10FFFF. + * + * @param map the map + * @param c the code point + * @return the map value, + * or an implementation-defined error value if the code point is not in the range 0..U+10FFFF + * @stable ICU 63 + */ +U_CAPI uint32_t U_EXPORT2 +ucpmap_get(const UCPMap *map, UChar32 c); + +/** + * Callback function type: Modifies a map value. + * Optionally called by ucpmap_getRange()/ucptrie_getRange()/umutablecptrie_getRange(). + * The modified value will be returned by the getRange function. + * + * Can be used to ignore some of the value bits, + * make a filter for one of several values, + * return a value index computed from the map value, etc. + * + * @param context an opaque pointer, as passed into the getRange function + * @param value a value from the map + * @return the modified value + * @stable ICU 63 + */ +typedef uint32_t U_CALLCONV +UCPMapValueFilter(const void *context, uint32_t value); + +/** + * Returns the last code point such that all those from start to there have the same value. + * Can be used to efficiently iterate over all same-value ranges in a map. + * (This is normally faster than iterating over code points and get()ting each value, + * but much slower than a data structure that stores ranges directly.) + * + * If the UCPMapValueFilter function pointer is not NULL, then + * the value to be delivered is passed through that function, and the return value is the end + * of the range where all values are modified to the same actual value. + * The value is unchanged if that function pointer is NULL. + * + * Example: + * \code + * UChar32 start = 0, end; + * uint32_t value; + * while ((end = ucpmap_getRange(map, start, UCPMAP_RANGE_NORMAL, 0, + * NULL, NULL, &value)) >= 0) { + * // Work with the range start..end and its value. + * start = end + 1; + * } + * \endcode + * + * @param map the map + * @param start range start + * @param option defines whether surrogates are treated normally, + * or as having the surrogateValue; usually UCPMAP_RANGE_NORMAL + * @param surrogateValue value for surrogates; ignored if option==UCPMAP_RANGE_NORMAL + * @param filter a pointer to a function that may modify the map data value, + * or NULL if the values from the map are to be used unmodified + * @param context an opaque pointer that is passed on to the filter function + * @param pValue if not NULL, receives the value that every code point start..end has; + * may have been modified by filter(context, map value) + * if that function pointer is not NULL + * @return the range end code point, or -1 if start is not a valid code point + * @stable ICU 63 + */ +U_CAPI UChar32 U_EXPORT2 +ucpmap_getRange(const UCPMap *map, UChar32 start, + UCPMapRangeOption option, uint32_t surrogateValue, + UCPMapValueFilter *filter, const void *context, uint32_t *pValue); + +U_CDECL_END + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucptrie.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucptrie.h new file mode 100644 index 0000000000000000000000000000000000000000..dadef79c5120495be7e87ba95a0da149b9605f90 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucptrie.h @@ -0,0 +1,645 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// ucptrie.h (modified from utrie2.h) +// created: 2017dec29 Markus W. Scherer + +#ifndef __UCPTRIE_H__ +#define __UCPTRIE_H__ + +#include "unicode/utypes.h" +#include "unicode/ucpmap.h" +#include "unicode/utf8.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +U_CDECL_BEGIN + +/** + * \file + * \brief C API: This file defines an immutable Unicode code point trie. + * + * @see UCPTrie + * @see UMutableCPTrie + */ + +#ifndef U_IN_DOXYGEN +/** @internal */ +typedef union UCPTrieData { + /** @internal */ + const void *ptr0; + /** @internal */ + const uint16_t *ptr16; + /** @internal */ + const uint32_t *ptr32; + /** @internal */ + const uint8_t *ptr8; +} UCPTrieData; +#endif + +/** + * Immutable Unicode code point trie structure. + * Fast, reasonably compact, map from Unicode code points (U+0000..U+10FFFF) to integer values. + * For details see https://icu.unicode.org/design/struct/utrie + * + * Do not access UCPTrie fields directly; use public functions and macros. + * Functions are easy to use: They support all trie types and value widths. + * + * When performance is really important, macros provide faster access. + * Most macros are specific to either "fast" or "small" tries, see UCPTrieType. + * There are "fast" macros for special optimized use cases. + * + * The macros will return bogus values, or may crash, if used on the wrong type or value width. + * + * @see UMutableCPTrie + * @stable ICU 63 + */ +struct UCPTrie { +#ifndef U_IN_DOXYGEN + /** @internal */ + const uint16_t *index; + /** @internal */ + UCPTrieData data; + + /** @internal */ + int32_t indexLength; + /** @internal */ + int32_t dataLength; + /** Start of the last range which ends at U+10FFFF. @internal */ + UChar32 highStart; + /** highStart>>12 @internal */ + uint16_t shifted12HighStart; + + /** @internal */ + int8_t type; // UCPTrieType + /** @internal */ + int8_t valueWidth; // UCPTrieValueWidth + + /** padding/reserved @internal */ + uint32_t reserved32; + /** padding/reserved @internal */ + uint16_t reserved16; + + /** + * Internal index-3 null block offset. + * Set to an impossibly high value (e.g., 0xffff) if there is no dedicated index-3 null block. + * @internal + */ + uint16_t index3NullOffset; + /** + * Internal data null block offset, not shifted. + * Set to an impossibly high value (e.g., 0xfffff) if there is no dedicated data null block. + * @internal + */ + int32_t dataNullOffset; + /** @internal */ + uint32_t nullValue; + +#ifdef UCPTRIE_DEBUG + /** @internal */ + const char *name; +#endif +#endif +}; +#ifndef U_IN_DOXYGEN +typedef struct UCPTrie UCPTrie; +#endif + +/** + * Selectors for the type of a UCPTrie. + * Different trade-offs for size vs. speed. + * + * @see umutablecptrie_buildImmutable + * @see ucptrie_openFromBinary + * @see ucptrie_getType + * @stable ICU 63 + */ +enum UCPTrieType { + /** + * For ucptrie_openFromBinary() to accept any type. + * ucptrie_getType() will return the actual type. + * @stable ICU 63 + */ + UCPTRIE_TYPE_ANY = -1, + /** + * Fast/simple/larger BMP data structure. Use functions and "fast" macros. + * @stable ICU 63 + */ + UCPTRIE_TYPE_FAST, + /** + * Small/slower BMP data structure. Use functions and "small" macros. + * @stable ICU 63 + */ + UCPTRIE_TYPE_SMALL +}; +#ifndef U_IN_DOXYGEN +typedef enum UCPTrieType UCPTrieType; +#endif + +/** + * Selectors for the number of bits in a UCPTrie data value. + * + * @see umutablecptrie_buildImmutable + * @see ucptrie_openFromBinary + * @see ucptrie_getValueWidth + * @stable ICU 63 + */ +enum UCPTrieValueWidth { + /** + * For ucptrie_openFromBinary() to accept any data value width. + * ucptrie_getValueWidth() will return the actual data value width. + * @stable ICU 63 + */ + UCPTRIE_VALUE_BITS_ANY = -1, + /** + * The trie stores 16 bits per data value. + * It returns them as unsigned values 0..0xffff=65535. + * @stable ICU 63 + */ + UCPTRIE_VALUE_BITS_16, + /** + * The trie stores 32 bits per data value. + * @stable ICU 63 + */ + UCPTRIE_VALUE_BITS_32, + /** + * The trie stores 8 bits per data value. + * It returns them as unsigned values 0..0xff=255. + * @stable ICU 63 + */ + UCPTRIE_VALUE_BITS_8 +}; +#ifndef U_IN_DOXYGEN +typedef enum UCPTrieValueWidth UCPTrieValueWidth; +#endif + +/** + * Opens a trie from its binary form, stored in 32-bit-aligned memory. + * Inverse of ucptrie_toBinary(). + * + * The memory must remain valid and unchanged as long as the trie is used. + * You must ucptrie_close() the trie once you are done using it. + * + * @param type selects the trie type; results in an + * U_INVALID_FORMAT_ERROR if it does not match the binary data; + * use UCPTRIE_TYPE_ANY to accept any type + * @param valueWidth selects the number of bits in a data value; results in an + * U_INVALID_FORMAT_ERROR if it does not match the binary data; + * use UCPTRIE_VALUE_BITS_ANY to accept any data value width + * @param data a pointer to 32-bit-aligned memory containing the binary data of a UCPTrie + * @param length the number of bytes available at data; + * can be more than necessary + * @param pActualLength receives the actual number of bytes at data taken up by the trie data; + * can be NULL + * @param pErrorCode an in/out ICU UErrorCode + * @return the trie + * + * @see umutablecptrie_open + * @see umutablecptrie_buildImmutable + * @see ucptrie_toBinary + * @stable ICU 63 + */ +U_CAPI UCPTrie * U_EXPORT2 +ucptrie_openFromBinary(UCPTrieType type, UCPTrieValueWidth valueWidth, + const void *data, int32_t length, int32_t *pActualLength, + UErrorCode *pErrorCode); + +/** + * Closes a trie and releases associated memory. + * + * @param trie the trie + * @stable ICU 63 + */ +U_CAPI void U_EXPORT2 +ucptrie_close(UCPTrie *trie); + +/** + * Returns the trie type. + * + * @param trie the trie + * @return the trie type + * @see ucptrie_openFromBinary + * @see UCPTRIE_TYPE_ANY + * @stable ICU 63 + */ +U_CAPI UCPTrieType U_EXPORT2 +ucptrie_getType(const UCPTrie *trie); + +/** + * Returns the number of bits in a trie data value. + * + * @param trie the trie + * @return the number of bits in a trie data value + * @see ucptrie_openFromBinary + * @see UCPTRIE_VALUE_BITS_ANY + * @stable ICU 63 + */ +U_CAPI UCPTrieValueWidth U_EXPORT2 +ucptrie_getValueWidth(const UCPTrie *trie); + +/** + * Returns the value for a code point as stored in the trie, with range checking. + * Returns the trie error value if c is not in the range 0..U+10FFFF. + * + * Easier to use than UCPTRIE_FAST_GET() and similar macros but slower. + * Easier to use because, unlike the macros, this function works on all UCPTrie + * objects, for all types and value widths. + * + * @param trie the trie + * @param c the code point + * @return the trie value, + * or the trie error value if the code point is not in the range 0..U+10FFFF + * @stable ICU 63 + */ +U_CAPI uint32_t U_EXPORT2 +ucptrie_get(const UCPTrie *trie, UChar32 c); + +/** + * Returns the last code point such that all those from start to there have the same value. + * Can be used to efficiently iterate over all same-value ranges in a trie. + * (This is normally faster than iterating over code points and get()ting each value, + * but much slower than a data structure that stores ranges directly.) + * + * If the UCPMapValueFilter function pointer is not NULL, then + * the value to be delivered is passed through that function, and the return value is the end + * of the range where all values are modified to the same actual value. + * The value is unchanged if that function pointer is NULL. + * + * Example: + * \code + * UChar32 start = 0, end; + * uint32_t value; + * while ((end = ucptrie_getRange(trie, start, UCPMAP_RANGE_NORMAL, 0, + * NULL, NULL, &value)) >= 0) { + * // Work with the range start..end and its value. + * start = end + 1; + * } + * \endcode + * + * @param trie the trie + * @param start range start + * @param option defines whether surrogates are treated normally, + * or as having the surrogateValue; usually UCPMAP_RANGE_NORMAL + * @param surrogateValue value for surrogates; ignored if option==UCPMAP_RANGE_NORMAL + * @param filter a pointer to a function that may modify the trie data value, + * or NULL if the values from the trie are to be used unmodified + * @param context an opaque pointer that is passed on to the filter function + * @param pValue if not NULL, receives the value that every code point start..end has; + * may have been modified by filter(context, trie value) + * if that function pointer is not NULL + * @return the range end code point, or -1 if start is not a valid code point + * @stable ICU 63 + */ +U_CAPI UChar32 U_EXPORT2 +ucptrie_getRange(const UCPTrie *trie, UChar32 start, + UCPMapRangeOption option, uint32_t surrogateValue, + UCPMapValueFilter *filter, const void *context, uint32_t *pValue); + +/** + * Writes a memory-mappable form of the trie into 32-bit aligned memory. + * Inverse of ucptrie_openFromBinary(). + * + * @param trie the trie + * @param data a pointer to 32-bit-aligned memory to be filled with the trie data; + * can be NULL if capacity==0 + * @param capacity the number of bytes available at data, or 0 for pure preflighting + * @param pErrorCode an in/out ICU UErrorCode; + * U_BUFFER_OVERFLOW_ERROR if the capacity is too small + * @return the number of bytes written or (if buffer overflow) needed for the trie + * + * @see ucptrie_openFromBinary() + * @stable ICU 63 + */ +U_CAPI int32_t U_EXPORT2 +ucptrie_toBinary(const UCPTrie *trie, void *data, int32_t capacity, UErrorCode *pErrorCode); + +/** + * Macro parameter value for a trie with 16-bit data values. + * Use the name of this macro as a "dataAccess" parameter in other macros. + * Do not use this macro in any other way. + * + * @see UCPTRIE_VALUE_BITS_16 + * @stable ICU 63 + */ +#define UCPTRIE_16(trie, i) ((trie)->data.ptr16[i]) + +/** + * Macro parameter value for a trie with 32-bit data values. + * Use the name of this macro as a "dataAccess" parameter in other macros. + * Do not use this macro in any other way. + * + * @see UCPTRIE_VALUE_BITS_32 + * @stable ICU 63 + */ +#define UCPTRIE_32(trie, i) ((trie)->data.ptr32[i]) + +/** + * Macro parameter value for a trie with 8-bit data values. + * Use the name of this macro as a "dataAccess" parameter in other macros. + * Do not use this macro in any other way. + * + * @see UCPTRIE_VALUE_BITS_8 + * @stable ICU 63 + */ +#define UCPTRIE_8(trie, i) ((trie)->data.ptr8[i]) + +/** + * Returns a trie value for a code point, with range checking. + * Returns the trie error value if c is not in the range 0..U+10FFFF. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param c (UChar32, in) the input code point + * @return The code point's trie value. + * @stable ICU 63 + */ +#define UCPTRIE_FAST_GET(trie, dataAccess, c) dataAccess(trie, _UCPTRIE_CP_INDEX(trie, 0xffff, c)) + +/** + * Returns a 16-bit trie value for a code point, with range checking. + * Returns the trie error value if c is not in the range U+0000..U+10FFFF. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_SMALL + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param c (UChar32, in) the input code point + * @return The code point's trie value. + * @stable ICU 63 + */ +#define UCPTRIE_SMALL_GET(trie, dataAccess, c) \ + dataAccess(trie, _UCPTRIE_CP_INDEX(trie, UCPTRIE_SMALL_MAX, c)) + +/** + * UTF-16: Reads the next code point (UChar32 c, out), post-increments src, + * and gets a value from the trie. + * Sets the trie error value if c is an unpaired surrogate. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param src (const UChar *, in/out) the source text pointer + * @param limit (const UChar *, in) the limit pointer for the text, or NULL if NUL-terminated + * @param c (UChar32, out) variable for the code point + * @param result (out) variable for the trie lookup result + * @stable ICU 63 + */ +#define UCPTRIE_FAST_U16_NEXT(trie, dataAccess, src, limit, c, result) UPRV_BLOCK_MACRO_BEGIN { \ + (c) = *(src)++; \ + int32_t __index; \ + if (!U16_IS_SURROGATE(c)) { \ + __index = _UCPTRIE_FAST_INDEX(trie, c); \ + } else { \ + uint16_t __c2; \ + if (U16_IS_SURROGATE_LEAD(c) && (src) != (limit) && U16_IS_TRAIL(__c2 = *(src))) { \ + ++(src); \ + (c) = U16_GET_SUPPLEMENTARY((c), __c2); \ + __index = _UCPTRIE_SMALL_INDEX(trie, c); \ + } else { \ + __index = (trie)->dataLength - UCPTRIE_ERROR_VALUE_NEG_DATA_OFFSET; \ + } \ + } \ + (result) = dataAccess(trie, __index); \ +} UPRV_BLOCK_MACRO_END + +/** + * UTF-16: Reads the previous code point (UChar32 c, out), pre-decrements src, + * and gets a value from the trie. + * Sets the trie error value if c is an unpaired surrogate. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param start (const UChar *, in) the start pointer for the text + * @param src (const UChar *, in/out) the source text pointer + * @param c (UChar32, out) variable for the code point + * @param result (out) variable for the trie lookup result + * @stable ICU 63 + */ +#define UCPTRIE_FAST_U16_PREV(trie, dataAccess, start, src, c, result) UPRV_BLOCK_MACRO_BEGIN { \ + (c) = *--(src); \ + int32_t __index; \ + if (!U16_IS_SURROGATE(c)) { \ + __index = _UCPTRIE_FAST_INDEX(trie, c); \ + } else { \ + uint16_t __c2; \ + if (U16_IS_SURROGATE_TRAIL(c) && (src) != (start) && U16_IS_LEAD(__c2 = *((src) - 1))) { \ + --(src); \ + (c) = U16_GET_SUPPLEMENTARY(__c2, (c)); \ + __index = _UCPTRIE_SMALL_INDEX(trie, c); \ + } else { \ + __index = (trie)->dataLength - UCPTRIE_ERROR_VALUE_NEG_DATA_OFFSET; \ + } \ + } \ + (result) = dataAccess(trie, __index); \ +} UPRV_BLOCK_MACRO_END + +/** + * UTF-8: Post-increments src and gets a value from the trie. + * Sets the trie error value for an ill-formed byte sequence. + * + * Unlike UCPTRIE_FAST_U16_NEXT() this UTF-8 macro does not provide the code point + * because it would be more work to do so and is often not needed. + * If the trie value differs from the error value, then the byte sequence is well-formed, + * and the code point can be assembled without revalidation. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param src (const char *, in/out) the source text pointer + * @param limit (const char *, in) the limit pointer for the text (must not be NULL) + * @param result (out) variable for the trie lookup result + * @stable ICU 63 + */ +#define UCPTRIE_FAST_U8_NEXT(trie, dataAccess, src, limit, result) UPRV_BLOCK_MACRO_BEGIN { \ + int32_t __lead = (uint8_t)*(src)++; \ + if (!U8_IS_SINGLE(__lead)) { \ + uint8_t __t1, __t2, __t3; \ + if ((src) != (limit) && \ + (__lead >= 0xe0 ? \ + __lead < 0xf0 ? /* U+0800..U+FFFF except surrogates */ \ + U8_LEAD3_T1_BITS[__lead &= 0xf] & (1 << ((__t1 = *(src)) >> 5)) && \ + ++(src) != (limit) && (__t2 = *(src) - 0x80) <= 0x3f && \ + (__lead = ((int32_t)(trie)->index[(__lead << 6) + (__t1 & 0x3f)]) + __t2, 1) \ + : /* U+10000..U+10FFFF */ \ + (__lead -= 0xf0) <= 4 && \ + U8_LEAD4_T1_BITS[(__t1 = *(src)) >> 4] & (1 << __lead) && \ + (__lead = (__lead << 6) | (__t1 & 0x3f), ++(src) != (limit)) && \ + (__t2 = *(src) - 0x80) <= 0x3f && \ + ++(src) != (limit) && (__t3 = *(src) - 0x80) <= 0x3f && \ + (__lead = __lead >= (trie)->shifted12HighStart ? \ + (trie)->dataLength - UCPTRIE_HIGH_VALUE_NEG_DATA_OFFSET : \ + ucptrie_internalSmallU8Index((trie), __lead, __t2, __t3), 1) \ + : /* U+0080..U+07FF */ \ + __lead >= 0xc2 && (__t1 = *(src) - 0x80) <= 0x3f && \ + (__lead = (int32_t)(trie)->index[__lead & 0x1f] + __t1, 1))) { \ + ++(src); \ + } else { \ + __lead = (trie)->dataLength - UCPTRIE_ERROR_VALUE_NEG_DATA_OFFSET; /* ill-formed*/ \ + } \ + } \ + (result) = dataAccess(trie, __lead); \ +} UPRV_BLOCK_MACRO_END + +/** + * UTF-8: Pre-decrements src and gets a value from the trie. + * Sets the trie error value for an ill-formed byte sequence. + * + * Unlike UCPTRIE_FAST_U16_PREV() this UTF-8 macro does not provide the code point + * because it would be more work to do so and is often not needed. + * If the trie value differs from the error value, then the byte sequence is well-formed, + * and the code point can be assembled without revalidation. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param start (const char *, in) the start pointer for the text + * @param src (const char *, in/out) the source text pointer + * @param result (out) variable for the trie lookup result + * @stable ICU 63 + */ +#define UCPTRIE_FAST_U8_PREV(trie, dataAccess, start, src, result) UPRV_BLOCK_MACRO_BEGIN { \ + int32_t __index = (uint8_t)*--(src); \ + if (!U8_IS_SINGLE(__index)) { \ + __index = ucptrie_internalU8PrevIndex((trie), __index, (const uint8_t *)(start), \ + (const uint8_t *)(src)); \ + (src) -= __index & 7; \ + __index >>= 3; \ + } \ + (result) = dataAccess(trie, __index); \ +} UPRV_BLOCK_MACRO_END + +/** + * Returns a trie value for an ASCII code point, without range checking. + * + * @param trie (const UCPTrie *, in) the trie (of either fast or small type) + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param c (UChar32, in) the input code point; must be U+0000..U+007F + * @return The ASCII code point's trie value. + * @stable ICU 63 + */ +#define UCPTRIE_ASCII_GET(trie, dataAccess, c) dataAccess(trie, c) + +/** + * Returns a trie value for a BMP code point (U+0000..U+FFFF), without range checking. + * Can be used to look up a value for a UTF-16 code unit if other parts of + * the string processing check for surrogates. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param c (UChar32, in) the input code point, must be U+0000..U+FFFF + * @return The BMP code point's trie value. + * @stable ICU 63 + */ +#define UCPTRIE_FAST_BMP_GET(trie, dataAccess, c) dataAccess(trie, _UCPTRIE_FAST_INDEX(trie, c)) + +/** + * Returns a trie value for a supplementary code point (U+10000..U+10FFFF), + * without range checking. + * + * @param trie (const UCPTrie *, in) the trie; must have type UCPTRIE_TYPE_FAST + * @param dataAccess UCPTRIE_16, UCPTRIE_32, or UCPTRIE_8 according to the trie’s value width + * @param c (UChar32, in) the input code point, must be U+10000..U+10FFFF + * @return The supplementary code point's trie value. + * @stable ICU 63 + */ +#define UCPTRIE_FAST_SUPP_GET(trie, dataAccess, c) dataAccess(trie, _UCPTRIE_SMALL_INDEX(trie, c)) + +/* Internal definitions ----------------------------------------------------- */ + +#ifndef U_IN_DOXYGEN + +/** + * Internal implementation constants. + * These are needed for the API macros, but users should not use these directly. + * @internal + */ +enum { + /** @internal */ + UCPTRIE_FAST_SHIFT = 6, + + /** Number of entries in a data block for code points below the fast limit. 64=0x40 @internal */ + UCPTRIE_FAST_DATA_BLOCK_LENGTH = 1 << UCPTRIE_FAST_SHIFT, + + /** Mask for getting the lower bits for the in-fast-data-block offset. @internal */ + UCPTRIE_FAST_DATA_MASK = UCPTRIE_FAST_DATA_BLOCK_LENGTH - 1, + + /** @internal */ + UCPTRIE_SMALL_MAX = 0xfff, + + /** + * Offset from dataLength (to be subtracted) for fetching the + * value returned for out-of-range code points and ill-formed UTF-8/16. + * @internal + */ + UCPTRIE_ERROR_VALUE_NEG_DATA_OFFSET = 1, + /** + * Offset from dataLength (to be subtracted) for fetching the + * value returned for code points highStart..U+10FFFF. + * @internal + */ + UCPTRIE_HIGH_VALUE_NEG_DATA_OFFSET = 2 +}; + +/* Internal functions and macros -------------------------------------------- */ +// Do not conditionalize with #ifndef U_HIDE_INTERNAL_API, needed for public API + +/** @internal */ +U_CAPI int32_t U_EXPORT2 +ucptrie_internalSmallIndex(const UCPTrie *trie, UChar32 c); + +/** @internal */ +U_CAPI int32_t U_EXPORT2 +ucptrie_internalSmallU8Index(const UCPTrie *trie, int32_t lt1, uint8_t t2, uint8_t t3); + +/** + * Internal function for part of the UCPTRIE_FAST_U8_PREVxx() macro implementations. + * Do not call directly. + * @internal + */ +U_CAPI int32_t U_EXPORT2 +ucptrie_internalU8PrevIndex(const UCPTrie *trie, UChar32 c, + const uint8_t *start, const uint8_t *src); + +/** Internal trie getter for a code point below the fast limit. Returns the data index. @internal */ +#define _UCPTRIE_FAST_INDEX(trie, c) \ + ((int32_t)(trie)->index[(c) >> UCPTRIE_FAST_SHIFT] + ((c) & UCPTRIE_FAST_DATA_MASK)) + +/** Internal trie getter for a code point at or above the fast limit. Returns the data index. @internal */ +#define _UCPTRIE_SMALL_INDEX(trie, c) \ + ((c) >= (trie)->highStart ? \ + (trie)->dataLength - UCPTRIE_HIGH_VALUE_NEG_DATA_OFFSET : \ + ucptrie_internalSmallIndex(trie, c)) + +/** + * Internal trie getter for a code point, with checking that c is in U+0000..10FFFF. + * Returns the data index. + * @internal + */ +#define _UCPTRIE_CP_INDEX(trie, fastMax, c) \ + ((uint32_t)(c) <= (uint32_t)(fastMax) ? \ + _UCPTRIE_FAST_INDEX(trie, c) : \ + (uint32_t)(c) <= 0x10ffff ? \ + _UCPTRIE_SMALL_INDEX(trie, c) : \ + (trie)->dataLength - UCPTRIE_ERROR_VALUE_NEG_DATA_OFFSET) + +U_CDECL_END + +#endif // U_IN_DOXYGEN + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUCPTriePointer + * "Smart pointer" class, closes a UCPTrie via ucptrie_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 63 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUCPTriePointer, UCPTrie, ucptrie_close); + +U_NAMESPACE_END + +#endif // U_SHOW_CPLUSPLUS_API + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucsdet.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucsdet.h new file mode 100644 index 0000000000000000000000000000000000000000..8c62fde9d2eeedc8bab818d087d2b55c2de481db --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucsdet.h @@ -0,0 +1,422 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ********************************************************************** + * Copyright (C) 2005-2013, International Business Machines + * Corporation and others. All Rights Reserved. + ********************************************************************** + * file name: ucsdet.h + * encoding: UTF-8 + * indentation:4 + * + * created on: 2005Aug04 + * created by: Andy Heninger + * + * ICU Character Set Detection, API for C + * + * Draft version 18 Oct 2005 + * + */ + +#ifndef __UCSDET_H +#define __UCSDET_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_CONVERSION + +#include "unicode/uenum.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Charset Detection API + * + * This API provides a facility for detecting the + * charset or encoding of character data in an unknown text format. + * The input data can be from an array of bytes. + *

+ * Character set detection is at best an imprecise operation. The detection + * process will attempt to identify the charset that best matches the characteristics + * of the byte data, but the process is partly statistical in nature, and + * the results can not be guaranteed to always be correct. + *

+ * For best accuracy in charset detection, the input data should be primarily + * in a single language, and a minimum of a few hundred bytes worth of plain text + * in the language are needed. The detection process will attempt to + * ignore html or xml style markup that could otherwise obscure the content. + *

+ * An alternative to the ICU Charset Detector is the + * Compact Encoding Detector, https://github.com/google/compact_enc_det. + * It often gives more accurate results, especially with short input samples. + */ + + +struct UCharsetDetector; +/** + * Structure representing a charset detector + * @stable ICU 3.6 + */ +typedef struct UCharsetDetector UCharsetDetector; + +struct UCharsetMatch; +/** + * Opaque structure representing a match that was identified + * from a charset detection operation. + * @stable ICU 3.6 + */ +typedef struct UCharsetMatch UCharsetMatch; + +/** + * Open a charset detector. + * + * @param status Any error conditions occurring during the open + * operation are reported back in this variable. + * @return the newly opened charset detector. + * @stable ICU 3.6 + */ +U_CAPI UCharsetDetector * U_EXPORT2 +ucsdet_open(UErrorCode *status); + +/** + * Close a charset detector. All storage and any other resources + * owned by this charset detector will be released. Failure to + * close a charset detector when finished with it can result in + * memory leaks in the application. + * + * @param ucsd The charset detector to be closed. + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ucsdet_close(UCharsetDetector *ucsd); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUCharsetDetectorPointer + * "Smart pointer" class, closes a UCharsetDetector via ucsdet_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUCharsetDetectorPointer, UCharsetDetector, ucsdet_close); + +U_NAMESPACE_END + +#endif + +/** + * Set the input byte data whose charset is to detected. + * + * Ownership of the input text byte array remains with the caller. + * The input string must not be altered or deleted until the charset + * detector is either closed or reset to refer to different input text. + * + * @param ucsd the charset detector to be used. + * @param textIn the input text of unknown encoding. . + * @param len the length of the input text, or -1 if the text + * is NUL terminated. + * @param status any error conditions are reported back in this variable. + * + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ucsdet_setText(UCharsetDetector *ucsd, const char *textIn, int32_t len, UErrorCode *status); + + +/** Set the declared encoding for charset detection. + * The declared encoding of an input text is an encoding obtained + * by the user from an http header or xml declaration or similar source that + * can be provided as an additional hint to the charset detector. + * + * How and whether the declared encoding will be used during the + * detection process is TBD. + * + * @param ucsd the charset detector to be used. + * @param encoding an encoding for the current data obtained from + * a header or declaration or other source outside + * of the byte data itself. + * @param length the length of the encoding name, or -1 if the name string + * is NUL terminated. + * @param status any error conditions are reported back in this variable. + * + * @stable ICU 3.6 + */ +U_CAPI void U_EXPORT2 +ucsdet_setDeclaredEncoding(UCharsetDetector *ucsd, const char *encoding, int32_t length, UErrorCode *status); + + +/** + * Return the charset that best matches the supplied input data. + * + * Note though, that because the detection + * only looks at the start of the input data, + * there is a possibility that the returned charset will fail to handle + * the full set of input data. + *

+ * The returned UCharsetMatch object is owned by the UCharsetDetector. + * It will remain valid until the detector input is reset, or until + * the detector is closed. + *

+ * The function will fail if + *

    + *
  • no charset appears to match the data.
  • + *
  • no input text has been provided
  • + *
+ * + * @param ucsd the charset detector to be used. + * @param status any error conditions are reported back in this variable. + * @return a UCharsetMatch representing the best matching charset, + * or NULL if no charset matches the byte data. + * + * @stable ICU 3.6 + */ +U_CAPI const UCharsetMatch * U_EXPORT2 +ucsdet_detect(UCharsetDetector *ucsd, UErrorCode *status); + + +/** + * Find all charset matches that appear to be consistent with the input, + * returning an array of results. The results are ordered with the + * best quality match first. + * + * Because the detection only looks at a limited amount of the + * input byte data, some of the returned charsets may fail to handle + * the all of input data. + *

+ * The returned UCharsetMatch objects are owned by the UCharsetDetector. + * They will remain valid until the detector is closed or modified + * + *

+ * Return an error if + *

    + *
  • no charsets appear to match the input data.
  • + *
  • no input text has been provided
  • + *
+ * + * @param ucsd the charset detector to be used. + * @param matchesFound pointer to a variable that will be set to the + * number of charsets identified that are consistent with + * the input data. Output only. + * @param status any error conditions are reported back in this variable. + * @return A pointer to an array of pointers to UCharSetMatch objects. + * This array, and the UCharSetMatch instances to which it refers, + * are owned by the UCharsetDetector, and will remain valid until + * the detector is closed or modified. + * @stable ICU 3.6 + */ +U_CAPI const UCharsetMatch ** U_EXPORT2 +ucsdet_detectAll(UCharsetDetector *ucsd, int32_t *matchesFound, UErrorCode *status); + + + +/** + * Get the name of the charset represented by a UCharsetMatch. + * + * The storage for the returned name string is owned by the + * UCharsetMatch, and will remain valid while the UCharsetMatch + * is valid. + * + * The name returned is suitable for use with the ICU conversion APIs. + * + * @param ucsm The charset match object. + * @param status Any error conditions are reported back in this variable. + * @return The name of the matching charset. + * + * @stable ICU 3.6 + */ +U_CAPI const char * U_EXPORT2 +ucsdet_getName(const UCharsetMatch *ucsm, UErrorCode *status); + +/** + * Get a confidence number for the quality of the match of the byte + * data with the charset. Confidence numbers range from zero to 100, + * with 100 representing complete confidence and zero representing + * no confidence. + * + * The confidence values are somewhat arbitrary. They define an + * an ordering within the results for any single detection operation + * but are not generally comparable between the results for different input. + * + * A confidence value of ten does have a general meaning - it is used + * for charsets that can represent the input data, but for which there + * is no other indication that suggests that the charset is the correct one. + * Pure 7 bit ASCII data, for example, is compatible with a + * great many charsets, most of which will appear as possible matches + * with a confidence of 10. + * + * @param ucsm The charset match object. + * @param status Any error conditions are reported back in this variable. + * @return A confidence number for the charset match. + * + * @stable ICU 3.6 + */ +U_CAPI int32_t U_EXPORT2 +ucsdet_getConfidence(const UCharsetMatch *ucsm, UErrorCode *status); + +/** + * Get the RFC 3066 code for the language of the input data. + * + * The Charset Detection service is intended primarily for detecting + * charsets, not language. For some, but not all, charsets, a language is + * identified as a byproduct of the detection process, and that is what + * is returned by this function. + * + * CAUTION: + * 1. Language information is not available for input data encoded in + * all charsets. In particular, no language is identified + * for UTF-8 input data. + * + * 2. Closely related languages may sometimes be confused. + * + * If more accurate language detection is required, a linguistic + * analysis package should be used. + * + * The storage for the returned name string is owned by the + * UCharsetMatch, and will remain valid while the UCharsetMatch + * is valid. + * + * @param ucsm The charset match object. + * @param status Any error conditions are reported back in this variable. + * @return The RFC 3066 code for the language of the input data, or + * an empty string if the language could not be determined. + * + * @stable ICU 3.6 + */ +U_CAPI const char * U_EXPORT2 +ucsdet_getLanguage(const UCharsetMatch *ucsm, UErrorCode *status); + + +/** + * Get the entire input text as a UChar string, placing it into + * a caller-supplied buffer. A terminating + * NUL character will be appended to the buffer if space is available. + * + * The number of UChars in the output string, not including the terminating + * NUL, is returned. + * + * If the supplied buffer is smaller than required to hold the output, + * the contents of the buffer are undefined. The full output string length + * (in UChars) is returned as always, and can be used to allocate a buffer + * of the correct size. + * + * + * @param ucsm The charset match object. + * @param buf A UChar buffer to be filled with the converted text data. + * @param cap The capacity of the buffer in UChars. + * @param status Any error conditions are reported back in this variable. + * @return The number of UChars in the output string. + * + * @stable ICU 3.6 + */ +U_CAPI int32_t U_EXPORT2 +ucsdet_getUChars(const UCharsetMatch *ucsm, + UChar *buf, int32_t cap, UErrorCode *status); + + + +/** + * Get an iterator over the set of all detectable charsets - + * over the charsets that are known to the charset detection + * service. + * + * The returned UEnumeration provides access to the names of + * the charsets. + * + *

+ * The state of the Charset detector that is passed in does not + * affect the result of this function, but requiring a valid, open + * charset detector as a parameter insures that the charset detection + * service has been safely initialized and that the required detection + * data is available. + * + *

+ * Note: Multiple different charset encodings in a same family may use + * a single shared name in this implementation. For example, this method returns + * an array including "ISO-8859-1" (ISO Latin 1), but not including "windows-1252" + * (Windows Latin 1). However, actual detection result could be "windows-1252" + * when the input data matches Latin 1 code points with any points only available + * in "windows-1252". + * + * @param ucsd a Charset detector. + * @param status Any error conditions are reported back in this variable. + * @return an iterator providing access to the detectable charset names. + * @stable ICU 3.6 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucsdet_getAllDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status); + +/** + * Test whether input filtering is enabled for this charset detector. + * Input filtering removes text that appears to be HTML or xml + * markup from the input before applying the code page detection + * heuristics. + * + * @param ucsd The charset detector to check. + * @return true if filtering is enabled. + * @stable ICU 3.6 + */ + +U_CAPI UBool U_EXPORT2 +ucsdet_isInputFilterEnabled(const UCharsetDetector *ucsd); + + +/** + * Enable filtering of input text. If filtering is enabled, + * text within angle brackets ("<" and ">") will be removed + * before detection, which will remove most HTML or xml markup. + * + * @param ucsd the charset detector to be modified. + * @param filter true to enable input text filtering. + * @return The previous setting. + * + * @stable ICU 3.6 + */ +U_CAPI UBool U_EXPORT2 +ucsdet_enableInputFilter(UCharsetDetector *ucsd, UBool filter); + +#ifndef U_HIDE_INTERNAL_API +/** + * Get an iterator over the set of detectable charsets - + * over the charsets that are enabled by the specified charset detector. + * + * The returned UEnumeration provides access to the names of + * the charsets. + * + * @param ucsd a Charset detector. + * @param status Any error conditions are reported back in this variable. + * @return an iterator providing access to the detectable charset names by + * the specified charset detector. + * @internal + */ +U_CAPI UEnumeration * U_EXPORT2 +ucsdet_getDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status); + +/** + * Enable or disable individual charset encoding. + * A name of charset encoding must be included in the names returned by + * {@link #ucsdet_getAllDetectableCharsets()}. + * + * @param ucsd a Charset detector. + * @param encoding encoding the name of charset encoding. + * @param enabled true to enable, or false to disable the + * charset encoding. + * @param status receives the return status. When the name of charset encoding + * is not supported, U_ILLEGAL_ARGUMENT_ERROR is set. + * @internal + */ +U_CAPI void U_EXPORT2 +ucsdet_setDetectableCharset(UCharsetDetector *ucsd, const char *encoding, UBool enabled, UErrorCode *status); +#endif /* U_HIDE_INTERNAL_API */ + +#endif +#endif /* __UCSDET_H */ + + diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucurr.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucurr.h new file mode 100644 index 0000000000000000000000000000000000000000..5589e799904914241a4029453318cd0a1a51d4dd --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ucurr.h @@ -0,0 +1,466 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2002-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +*/ +#ifndef _UCURR_H_ +#define _UCURR_H_ + +#include "unicode/utypes.h" +#include "unicode/uenum.h" + +/** + * \file + * \brief C API: Encapsulates information about a currency. + * + * The ucurr API encapsulates information about a currency, as defined by + * ISO 4217. A currency is represented by a 3-character string + * containing its ISO 4217 code. This API can return various data + * necessary the proper display of a currency: + * + *

  • A display symbol, for a specific locale + *
  • The number of fraction digits to display + *
  • A rounding increment + *
+ * + * The DecimalFormat class uses these data to display + * currencies. + * @author Alan Liu + * @since ICU 2.2 + */ + +#if !UCONFIG_NO_FORMATTING + +/** + * Currency Usage used for Decimal Format + * @stable ICU 54 + */ +enum UCurrencyUsage { + /** + * a setting to specify currency usage which determines currency digit + * and rounding for standard usage, for example: "50.00 NT$" + * used as DEFAULT value + * @stable ICU 54 + */ + UCURR_USAGE_STANDARD=0, + /** + * a setting to specify currency usage which determines currency digit + * and rounding for cash usage, for example: "50 NT$" + * @stable ICU 54 + */ + UCURR_USAGE_CASH=1, +#ifndef U_HIDE_DEPRECATED_API + /** + * One higher than the last enum UCurrencyUsage constant. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UCURR_USAGE_COUNT=2 +#endif // U_HIDE_DEPRECATED_API +}; +/** Currency Usage used for Decimal Format */ +typedef enum UCurrencyUsage UCurrencyUsage; + +/** + * Finds a currency code for the given locale. + * @param locale the locale for which to retrieve a currency code. + * Currency can be specified by the "currency" keyword + * in which case it overrides the default currency code + * @param buff fill in buffer. Can be NULL for preflighting. + * @param buffCapacity capacity of the fill in buffer. Can be 0 for + * preflighting. If it is non-zero, the buff parameter + * must not be NULL. + * @param ec error code + * @return length of the currency string. It should always be 3. If 0, + * currency couldn't be found or the input values are + * invalid. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_forLocale(const char* locale, + UChar* buff, + int32_t buffCapacity, + UErrorCode* ec); + +/** + * Selector constants for ucurr_getName(). + * + * @see ucurr_getName + * @stable ICU 2.6 + */ +typedef enum UCurrNameStyle { + /** + * Selector for ucurr_getName indicating a symbolic name for a + * currency, such as "$" for USD. + * @stable ICU 2.6 + */ + UCURR_SYMBOL_NAME, + + /** + * Selector for ucurr_getName indicating the long name for a + * currency, such as "US Dollar" for USD. + * @stable ICU 2.6 + */ + UCURR_LONG_NAME, + + /** + * Selector for getName() indicating the narrow currency symbol. + * The narrow currency symbol is similar to the regular currency + * symbol, but it always takes the shortest form: for example, + * "$" instead of "US$" for USD in en-CA. + * + * @stable ICU 61 + */ + UCURR_NARROW_SYMBOL_NAME, + + /** + * Selector for getName() indicating the formal currency symbol. + * The formal currency symbol is similar to the regular currency + * symbol, but it always takes the form used in formal settings + * such as banking; for example, "NT$" instead of "$" for TWD in zh-TW. + * + * @stable ICU 68 + */ + UCURR_FORMAL_SYMBOL_NAME, + + /** + * Selector for getName() indicating the variant currency symbol. + * The variant symbol for a currency is an alternative symbol + * that is not necessarily as widely used as the regular symbol. + * + * @stable ICU 68 + */ + UCURR_VARIANT_SYMBOL_NAME + +} UCurrNameStyle; + +#if !UCONFIG_NO_SERVICE +/** + * @stable ICU 2.6 + */ +typedef const void* UCurrRegistryKey; + +/** + * Register an (existing) ISO 4217 currency code for the given locale. + * Only the country code and the two variants EURO and PRE_EURO are + * recognized. + * @param isoCode the three-letter ISO 4217 currency code + * @param locale the locale for which to register this currency code + * @param status the in/out status code + * @return a registry key that can be used to unregister this currency code, or NULL + * if there was an error. + * @stable ICU 2.6 + */ +U_CAPI UCurrRegistryKey U_EXPORT2 +ucurr_register(const UChar* isoCode, + const char* locale, + UErrorCode* status); +/** + * Unregister the previously-registered currency definitions using the + * URegistryKey returned from ucurr_register. Key becomes invalid after + * a successful call and should not be used again. Any currency + * that might have been hidden by the original ucurr_register call is + * restored. + * @param key the registry key returned by a previous call to ucurr_register + * @param status the in/out status code, no special meanings are assigned + * @return true if the currency for this key was successfully unregistered + * @stable ICU 2.6 + */ +U_CAPI UBool U_EXPORT2 +ucurr_unregister(UCurrRegistryKey key, UErrorCode* status); +#endif /* UCONFIG_NO_SERVICE */ + +/** + * Returns the display name for the given currency in the + * given locale. For example, the display name for the USD + * currency object in the en_US locale is "$". + * @param currency null-terminated 3-letter ISO 4217 code + * @param locale locale in which to display currency + * @param nameStyle selector for which kind of name to return + * @param isChoiceFormat always set to false, or can be NULL; + * display names are static strings; + * since ICU 4.4, ChoiceFormat patterns are no longer supported + * @param len fill-in parameter to receive length of result + * @param ec error code + * @return pointer to display string of 'len' UChars. If the resource + * data contains no entry for 'currency', then 'currency' itself is + * returned. + * @stable ICU 2.6 + */ +U_CAPI const UChar* U_EXPORT2 +ucurr_getName(const UChar* currency, + const char* locale, + UCurrNameStyle nameStyle, + UBool* isChoiceFormat, + int32_t* len, + UErrorCode* ec); + +/** + * Returns the plural name for the given currency in the + * given locale. For example, the plural name for the USD + * currency object in the en_US locale is "US dollar" or "US dollars". + * @param currency null-terminated 3-letter ISO 4217 code + * @param locale locale in which to display currency + * @param isChoiceFormat always set to false, or can be NULL; + * display names are static strings; + * since ICU 4.4, ChoiceFormat patterns are no longer supported + * @param pluralCount plural count + * @param len fill-in parameter to receive length of result + * @param ec error code + * @return pointer to display string of 'len' UChars. If the resource + * data contains no entry for 'currency', then 'currency' itself is + * returned. + * @stable ICU 4.2 + */ +U_CAPI const UChar* U_EXPORT2 +ucurr_getPluralName(const UChar* currency, + const char* locale, + UBool* isChoiceFormat, + const char* pluralCount, + int32_t* len, + UErrorCode* ec); + +/** + * Returns the number of the number of fraction digits that should + * be displayed for the given currency. + * This is equivalent to ucurr_getDefaultFractionDigitsForUsage(currency,UCURR_USAGE_STANDARD,ec); + * + * Important: The number of fraction digits for a given currency is NOT + * guaranteed to be constant across versions of ICU or CLDR. For example, + * do NOT use this value as a mechanism for deciding the magnitude used + * to store currency values in a database. You should use this value for + * display purposes only. + * + * @param currency null-terminated 3-letter ISO 4217 code + * @param ec input-output error code + * @return a non-negative number of fraction digits to be + * displayed, or 0 if there is an error + * @stable ICU 3.0 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_getDefaultFractionDigits(const UChar* currency, + UErrorCode* ec); + +/** + * Returns the number of the number of fraction digits that should + * be displayed for the given currency with usage. + * + * Important: The number of fraction digits for a given currency is NOT + * guaranteed to be constant across versions of ICU or CLDR. For example, + * do NOT use this value as a mechanism for deciding the magnitude used + * to store currency values in a database. You should use this value for + * display purposes only. + * + * @param currency null-terminated 3-letter ISO 4217 code + * @param usage enum usage for the currency + * @param ec input-output error code + * @return a non-negative number of fraction digits to be + * displayed, or 0 if there is an error + * @stable ICU 54 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_getDefaultFractionDigitsForUsage(const UChar* currency, + const UCurrencyUsage usage, + UErrorCode* ec); + +/** + * Returns the rounding increment for the given currency, or 0.0 if no + * rounding is done by the currency. + * This is equivalent to ucurr_getRoundingIncrementForUsage(currency,UCURR_USAGE_STANDARD,ec); + * @param currency null-terminated 3-letter ISO 4217 code + * @param ec input-output error code + * @return the non-negative rounding increment, or 0.0 if none, + * or 0.0 if there is an error + * @stable ICU 3.0 + */ +U_CAPI double U_EXPORT2 +ucurr_getRoundingIncrement(const UChar* currency, + UErrorCode* ec); + +/** + * Returns the rounding increment for the given currency, or 0.0 if no + * rounding is done by the currency given usage. + * @param currency null-terminated 3-letter ISO 4217 code + * @param usage enum usage for the currency + * @param ec input-output error code + * @return the non-negative rounding increment, or 0.0 if none, + * or 0.0 if there is an error + * @stable ICU 54 + */ +U_CAPI double U_EXPORT2 +ucurr_getRoundingIncrementForUsage(const UChar* currency, + const UCurrencyUsage usage, + UErrorCode* ec); + +/** + * Selector constants for ucurr_openCurrencies(). + * + * @see ucurr_openCurrencies + * @stable ICU 3.2 + */ +typedef enum UCurrCurrencyType { + /** + * Select all ISO-4217 currency codes. + * @stable ICU 3.2 + */ + UCURR_ALL = INT32_MAX, + /** + * Select only ISO-4217 commonly used currency codes. + * These currencies can be found in common use, and they usually have + * bank notes or coins associated with the currency code. + * This does not include fund codes, precious metals and other + * various ISO-4217 codes limited to special financial products. + * @stable ICU 3.2 + */ + UCURR_COMMON = 1, + /** + * Select ISO-4217 uncommon currency codes. + * These codes respresent fund codes, precious metals and other + * various ISO-4217 codes limited to special financial products. + * A fund code is a monetary resource associated with a currency. + * @stable ICU 3.2 + */ + UCURR_UNCOMMON = 2, + /** + * Select only deprecated ISO-4217 codes. + * These codes are no longer in general public use. + * @stable ICU 3.2 + */ + UCURR_DEPRECATED = 4, + /** + * Select only non-deprecated ISO-4217 codes. + * These codes are in general public use. + * @stable ICU 3.2 + */ + UCURR_NON_DEPRECATED = 8 +} UCurrCurrencyType; + +/** + * Provides a UEnumeration object for listing ISO-4217 codes. + * @param currType You can use one of several UCurrCurrencyType values for this + * variable. You can also | (or) them together to get a specific list of + * currencies. Most people will want to use the (UCURR_COMMON|UCURR_NON_DEPRECATED) value to + * get a list of current currencies. + * @param pErrorCode Error code + * @stable ICU 3.2 + */ +U_CAPI UEnumeration * U_EXPORT2 +ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode); + +/** + * Queries if the given ISO 4217 3-letter code is available on the specified date range. + * + * Note: For checking availability of a currency on a specific date, specify the date on both 'from' and 'to' + * + * When 'from' is U_DATE_MIN and 'to' is U_DATE_MAX, this method checks if the specified currency is available any time. + * If 'from' and 'to' are same UDate value, this method checks if the specified currency is available on that date. + * + * @param isoCode + * The ISO 4217 3-letter code. + * + * @param from + * The lower bound of the date range, inclusive. When 'from' is U_DATE_MIN, check the availability + * of the currency any date before 'to' + * + * @param to + * The upper bound of the date range, inclusive. When 'to' is U_DATE_MAX, check the availability of + * the currency any date after 'from' + * + * @param errorCode + * ICU error code + * + * @return true if the given ISO 4217 3-letter code is supported on the specified date range. + * + * @stable ICU 4.8 + */ +U_CAPI UBool U_EXPORT2 +ucurr_isAvailable(const UChar* isoCode, + UDate from, + UDate to, + UErrorCode* errorCode); + +/** + * Finds the number of valid currency codes for the + * given locale and date. + * @param locale the locale for which to retrieve the + * currency count. + * @param date the date for which to retrieve the + * currency count for the given locale. + * @param ec error code + * @return the number of currency codes for the + * given locale and date. If 0, currency + * codes couldn't be found for the input + * values are invalid. + * @stable ICU 4.0 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_countCurrencies(const char* locale, + UDate date, + UErrorCode* ec); + +/** + * Finds a currency code for the given locale and date + * @param locale the locale for which to retrieve a currency code. + * Currency can be specified by the "currency" keyword + * in which case it overrides the default currency code + * @param date the date for which to retrieve a currency code for + * the given locale. + * @param index the index within the available list of currency codes + * for the given locale on the given date. + * @param buff fill in buffer. Can be NULL for preflighting. + * @param buffCapacity capacity of the fill in buffer. Can be 0 for + * preflighting. If it is non-zero, the buff parameter + * must not be NULL. + * @param ec error code + * @return length of the currency string. It should always be 3. + * If 0, currency couldn't be found or the input values are + * invalid. + * @stable ICU 4.0 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_forLocaleAndDate(const char* locale, + UDate date, + int32_t index, + UChar* buff, + int32_t buffCapacity, + UErrorCode* ec); + +/** + * Given a key and a locale, returns an array of string values in a preferred + * order that would make a difference. These are all and only those values where + * the open (creation) of the service with the locale formed from the input locale + * plus input keyword and that value has different behavior than creation with the + * input locale alone. + * @param key one of the keys supported by this service. For now, only + * "currency" is supported. + * @param locale the locale + * @param commonlyUsed if set to true it will return only commonly used values + * with the given locale in preferred order. Otherwise, + * it will return all the available values for the locale. + * @param status error status + * @return a string enumeration over keyword values for the given key and the locale. + * @stable ICU 4.2 + */ +U_CAPI UEnumeration* U_EXPORT2 +ucurr_getKeywordValuesForLocale(const char* key, + const char* locale, + UBool commonlyUsed, + UErrorCode* status); + +/** + * Returns the ISO 4217 numeric code for the currency. + *

Note: If the ISO 4217 numeric code is not assigned for the currency or + * the currency is unknown, this function returns 0. + * + * @param currency null-terminated 3-letter ISO 4217 code + * @return The ISO 4217 numeric code of the currency + * @stable ICU 49 + */ +U_CAPI int32_t U_EXPORT2 +ucurr_getNumericCode(const UChar* currency); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udat.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udat.h new file mode 100644 index 0000000000000000000000000000000000000000..3823dc88c4fa88b049f0781db98cf754c13b64dc --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udat.h @@ -0,0 +1,1741 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * Copyright (C) 1996-2016, International Business Machines + * Corporation and others. All Rights Reserved. + ******************************************************************************* +*/ + +#ifndef UDAT_H +#define UDAT_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/ucal.h" +#include "unicode/unum.h" +#include "unicode/udisplaycontext.h" +#include "unicode/ufieldpositer.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: DateFormat + * + *

Date Format C API

+ * + * Date Format C API consists of functions that convert dates and + * times from their internal representations to textual form and back again in a + * language-independent manner. Converting from the internal representation (milliseconds + * since midnight, January 1, 1970) to text is known as "formatting," and converting + * from text to millis is known as "parsing." We currently define only one concrete + * structure UDateFormat, which can handle pretty much all normal + * date formatting and parsing actions. + *

+ * Date Format helps you to format and parse dates for any locale. Your code can + * be completely independent of the locale conventions for months, days of the + * week, or even the calendar format: lunar vs. solar. + *

+ * To format a date for the current Locale with default time and date style, + * use one of the static factory methods: + *

+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, NULL, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, NULL, &status);
+ *  }
+ * \endcode
+ * 
+ * If you are formatting multiple numbers, it is more efficient to get the + * format and use it multiple times so that the system doesn't have to fetch the + * information about the local language and country conventions multiple times. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t i, myStrlen = 0;
+ *  UChar* myString;
+ *  char buffer[1024];
+ *  UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *  UDateFormat* df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, 0, &status);
+ *  for (i = 0; i < 3; i++) {
+ *      myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status);
+ *      if(status == U_BUFFER_OVERFLOW_ERROR){
+ *          status = U_ZERO_ERROR;
+ *          myString = (UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *          udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status);
+ *          printf("%s\n", u_austrcpy(buffer, myString) );
+ *          free(myString);
+ *      }
+ *  }
+ * \endcode
+ * 
+ * To get specific fields of a date, you can use UFieldPosition to + * get specific fields. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UFieldPosition pos;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  char buffer[1024];
+ *
+ *  pos.field = 1;  // Same as the DateFormat::EField enum
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, -1, NULL, 0, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status);
+ *  }
+ *  printf("date format: %s\n", u_austrcpy(buffer, myString));
+ *  buffer[pos.endIndex] = 0;   // NULL terminate the string.
+ *  printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]);
+ * \endcode
+ * 
+ * To format a date for a different Locale, specify it in the call to + * udat_open() + *
+ * \code
+ *        UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", NULL, -1, NULL, 0, &status);
+ * \endcode
+ * 
+ * You can use a DateFormat API udat_parse() to parse. + *
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t parsepos=0;
+ *  UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status);
+ * \endcode
+ * 
+ * You can pass in different options for the arguments for date and time style + * to control the length of the result; from SHORT to MEDIUM to LONG to FULL. + * The exact result depends on the locale, but generally: + * see UDateFormatStyle for more details + *
    + *
  • UDAT_SHORT is completely numeric, such as 12/13/52 or 3:30pm + *
  • UDAT_MEDIUM is longer, such as Jan 12, 1952 + *
  • UDAT_LONG is longer, such as January 12, 1952 or 3:30:32pm + *
  • UDAT_FULL is pretty completely specified, such as + * Tuesday, April 12, 1952 AD or 3:30:42pm PST. + *
+ * You can also set the time zone on the format if you wish. + *

+ * You can also use forms of the parse and format methods with Parse Position and + * UFieldPosition to allow you to + *

    + *
  • Progressively parse through pieces of a string. + *
  • Align any particular field, or find out where it is for selection + * on the screen. + *
+ *

Date and Time Patterns:

+ * + *

Date and time formats are specified by date and time pattern strings. + * Within date and time pattern strings, all unquoted ASCII letters [A-Za-z] are reserved + * as pattern letters representing calendar fields. UDateFormat supports + * the date and time formatting algorithm and pattern letters defined by + * UTS#35 + * Unicode Locale Data Markup Language (LDML) and further documented for ICU in the + * ICU + * User Guide.

+ */ + +/** A date formatter. + * For usage in C programs. + * @stable ICU 2.6 + */ +typedef void* UDateFormat; + +/** The possible date/time format styles + * @stable ICU 2.6 + */ +typedef enum UDateFormatStyle { + /** Full style */ + UDAT_FULL, + /** Long style */ + UDAT_LONG, + /** Medium style */ + UDAT_MEDIUM, + /** Short style */ + UDAT_SHORT, + /** Default style */ + UDAT_DEFAULT = UDAT_MEDIUM, + + /** Bitfield for relative date */ + UDAT_RELATIVE = (1 << 7), + + UDAT_FULL_RELATIVE = UDAT_FULL | UDAT_RELATIVE, + + UDAT_LONG_RELATIVE = UDAT_LONG | UDAT_RELATIVE, + + UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM | UDAT_RELATIVE, + + UDAT_SHORT_RELATIVE = UDAT_SHORT | UDAT_RELATIVE, + + + /** No style */ + UDAT_NONE = -1, + + /** + * Use the pattern given in the parameter to udat_open + * @see udat_open + * @stable ICU 50 + */ + UDAT_PATTERN = -2, + +#ifndef U_HIDE_INTERNAL_API + /** @internal alias to UDAT_PATTERN */ + UDAT_IGNORE = UDAT_PATTERN +#endif /* U_HIDE_INTERNAL_API */ +} UDateFormatStyle; + +/* Skeletons for dates. */ + +/** + * Constant for date skeleton with year. + * @stable ICU 4.0 + */ +#define UDAT_YEAR "y" +/** + * Constant for date skeleton with quarter. + * @stable ICU 51 + */ +#define UDAT_QUARTER "QQQQ" +/** + * Constant for date skeleton with abbreviated quarter. + * @stable ICU 51 + */ +#define UDAT_ABBR_QUARTER "QQQ" +/** + * Constant for date skeleton with year and quarter. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_QUARTER "yQQQQ" +/** + * Constant for date skeleton with year and abbreviated quarter. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_ABBR_QUARTER "yQQQ" +/** + * Constant for date skeleton with month. + * @stable ICU 4.0 + */ +#define UDAT_MONTH "MMMM" +/** + * Constant for date skeleton with abbreviated month. + * @stable ICU 4.0 + */ +#define UDAT_ABBR_MONTH "MMM" +/** + * Constant for date skeleton with numeric month. + * @stable ICU 4.0 + */ +#define UDAT_NUM_MONTH "M" +/** + * Constant for date skeleton with year and month. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_MONTH "yMMMM" +/** + * Constant for date skeleton with year and abbreviated month. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_ABBR_MONTH "yMMM" +/** + * Constant for date skeleton with year and numeric month. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_NUM_MONTH "yM" +/** + * Constant for date skeleton with day. + * @stable ICU 4.0 + */ +#define UDAT_DAY "d" +/** + * Constant for date skeleton with year, month, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_MONTH_DAY "yMMMMd" +/** + * Constant for date skeleton with year, abbreviated month, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_ABBR_MONTH_DAY "yMMMd" +/** + * Constant for date skeleton with year, numeric month, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_NUM_MONTH_DAY "yMd" +/** + * Constant for date skeleton with weekday. + * @stable ICU 51 + */ +#define UDAT_WEEKDAY "EEEE" +/** + * Constant for date skeleton with abbreviated weekday. + * @stable ICU 51 + */ +#define UDAT_ABBR_WEEKDAY "E" +/** + * Constant for date skeleton with year, month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_MONTH_WEEKDAY_DAY "yMMMMEEEEd" +/** + * Constant for date skeleton with year, abbreviated month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY "yMMMEd" +/** + * Constant for date skeleton with year, numeric month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_YEAR_NUM_MONTH_WEEKDAY_DAY "yMEd" +/** + * Constant for date skeleton with long month and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_MONTH_DAY "MMMMd" +/** + * Constant for date skeleton with abbreviated month and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_ABBR_MONTH_DAY "MMMd" +/** + * Constant for date skeleton with numeric month and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_NUM_MONTH_DAY "Md" +/** + * Constant for date skeleton with month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_MONTH_WEEKDAY_DAY "MMMMEEEEd" +/** + * Constant for date skeleton with abbreviated month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_ABBR_MONTH_WEEKDAY_DAY "MMMEd" +/** + * Constant for date skeleton with numeric month, weekday, and day. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_NUM_MONTH_WEEKDAY_DAY "MEd" + +/* Skeletons for times. */ + +/** + * Constant for date skeleton with hour, with the locale's preferred hour format (12 or 24). + * @stable ICU 4.0 + */ +#define UDAT_HOUR "j" +/** + * Constant for date skeleton with hour in 24-hour presentation. + * @stable ICU 51 + */ +#define UDAT_HOUR24 "H" +/** + * Constant for date skeleton with minute. + * @stable ICU 51 + */ +#define UDAT_MINUTE "m" +/** + * Constant for date skeleton with hour and minute, with the locale's preferred hour format (12 or 24). + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_HOUR_MINUTE "jm" +/** + * Constant for date skeleton with hour and minute in 24-hour presentation. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_HOUR24_MINUTE "Hm" +/** + * Constant for date skeleton with second. + * @stable ICU 51 + */ +#define UDAT_SECOND "s" +/** + * Constant for date skeleton with hour, minute, and second, + * with the locale's preferred hour format (12 or 24). + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_HOUR_MINUTE_SECOND "jms" +/** + * Constant for date skeleton with hour, minute, and second in + * 24-hour presentation. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_HOUR24_MINUTE_SECOND "Hms" +/** + * Constant for date skeleton with minute and second. + * Used in combinations date + time, date + time + zone, or time + zone. + * @stable ICU 4.0 + */ +#define UDAT_MINUTE_SECOND "ms" + +/* Skeletons for time zones. */ + +/** + * Constant for generic location format, such as Los Angeles Time; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_LOCATION_TZ "VVVV" +/** + * Constant for generic non-location format, such as Pacific Time; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_GENERIC_TZ "vvvv" +/** + * Constant for generic non-location format, abbreviated if possible, such as PT; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_ABBR_GENERIC_TZ "v" +/** + * Constant for specific non-location format, such as Pacific Daylight Time; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_SPECIFIC_TZ "zzzz" +/** + * Constant for specific non-location format, abbreviated if possible, such as PDT; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_ABBR_SPECIFIC_TZ "z" +/** + * Constant for localized GMT/UTC format, such as GMT+8:00 or HPG-8:00; + * used in combinations date + time + zone, or time + zone. + * @see LDML Date Format Patterns + * @see LDML Time Zone Fallback + * @stable ICU 51 + */ +#define UDAT_ABBR_UTC_TZ "ZZZZ" + +/* deprecated skeleton constants */ + +#ifndef U_HIDE_DEPRECATED_API +/** + * Constant for date skeleton with standalone month. + * @deprecated ICU 50 Use UDAT_MONTH instead. + */ +#define UDAT_STANDALONE_MONTH "LLLL" +/** + * Constant for date skeleton with standalone abbreviated month. + * @deprecated ICU 50 Use UDAT_ABBR_MONTH instead. + */ +#define UDAT_ABBR_STANDALONE_MONTH "LLL" + +/** + * Constant for date skeleton with hour, minute, and generic timezone. + * @deprecated ICU 50 Use instead UDAT_HOUR_MINUTE UDAT_ABBR_GENERIC_TZ or some other timezone presentation. + */ +#define UDAT_HOUR_MINUTE_GENERIC_TZ "jmv" +/** + * Constant for date skeleton with hour, minute, and timezone. + * @deprecated ICU 50 Use instead UDAT_HOUR_MINUTE UDAT_ABBR_SPECIFIC_TZ or some other timezone presentation. + */ +#define UDAT_HOUR_MINUTE_TZ "jmz" +/** + * Constant for date skeleton with hour and generic timezone. + * @deprecated ICU 50 Use instead UDAT_HOUR UDAT_ABBR_GENERIC_TZ or some other timezone presentation. + */ +#define UDAT_HOUR_GENERIC_TZ "jv" +/** + * Constant for date skeleton with hour and timezone. + * @deprecated ICU 50 Use instead UDAT_HOUR UDAT_ABBR_SPECIFIC_TZ or some other timezone presentation. + */ +#define UDAT_HOUR_TZ "jz" +#endif /* U_HIDE_DEPRECATED_API */ + +#ifndef U_HIDE_INTERNAL_API +/** + * Constant for Unicode string name of new (in 2019) Japanese calendar era, + * root/English abbreviated version (ASCII-range characters). + * @internal + */ +#define JP_ERA_2019_ROOT "Reiwa" +/** + * Constant for Unicode string name of new (in 2019) Japanese calendar era, + * Japanese abbreviated version (Han, or fullwidth Latin for testing). + * @internal + */ +#define JP_ERA_2019_JA "\\u4EE4\\u548C" +/** + * Constant for Unicode string name of new (in 2019) Japanese calendar era, + * root and Japanese narrow version (ASCII-range characters). + * @internal + */ +#define JP_ERA_2019_NARROW "R" +#endif // U_HIDE_INTERNAL_API + +/** + * FieldPosition and UFieldPosition selectors for format fields + * defined by DateFormat and UDateFormat. + * @stable ICU 3.0 + */ +typedef enum UDateFormatField { + /** + * FieldPosition and UFieldPosition selector for 'G' field alignment, + * corresponding to the UCAL_ERA field. + * @stable ICU 3.0 + */ + UDAT_ERA_FIELD = 0, + + /** + * FieldPosition and UFieldPosition selector for 'y' field alignment, + * corresponding to the UCAL_YEAR field. + * @stable ICU 3.0 + */ + UDAT_YEAR_FIELD = 1, + + /** + * FieldPosition and UFieldPosition selector for 'M' field alignment, + * corresponding to the UCAL_MONTH field. + * @stable ICU 3.0 + */ + UDAT_MONTH_FIELD = 2, + + /** + * FieldPosition and UFieldPosition selector for 'd' field alignment, + * corresponding to the UCAL_DATE field. + * @stable ICU 3.0 + */ + UDAT_DATE_FIELD = 3, + + /** + * FieldPosition and UFieldPosition selector for 'k' field alignment, + * corresponding to the UCAL_HOUR_OF_DAY field. + * UDAT_HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. + * For example, 23:59 + 01:00 results in 24:59. + * @stable ICU 3.0 + */ + UDAT_HOUR_OF_DAY1_FIELD = 4, + + /** + * FieldPosition and UFieldPosition selector for 'H' field alignment, + * corresponding to the UCAL_HOUR_OF_DAY field. + * UDAT_HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. + * For example, 23:59 + 01:00 results in 00:59. + * @stable ICU 3.0 + */ + UDAT_HOUR_OF_DAY0_FIELD = 5, + + /** + * FieldPosition and UFieldPosition selector for 'm' field alignment, + * corresponding to the UCAL_MINUTE field. + * @stable ICU 3.0 + */ + UDAT_MINUTE_FIELD = 6, + + /** + * FieldPosition and UFieldPosition selector for 's' field alignment, + * corresponding to the UCAL_SECOND field. + * @stable ICU 3.0 + */ + UDAT_SECOND_FIELD = 7, + + /** + * FieldPosition and UFieldPosition selector for 'S' field alignment, + * corresponding to the UCAL_MILLISECOND field. + * + * Note: Time formats that use 'S' can display a maximum of three + * significant digits for fractional seconds, corresponding to millisecond + * resolution and a fractional seconds sub-pattern of SSS. If the + * sub-pattern is S or SS, the fractional seconds value will be truncated + * (not rounded) to the number of display places specified. If the + * fractional seconds sub-pattern is longer than SSS, the additional + * display places will be filled with zeros. + * @stable ICU 3.0 + */ + UDAT_FRACTIONAL_SECOND_FIELD = 8, + + /** + * FieldPosition and UFieldPosition selector for 'E' field alignment, + * corresponding to the UCAL_DAY_OF_WEEK field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_WEEK_FIELD = 9, + + /** + * FieldPosition and UFieldPosition selector for 'D' field alignment, + * corresponding to the UCAL_DAY_OF_YEAR field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_YEAR_FIELD = 10, + + /** + * FieldPosition and UFieldPosition selector for 'F' field alignment, + * corresponding to the UCAL_DAY_OF_WEEK_IN_MONTH field. + * @stable ICU 3.0 + */ + UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11, + + /** + * FieldPosition and UFieldPosition selector for 'w' field alignment, + * corresponding to the UCAL_WEEK_OF_YEAR field. + * @stable ICU 3.0 + */ + UDAT_WEEK_OF_YEAR_FIELD = 12, + + /** + * FieldPosition and UFieldPosition selector for 'W' field alignment, + * corresponding to the UCAL_WEEK_OF_MONTH field. + * @stable ICU 3.0 + */ + UDAT_WEEK_OF_MONTH_FIELD = 13, + + /** + * FieldPosition and UFieldPosition selector for 'a' field alignment, + * corresponding to the UCAL_AM_PM field. + * @stable ICU 3.0 + */ + UDAT_AM_PM_FIELD = 14, + + /** + * FieldPosition and UFieldPosition selector for 'h' field alignment, + * corresponding to the UCAL_HOUR field. + * UDAT_HOUR1_FIELD is used for the one-based 12-hour clock. + * For example, 11:30 PM + 1 hour results in 12:30 AM. + * @stable ICU 3.0 + */ + UDAT_HOUR1_FIELD = 15, + + /** + * FieldPosition and UFieldPosition selector for 'K' field alignment, + * corresponding to the UCAL_HOUR field. + * UDAT_HOUR0_FIELD is used for the zero-based 12-hour clock. + * For example, 11:30 PM + 1 hour results in 00:30 AM. + * @stable ICU 3.0 + */ + UDAT_HOUR0_FIELD = 16, + + /** + * FieldPosition and UFieldPosition selector for 'z' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and + * UCAL_DST_OFFSET fields. + * @stable ICU 3.0 + */ + UDAT_TIMEZONE_FIELD = 17, + + /** + * FieldPosition and UFieldPosition selector for 'Y' field alignment, + * corresponding to the UCAL_YEAR_WOY field. + * @stable ICU 3.0 + */ + UDAT_YEAR_WOY_FIELD = 18, + + /** + * FieldPosition and UFieldPosition selector for 'e' field alignment, + * corresponding to the UCAL_DOW_LOCAL field. + * @stable ICU 3.0 + */ + UDAT_DOW_LOCAL_FIELD = 19, + + /** + * FieldPosition and UFieldPosition selector for 'u' field alignment, + * corresponding to the UCAL_EXTENDED_YEAR field. + * @stable ICU 3.0 + */ + UDAT_EXTENDED_YEAR_FIELD = 20, + + /** + * FieldPosition and UFieldPosition selector for 'g' field alignment, + * corresponding to the UCAL_JULIAN_DAY field. + * @stable ICU 3.0 + */ + UDAT_JULIAN_DAY_FIELD = 21, + + /** + * FieldPosition and UFieldPosition selector for 'A' field alignment, + * corresponding to the UCAL_MILLISECONDS_IN_DAY field. + * @stable ICU 3.0 + */ + UDAT_MILLISECONDS_IN_DAY_FIELD = 22, + + /** + * FieldPosition and UFieldPosition selector for 'Z' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and + * UCAL_DST_OFFSET fields. + * @stable ICU 3.0 + */ + UDAT_TIMEZONE_RFC_FIELD = 23, + + /** + * FieldPosition and UFieldPosition selector for 'v' field alignment, + * corresponding to the UCAL_ZONE_OFFSET field. + * @stable ICU 3.4 + */ + UDAT_TIMEZONE_GENERIC_FIELD = 24, + /** + * FieldPosition selector for 'c' field alignment, + * corresponding to the {@link #UCAL_DOW_LOCAL} field. + * This displays the stand alone day name, if available. + * @stable ICU 3.4 + */ + UDAT_STANDALONE_DAY_FIELD = 25, + + /** + * FieldPosition selector for 'L' field alignment, + * corresponding to the {@link #UCAL_MONTH} field. + * This displays the stand alone month name, if available. + * @stable ICU 3.4 + */ + UDAT_STANDALONE_MONTH_FIELD = 26, + + /** + * FieldPosition selector for "Q" field alignment, + * corresponding to quarters. This is implemented + * using the {@link #UCAL_MONTH} field. This + * displays the quarter. + * @stable ICU 3.6 + */ + UDAT_QUARTER_FIELD = 27, + + /** + * FieldPosition selector for the "q" field alignment, + * corresponding to stand-alone quarters. This is + * implemented using the {@link #UCAL_MONTH} field. + * This displays the stand-alone quarter. + * @stable ICU 3.6 + */ + UDAT_STANDALONE_QUARTER_FIELD = 28, + + /** + * FieldPosition and UFieldPosition selector for 'V' field alignment, + * corresponding to the UCAL_ZONE_OFFSET field. + * @stable ICU 3.8 + */ + UDAT_TIMEZONE_SPECIAL_FIELD = 29, + + /** + * FieldPosition selector for "U" field alignment, + * corresponding to cyclic year names. This is implemented + * using the {@link #UCAL_YEAR} field. This displays + * the cyclic year name, if available. + * @stable ICU 49 + */ + UDAT_YEAR_NAME_FIELD = 30, + + /** + * FieldPosition selector for 'O' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSETfields. + * This displays the localized GMT format. + * @stable ICU 51 + */ + UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD = 31, + + /** + * FieldPosition selector for 'X' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSETfields. + * This displays the ISO 8601 local time offset format or UTC indicator ("Z"). + * @stable ICU 51 + */ + UDAT_TIMEZONE_ISO_FIELD = 32, + + /** + * FieldPosition selector for 'x' field alignment, + * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSET fields. + * This displays the ISO 8601 local time offset format. + * @stable ICU 51 + */ + UDAT_TIMEZONE_ISO_LOCAL_FIELD = 33, + +#ifndef U_HIDE_INTERNAL_API + /** + * FieldPosition and UFieldPosition selector for 'r' field alignment, + * no directly corresponding UCAL_ field. + * @internal ICU 53 + */ + UDAT_RELATED_YEAR_FIELD = 34, +#endif /* U_HIDE_INTERNAL_API */ + + /** + * FieldPosition selector for 'b' field alignment. + * Displays midnight and noon for 12am and 12pm, respectively, if available; + * otherwise fall back to AM / PM. + * @stable ICU 57 + */ + UDAT_AM_PM_MIDNIGHT_NOON_FIELD = 35, + + /* FieldPosition selector for 'B' field alignment. + * Displays flexible day periods, such as "in the morning", if available. + * @stable ICU 57 + */ + UDAT_FLEXIBLE_DAY_PERIOD_FIELD = 36, + +#ifndef U_HIDE_INTERNAL_API + /** + * FieldPosition and UFieldPosition selector for time separator, + * no corresponding UCAL_ field. No pattern character is currently + * defined for this. + * @internal + */ + UDAT_TIME_SEPARATOR_FIELD = 37, +#endif /* U_HIDE_INTERNAL_API */ + +#ifndef U_HIDE_DEPRECATED_API + /** + * Number of FieldPosition and UFieldPosition selectors for + * DateFormat and UDateFormat. + * Valid selectors range from 0 to UDAT_FIELD_COUNT-1. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDAT_FIELD_COUNT = 38 +#endif /* U_HIDE_DEPRECATED_API */ +} UDateFormatField; + + +#ifndef U_HIDE_INTERNAL_API +/** + * Is a pattern character defined for UDAT_TIME_SEPARATOR_FIELD? + * In ICU 55 it was COLON, but that was withdrawn in ICU 56. + * @internal ICU 56 + */ +#define UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR 0 +#endif /* U_HIDE_INTERNAL_API */ + + +/** + * Maps from a UDateFormatField to the corresponding UCalendarDateFields. + * + * Note 1: Since the mapping is many-to-one, there is no inverse mapping. + * + * Note 2: There is no UErrorCode parameter, so in case of error (UDateFormatField is + * unknown or has no corresponding UCalendarDateFields value), the function returns the + * current value of UCAL_FIELD_COUNT. However, that value may change from release to + * release and is consequently deprecated. For a future-proof runtime way of checking + * for errors: + * a) First save the value returned by the function when it is passed an invalid value + * such as "(UDateFormatField)-1". + * b) Then, to test for errors when passing some other UDateFormatField value, check + * whether the function returns that saved value. + * + * @param field the UDateFormatField. + * @return the UCalendarDateField. In case of error (UDateFormatField is unknown or has + * no corresponding UCalendarDateFields value) this will be the current value of + * UCAL_FIELD_COUNT, but that value may change from release to release. + * See Note 2 above. + * @stable ICU 4.4 + */ +U_CAPI UCalendarDateFields U_EXPORT2 +udat_toCalendarDateField(UDateFormatField field); + + +/** + * Open a new UDateFormat for formatting and parsing dates and times. + * A UDateFormat may be used to format dates in calls to {@link #udat_format }, + * and to parse dates in calls to {@link #udat_parse }. + * @param timeStyle The style used to format times; one of UDAT_FULL, UDAT_LONG, + * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, or UDAT_NONE (relative time styles + * are not currently supported). + * When the pattern parameter is used, pass in UDAT_PATTERN for both timeStyle and dateStyle. + * @param dateStyle The style used to format dates; one of UDAT_FULL, UDAT_LONG, + * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, UDAT_FULL_RELATIVE, UDAT_LONG_RELATIVE, + * UDAT_MEDIUM_RELATIVE, UDAT_SHORT_RELATIVE, or UDAT_NONE. + * When the pattern parameter is used, pass in UDAT_PATTERN for both timeStyle and dateStyle. + * As currently implemented, + * relative date formatting only affects a limited range of calendar days before or + * after the current date, based on the CLDR <field type="day">/<relative> data: For + * example, in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, + * dates are formatted using the corresponding non-relative style. + * @param locale The locale specifying the formatting conventions + * @param tzID A timezone ID specifying the timezone to use. If 0, use + * the default timezone. + * @param tzIDLength The length of tzID, or -1 if null-terminated. + * @param pattern A pattern specifying the format to use. + * @param patternLength The number of characters in the pattern, or -1 if null-terminated. + * @param status A pointer to an UErrorCode to receive any errors + * @return A pointer to a UDateFormat to use for formatting dates and times, or 0 if + * an error occurred. + * @stable ICU 2.0 + */ +U_CAPI UDateFormat* U_EXPORT2 +udat_open(UDateFormatStyle timeStyle, + UDateFormatStyle dateStyle, + const char *locale, + const UChar *tzID, + int32_t tzIDLength, + const UChar *pattern, + int32_t patternLength, + UErrorCode *status); + + +/** +* Close a UDateFormat. +* Once closed, a UDateFormat may no longer be used. +* @param format The formatter to close. +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_close(UDateFormat* format); + + +/** + * DateFormat boolean attributes + * + * @stable ICU 53 + */ +typedef enum UDateFormatBooleanAttribute { + /** + * indicates whether whitespace is allowed. Includes trailing dot tolerance. + * @stable ICU 53 + */ + UDAT_PARSE_ALLOW_WHITESPACE = 0, + /** + * indicates tolerance of numeric data when String data may be assumed. eg: UDAT_YEAR_NAME_FIELD, + * UDAT_STANDALONE_MONTH_FIELD, UDAT_DAY_OF_WEEK_FIELD + * @stable ICU 53 + */ + UDAT_PARSE_ALLOW_NUMERIC = 1, + /** + * indicates tolerance of a partial literal match + * e.g. accepting "--mon-02-march-2011" for a pattern of "'--: 'EEE-WW-MMMM-yyyy" + * @stable ICU 56 + */ + UDAT_PARSE_PARTIAL_LITERAL_MATCH = 2, + /** + * indicates tolerance of pattern mismatch between input data and specified format pattern. + * e.g. accepting "September" for a month pattern of MMM ("Sep") + * @stable ICU 56 + */ + UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH = 3, + + /* Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, + * it is needed for layout of DateFormat object. */ +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateFormatBooleanAttribute value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDAT_BOOLEAN_ATTRIBUTE_COUNT = 4 +#endif // U_FORCE_HIDE_DEPRECATED_API +} UDateFormatBooleanAttribute; + +/** + * Get a boolean attribute associated with a UDateFormat. + * An example would be a true value for a key of UDAT_PARSE_ALLOW_WHITESPACE indicating allowing whitespace leniency. + * If the formatter does not understand the attribute, -1 is returned. + * @param fmt The formatter to query. + * @param attr The attribute to query; e.g. UDAT_PARSE_ALLOW_WHITESPACE. + * @param status A pointer to an UErrorCode to receive any errors + * @return The value of attr. + * @stable ICU 53 + */ +U_CAPI UBool U_EXPORT2 +udat_getBooleanAttribute(const UDateFormat* fmt, UDateFormatBooleanAttribute attr, UErrorCode* status); + +/** + * Set a boolean attribute associated with a UDateFormat. + * An example of a boolean attribute is parse leniency control. If the formatter does not understand + * the attribute, the call is ignored. + * @param fmt The formatter to set. + * @param attr The attribute to set; one of UDAT_PARSE_ALLOW_WHITESPACE or UDAT_PARSE_ALLOW_NUMERIC + * @param newValue The new value of attr. + * @param status A pointer to an UErrorCode to receive any errors + * @stable ICU 53 + */ +U_CAPI void U_EXPORT2 +udat_setBooleanAttribute(UDateFormat *fmt, UDateFormatBooleanAttribute attr, UBool newValue, UErrorCode* status); + +/** + * Hour Cycle. + * @stable ICU 67 + */ +typedef enum UDateFormatHourCycle { + /** + * Hour in am/pm (0~11) + * @stable ICU 67 + */ + UDAT_HOUR_CYCLE_11, + + /** + * Hour in am/pm (1~12) + * @stable ICU 67 + */ + UDAT_HOUR_CYCLE_12, + + /** + * Hour in day (0~23) + * @stable ICU 67 + */ + UDAT_HOUR_CYCLE_23, + + /** + * Hour in day (1~24) + * @stable ICU 67 + */ + UDAT_HOUR_CYCLE_24 +} UDateFormatHourCycle; + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDateFormatPointer + * "Smart pointer" class, closes a UDateFormat via udat_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateFormatPointer, UDateFormat, udat_close); + +U_NAMESPACE_END + +#endif + +/** + * Open a copy of a UDateFormat. + * This function performs a deep copy. + * @param fmt The format to copy + * @param status A pointer to an UErrorCode to receive any errors. + * @return A pointer to a UDateFormat identical to fmt. + * @stable ICU 2.0 + */ +U_CAPI UDateFormat* U_EXPORT2 +udat_clone(const UDateFormat *fmt, + UErrorCode *status); + +/** +* Format a date using a UDateFormat. +* The date will be formatted using the conventions specified in {@link #udat_open } +* @param format The formatter to use +* @param dateToFormat The date to format +* @param result A pointer to a buffer to receive the formatted number. +* @param resultLength The maximum size of result. +* @param position A pointer to a UFieldPosition. On input, position->field +* is read. On output, position->beginIndex and position->endIndex indicate +* the beginning and ending indices of field number position->field, if such +* a field exists. This parameter may be NULL, in which case no field +* position data is returned. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_parse +* @see UFieldPosition +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +udat_format( const UDateFormat* format, + UDate dateToFormat, + UChar* result, + int32_t resultLength, + UFieldPosition* position, + UErrorCode* status); + +/** +* Format a date using an UDateFormat. +* The date will be formatted using the conventions specified in {@link #udat_open } +* @param format The formatter to use +* @param calendar The calendar to format. The calendar instance might be +* mutated if fields are not yet fully calculated, though +* the function won't change the logical date and time held +* by the instance. +* @param result A pointer to a buffer to receive the formatted number. +* @param capacity The maximum size of result. +* @param position A pointer to a UFieldPosition. On input, position->field +* is read. On output, position->beginIndex and position->endIndex indicate +* the beginning and ending indices of field number position->field, if such +* a field exists. This parameter may be NULL, in which case no field +* position data is returned. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_format +* @see udat_parseCalendar +* @see UFieldPosition +* @stable ICU 55 +*/ +U_CAPI int32_t U_EXPORT2 +udat_formatCalendar( const UDateFormat* format, + UCalendar* calendar, + UChar* result, + int32_t capacity, + UFieldPosition* position, + UErrorCode* status); + +/** +* Format a date using a UDateFormat. +* The date will be formatted using the conventions specified in {@link #udat_open} +* @param format +* The formatter to use +* @param dateToFormat +* The date to format +* @param result +* A pointer to a buffer to receive the formatted number. +* @param resultLength +* The maximum size of result. +* @param fpositer +* A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open} +* (may be NULL if field position information is not needed). Any +* iteration information already present in the UFieldPositionIterator +* will be deleted, and the iterator will be reset to apply to the +* fields in the formatted string created by this function call; the +* field values provided by {@link #ufieldpositer_next} will be from the +* UDateFormatField enum. +* @param status +* A pointer to a UErrorCode to receive any errors +* @return +* The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_parse +* @see UFieldPositionIterator +* @stable ICU 55 +*/ +U_CAPI int32_t U_EXPORT2 +udat_formatForFields( const UDateFormat* format, + UDate dateToFormat, + UChar* result, + int32_t resultLength, + UFieldPositionIterator* fpositer, + UErrorCode* status); + +/** +* Format a date using a UDateFormat. +* The date will be formatted using the conventions specified in {@link #udat_open } +* @param format +* The formatter to use +* @param calendar +* The calendar to format. The calendar instance might be mutated if fields +* are not yet fully calculated, though the function won't change the logical +* date and time held by the instance. +* @param result +* A pointer to a buffer to receive the formatted number. +* @param capacity +* The maximum size of result. +* @param fpositer +* A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open} +* (may be NULL if field position information is not needed). Any +* iteration information already present in the UFieldPositionIterator +* will be deleted, and the iterator will be reset to apply to the +* fields in the formatted string created by this function call; the +* field values provided by {@link #ufieldpositer_next} will be from the +* UDateFormatField enum. +* @param status +* A pointer to a UErrorCode to receive any errors +* @return +* The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_format +* @see udat_parseCalendar +* @see UFieldPositionIterator +* @stable ICU 55 +*/ +U_CAPI int32_t U_EXPORT2 +udat_formatCalendarForFields( const UDateFormat* format, + UCalendar* calendar, + UChar* result, + int32_t capacity, + UFieldPositionIterator* fpositer, + UErrorCode* status); + + +/** +* Parse a string into an date/time using a UDateFormat. +* The date will be parsed using the conventions specified in {@link #udat_open }. +*

+* Note that the normal date formats associated with some calendars - such +* as the Chinese lunar calendar - do not specify enough fields to enable +* dates to be parsed unambiguously. In the case of the Chinese lunar +* calendar, while the year within the current 60-year cycle is specified, +* the number of such cycles since the start date of the calendar (in the +* UCAL_ERA field of the UCalendar object) is not normally part of the format, +* and parsing may assume the wrong era. For cases such as this it is +* recommended that clients parse using udat_parseCalendar with the UCalendar +* passed in set to the current date, or to a date within the era/cycle that +* should be assumed if absent in the format. +* +* @param format The formatter to use. +* @param text The text to parse. +* @param textLength The length of text, or -1 if null-terminated. +* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which +* to begin parsing. If not 0, on output the offset at which parsing ended. +* @param status A pointer to an UErrorCode to receive any errors +* @return The value of the parsed date/time +* @see udat_format +* @stable ICU 2.0 +*/ +U_CAPI UDate U_EXPORT2 +udat_parse(const UDateFormat* format, + const UChar* text, + int32_t textLength, + int32_t *parsePos, + UErrorCode *status); + +/** +* Parse a string into an date/time using a UDateFormat. +* The date will be parsed using the conventions specified in {@link #udat_open }. +* @param format The formatter to use. +* @param calendar A calendar set on input to the date and time to be used for +* missing values in the date/time string being parsed, and set +* on output to the parsed date/time. When the calendar type is +* different from the internal calendar held by the UDateFormat +* instance, the internal calendar will be cloned to a work +* calendar set to the same milliseconds and time zone as this +* calendar parameter, field values will be parsed based on the +* work calendar, then the result (milliseconds and time zone) +* will be set in this calendar. +* @param text The text to parse. +* @param textLength The length of text, or -1 if null-terminated. +* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which +* to begin parsing. If not 0, on output the offset at which parsing ended. +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_format +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_parseCalendar(const UDateFormat* format, + UCalendar* calendar, + const UChar* text, + int32_t textLength, + int32_t *parsePos, + UErrorCode *status); + +/** +* Determine if an UDateFormat will perform lenient parsing. +* With lenient parsing, the parser may use heuristics to interpret inputs that do not +* precisely match the pattern. With strict parsing, inputs must match the pattern. +* @param fmt The formatter to query +* @return true if fmt is set to perform lenient parsing, false otherwise. +* @see udat_setLenient +* @stable ICU 2.0 +*/ +U_CAPI UBool U_EXPORT2 +udat_isLenient(const UDateFormat* fmt); + +/** +* Specify whether an UDateFormat will perform lenient parsing. +* With lenient parsing, the parser may use heuristics to interpret inputs that do not +* precisely match the pattern. With strict parsing, inputs must match the pattern. +* @param fmt The formatter to set +* @param isLenient true if fmt should perform lenient parsing, false otherwise. +* @see dat_isLenient +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_setLenient( UDateFormat* fmt, + UBool isLenient); + +/** +* Get the UCalendar associated with an UDateFormat. +* A UDateFormat uses a UCalendar to convert a raw value to, for example, +* the day of the week. +* @param fmt The formatter to query. +* @return A pointer to the UCalendar used by fmt. +* @see udat_setCalendar +* @stable ICU 2.0 +*/ +U_CAPI const UCalendar* U_EXPORT2 +udat_getCalendar(const UDateFormat* fmt); + +/** +* Set the UCalendar associated with an UDateFormat. +* A UDateFormat uses a UCalendar to convert a raw value to, for example, +* the day of the week. +* @param fmt The formatter to set. +* @param calendarToSet A pointer to an UCalendar to be used by fmt. +* @see udat_setCalendar +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_setCalendar( UDateFormat* fmt, + const UCalendar* calendarToSet); + +/** +* Get the UNumberFormat associated with an UDateFormat. +* A UDateFormat uses a UNumberFormat to format numbers within a date, +* for example the day number. +* @param fmt The formatter to query. +* @return A pointer to the UNumberFormat used by fmt to format numbers. +* @see udat_setNumberFormat +* @stable ICU 2.0 +*/ +U_CAPI const UNumberFormat* U_EXPORT2 +udat_getNumberFormat(const UDateFormat* fmt); + +/** +* Get the UNumberFormat for specific field associated with an UDateFormat. +* For example: 'y' for year and 'M' for month +* @param fmt The formatter to query. +* @param field the field to query +* @return A pointer to the UNumberFormat used by fmt to format field numbers. +* @see udat_setNumberFormatForField +* @stable ICU 54 +*/ +U_CAPI const UNumberFormat* U_EXPORT2 +udat_getNumberFormatForField(const UDateFormat* fmt, UChar field); + +/** +* Set the UNumberFormat for specific field associated with an UDateFormat. +* It can be a single field like: "y"(year) or "M"(month) +* It can be several field combined together: "yM"(year and month) +* Note: +* 1 symbol field is enough for multiple symbol field (so "y" will override "yy", "yyy") +* If the field is not numeric, then override has no effect (like "MMM" will use abbreviation, not numerical field) +* +* @param fields the fields to set +* @param fmt The formatter to set. +* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers. +* @param status error code passed around (memory allocation or invalid fields) +* @see udat_getNumberFormatForField +* @stable ICU 54 +*/ +U_CAPI void U_EXPORT2 +udat_adoptNumberFormatForFields( UDateFormat* fmt, + const UChar* fields, + UNumberFormat* numberFormatToSet, + UErrorCode* status); +/** +* Set the UNumberFormat associated with an UDateFormat. +* A UDateFormat uses a UNumberFormat to format numbers within a date, +* for example the day number. +* This method also clears per field NumberFormat instances previously +* set by {@see udat_setNumberFormatForField} +* @param fmt The formatter to set. +* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers. +* @see udat_getNumberFormat +* @see udat_setNumberFormatForField +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_setNumberFormat( UDateFormat* fmt, + const UNumberFormat* numberFormatToSet); +/** +* Adopt the UNumberFormat associated with an UDateFormat. +* A UDateFormat uses a UNumberFormat to format numbers within a date, +* for example the day number. +* @param fmt The formatter to set. +* @param numberFormatToAdopt A pointer to the UNumberFormat to be used by fmt to format numbers. +* @see udat_getNumberFormat +* @stable ICU 54 +*/ +U_CAPI void U_EXPORT2 +udat_adoptNumberFormat( UDateFormat* fmt, + UNumberFormat* numberFormatToAdopt); +/** +* Get a locale for which date/time formatting patterns are available. +* A UDateFormat in a locale returned by this function will perform the correct +* formatting and parsing for the locale. +* @param localeIndex The index of the desired locale. +* @return A locale for which date/time formatting patterns are available, or 0 if none. +* @see udat_countAvailable +* @stable ICU 2.0 +*/ +U_CAPI const char* U_EXPORT2 +udat_getAvailable(int32_t localeIndex); + +/** +* Determine how many locales have date/time formatting patterns available. +* This function is most useful as determining the loop ending condition for +* calls to {@link #udat_getAvailable }. +* @return The number of locales for which date/time formatting patterns are available. +* @see udat_getAvailable +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +udat_countAvailable(void); + +/** +* Get the year relative to which all 2-digit years are interpreted. +* For example, if the 2-digit start year is 2100, the year 99 will be +* interpreted as 2199. +* @param fmt The formatter to query. +* @param status A pointer to an UErrorCode to receive any errors +* @return The year relative to which all 2-digit years are interpreted. +* @see udat_Set2DigitYearStart +* @stable ICU 2.0 +*/ +U_CAPI UDate U_EXPORT2 +udat_get2DigitYearStart( const UDateFormat *fmt, + UErrorCode *status); + +/** +* Set the year relative to which all 2-digit years will be interpreted. +* For example, if the 2-digit start year is 2100, the year 99 will be +* interpreted as 2199. +* @param fmt The formatter to set. +* @param d The year relative to which all 2-digit years will be interpreted. +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_Set2DigitYearStart +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_set2DigitYearStart( UDateFormat *fmt, + UDate d, + UErrorCode *status); + +/** +* Extract the pattern from a UDateFormat. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param localized true if the pattern should be localized, false otherwise. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPattern +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +udat_toPattern( const UDateFormat *fmt, + UBool localized, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Set the pattern used by an UDateFormat. +* The pattern should follow the pattern syntax rules. +* @param format The formatter to set. +* @param localized true if the pattern is localized, false otherwise. +* @param pattern The new pattern +* @param patternLength The length of pattern, or -1 if null-terminated. +* @see udat_toPattern +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_applyPattern( UDateFormat *format, + UBool localized, + const UChar *pattern, + int32_t patternLength); + +/** + * The possible types of date format symbols + * @stable ICU 2.6 + */ +typedef enum UDateFormatSymbolType { + /** The era names, for example AD */ + UDAT_ERAS, + /** The month names, for example February */ + UDAT_MONTHS, + /** The short month names, for example Feb. */ + UDAT_SHORT_MONTHS, + /** The CLDR-style format "wide" weekday names, for example Monday */ + UDAT_WEEKDAYS, + /** + * The CLDR-style format "abbreviated" (not "short") weekday names, for example "Mon." + * For the CLDR-style format "short" weekday names, use UDAT_SHORTER_WEEKDAYS. + */ + UDAT_SHORT_WEEKDAYS, + /** The AM/PM names, for example AM */ + UDAT_AM_PMS, + /** The localized characters */ + UDAT_LOCALIZED_CHARS, + /** The long era names, for example Anno Domini */ + UDAT_ERA_NAMES, + /** The narrow month names, for example F */ + UDAT_NARROW_MONTHS, + /** The CLDR-style format "narrow" weekday names, for example "M" */ + UDAT_NARROW_WEEKDAYS, + /** Standalone context versions of months */ + UDAT_STANDALONE_MONTHS, + UDAT_STANDALONE_SHORT_MONTHS, + UDAT_STANDALONE_NARROW_MONTHS, + /** The CLDR-style stand-alone "wide" weekday names */ + UDAT_STANDALONE_WEEKDAYS, + /** + * The CLDR-style stand-alone "abbreviated" (not "short") weekday names. + * For the CLDR-style stand-alone "short" weekday names, use UDAT_STANDALONE_SHORTER_WEEKDAYS. + */ + UDAT_STANDALONE_SHORT_WEEKDAYS, + /** The CLDR-style stand-alone "narrow" weekday names */ + UDAT_STANDALONE_NARROW_WEEKDAYS, + /** The quarters, for example 1st Quarter */ + UDAT_QUARTERS, + /** The short quarter names, for example Q1 */ + UDAT_SHORT_QUARTERS, + /** Standalone context versions of quarters */ + UDAT_STANDALONE_QUARTERS, + UDAT_STANDALONE_SHORT_QUARTERS, + /** + * The CLDR-style short weekday names, e.g. "Su", Mo", etc. + * These are named "SHORTER" to contrast with the constants using _SHORT_ + * above, which actually get the CLDR-style *abbreviated* versions of the + * corresponding names. + * @stable ICU 51 + */ + UDAT_SHORTER_WEEKDAYS, + /** + * Standalone version of UDAT_SHORTER_WEEKDAYS. + * @stable ICU 51 + */ + UDAT_STANDALONE_SHORTER_WEEKDAYS, + /** + * Cyclic year names (only supported for some calendars, and only for FORMAT usage; + * udat_setSymbols not supported for UDAT_CYCLIC_YEARS_WIDE) + * @stable ICU 54 + */ + UDAT_CYCLIC_YEARS_WIDE, + /** + * Cyclic year names (only supported for some calendars, and only for FORMAT usage) + * @stable ICU 54 + */ + UDAT_CYCLIC_YEARS_ABBREVIATED, + /** + * Cyclic year names (only supported for some calendars, and only for FORMAT usage; + * udat_setSymbols not supported for UDAT_CYCLIC_YEARS_NARROW) + * @stable ICU 54 + */ + UDAT_CYCLIC_YEARS_NARROW, + /** + * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage; + * udat_setSymbols not supported for UDAT_ZODIAC_NAMES_WIDE) + * @stable ICU 54 + */ + UDAT_ZODIAC_NAMES_WIDE, + /** + * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage) + * @stable ICU 54 + */ + UDAT_ZODIAC_NAMES_ABBREVIATED, + /** + * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage; + * udat_setSymbols not supported for UDAT_ZODIAC_NAMES_NARROW) + * @stable ICU 54 + */ + UDAT_ZODIAC_NAMES_NARROW, + + /** + * The narrow quarter names, for example 1 + * @stable ICU 70 + */ + UDAT_NARROW_QUARTERS, + + /** + * The narrow standalone quarter names, for example 1 + * @stable ICU 70 + */ + UDAT_STANDALONE_NARROW_QUARTERS +} UDateFormatSymbolType; + +struct UDateFormatSymbols; +/** Date format symbols. + * For usage in C programs. + * @stable ICU 2.6 + */ +typedef struct UDateFormatSymbols UDateFormatSymbols; + +/** +* Get the symbols associated with an UDateFormat. +* The symbols are what a UDateFormat uses to represent locale-specific data, +* for example month or day names. +* @param fmt The formatter to query. +* @param type The type of symbols to get. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @param symbolIndex The desired symbol of type type. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to an UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_countSymbols +* @see udat_setSymbols +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +udat_getSymbols(const UDateFormat *fmt, + UDateFormatSymbolType type, + int32_t symbolIndex, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Count the number of particular symbols for an UDateFormat. +* This function is most useful as for determining the loop termination condition +* for calls to {@link #udat_getSymbols }. +* @param fmt The formatter to query. +* @param type The type of symbols to count. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @return The number of symbols of type type. +* @see udat_getSymbols +* @see udat_setSymbols +* @stable ICU 2.0 +*/ +U_CAPI int32_t U_EXPORT2 +udat_countSymbols( const UDateFormat *fmt, + UDateFormatSymbolType type); + +/** +* Set the symbols associated with an UDateFormat. +* The symbols are what a UDateFormat uses to represent locale-specific data, +* for example month or day names. +* @param format The formatter to set +* @param type The type of symbols to set. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, +* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS +* @param symbolIndex The index of the symbol to set of type type. +* @param value The new value +* @param valueLength The length of value, or -1 if null-terminated +* @param status A pointer to an UErrorCode to receive any errors +* @see udat_getSymbols +* @see udat_countSymbols +* @stable ICU 2.0 +*/ +U_CAPI void U_EXPORT2 +udat_setSymbols( UDateFormat *format, + UDateFormatSymbolType type, + int32_t symbolIndex, + UChar *value, + int32_t valueLength, + UErrorCode *status); + +/** + * Get the locale for this date format object. + * You can choose between valid and actual locale. + * @param fmt The formatter to get the locale from + * @param type type of the locale we're looking for (valid or actual) + * @param status error code for the operation + * @return the locale name + * @stable ICU 2.8 + */ +U_CAPI const char* U_EXPORT2 +udat_getLocaleByType(const UDateFormat *fmt, + ULocDataLocaleType type, + UErrorCode* status); + +/** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. + * @param fmt The formatter for which to set a UDisplayContext value. + * @param value The UDisplayContext value to set. + * @param status A pointer to an UErrorCode to receive any errors + * @stable ICU 51 + */ +U_CAPI void U_EXPORT2 +udat_setContext(UDateFormat* fmt, UDisplayContext value, UErrorCode* status); + +/** + * Get the formatter's UDisplayContext value for the specified UDisplayContextType, + * such as UDISPCTX_TYPE_CAPITALIZATION. + * @param fmt The formatter to query. + * @param type The UDisplayContextType whose value to return + * @param status A pointer to an UErrorCode to receive any errors + * @return The UDisplayContextValue for the specified type. + * @stable ICU 53 + */ +U_CAPI UDisplayContext U_EXPORT2 +udat_getContext(const UDateFormat* fmt, UDisplayContextType type, UErrorCode* status); + +#ifndef U_HIDE_INTERNAL_API +/** +* Extract the date pattern from a UDateFormat set for relative date formatting. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to a UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPatternRelative +* @internal ICU 4.2 technology preview +*/ +U_CAPI int32_t U_EXPORT2 +udat_toPatternRelativeDate(const UDateFormat *fmt, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Extract the time pattern from a UDateFormat set for relative date formatting. +* The pattern will follow the pattern syntax rules. +* @param fmt The formatter to query. +* @param result A pointer to a buffer to receive the pattern. +* @param resultLength The maximum size of result. +* @param status A pointer to a UErrorCode to receive any errors +* @return The total buffer size needed; if greater than resultLength, the output was truncated. +* @see udat_applyPatternRelative +* @internal ICU 4.2 technology preview +*/ +U_CAPI int32_t U_EXPORT2 +udat_toPatternRelativeTime(const UDateFormat *fmt, + UChar *result, + int32_t resultLength, + UErrorCode *status); + +/** +* Set the date & time patterns used by a UDateFormat set for relative date formatting. +* The patterns should follow the pattern syntax rules. +* @param format The formatter to set. +* @param datePattern The new date pattern +* @param datePatternLength The length of datePattern, or -1 if null-terminated. +* @param timePattern The new time pattern +* @param timePatternLength The length of timePattern, or -1 if null-terminated. +* @param status A pointer to a UErrorCode to receive any errors +* @see udat_toPatternRelativeDate, udat_toPatternRelativeTime +* @internal ICU 4.2 technology preview +*/ +U_CAPI void U_EXPORT2 +udat_applyPatternRelative(UDateFormat *format, + const UChar *datePattern, + int32_t datePatternLength, + const UChar *timePattern, + int32_t timePatternLength, + UErrorCode *status); + +/** + * @internal + * @see udat_open + */ +typedef UDateFormat* (U_EXPORT2 *UDateFormatOpener) (UDateFormatStyle timeStyle, + UDateFormatStyle dateStyle, + const char *locale, + const UChar *tzID, + int32_t tzIDLength, + const UChar *pattern, + int32_t patternLength, + UErrorCode *status); + +/** + * Register a provider factory + * @internal ICU 49 + */ +U_CAPI void U_EXPORT2 +udat_registerOpener(UDateFormatOpener opener, UErrorCode *status); + +/** + * Un-Register a provider factory + * @internal ICU 49 + */ +U_CAPI UDateFormatOpener U_EXPORT2 +udat_unregisterOpener(UDateFormatOpener opener, UErrorCode *status); +#endif /* U_HIDE_INTERNAL_API */ + + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udata.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udata.h new file mode 100644 index 0000000000000000000000000000000000000000..4cda255010ad07a8993653b7e03f5ef95f5a6e66 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udata.h @@ -0,0 +1,440 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1999-2014, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* file name: udata.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 1999oct25 +* created by: Markus W. Scherer +*/ + +#ifndef __UDATA_H__ +#define __UDATA_H__ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +U_CDECL_BEGIN + +/** + * \file + * \brief C API: Data loading interface + * + *

Information about data loading interface

+ * + * This API is used to find and efficiently load data for ICU and applications + * using ICU. It provides an abstract interface that specifies a data type and + * name to find and load the data. Normally this API is used by other ICU APIs + * to load required data out of the ICU data library, but it can be used to + * load data out of other places. + * + * See the User Guide Data Management chapter. + */ + +#ifndef U_HIDE_INTERNAL_API +/** + * Character used to separate package names from tree names + * @internal ICU 3.0 + */ +#define U_TREE_SEPARATOR '-' + +/** + * String used to separate package names from tree names + * @internal ICU 3.0 + */ +#define U_TREE_SEPARATOR_STRING "-" + +/** + * Character used to separate parts of entry names + * @internal ICU 3.0 + */ +#define U_TREE_ENTRY_SEP_CHAR '/' + +/** + * String used to separate parts of entry names + * @internal ICU 3.0 + */ +#define U_TREE_ENTRY_SEP_STRING "/" + +/** + * Alias for standard ICU data + * @internal ICU 3.0 + */ +#define U_ICUDATA_ALIAS "ICUDATA" + +#endif /* U_HIDE_INTERNAL_API */ + +/** + * UDataInfo contains the properties about the requested data. + * This is meta data. + * + *

This structure may grow in the future, indicated by the + * size field.

+ * + *

ICU data must be at least 8-aligned, and should be 16-aligned. + * The UDataInfo struct begins 4 bytes after the start of the data item, + * so it is 4-aligned. + * + *

The platform data property fields help determine if a data + * file can be efficiently used on a given machine. + * The particular fields are of importance only if the data + * is affected by the properties - if there is integer data + * with word sizes > 1 byte, char* text, or UChar* text.

+ * + *

The implementation for the udata_open[Choice]() + * functions may reject data based on the value in isBigEndian. + * No other field is used by the udata API implementation.

+ * + *

The dataFormat may be used to identify + * the kind of data, e.g. a converter table.

+ * + *

The formatVersion field should be used to + * make sure that the format can be interpreted. + * It may be a good idea to check only for the one or two highest + * of the version elements to allow the data memory to + * get more or somewhat rearranged contents, for as long + * as the using code can still interpret the older contents.

+ * + *

The dataVersion field is intended to be a + * common place to store the source version of the data; + * for data from the Unicode character database, this could + * reflect the Unicode version.

+ * + * @stable ICU 2.0 + */ +typedef struct { + /** sizeof(UDataInfo) + * @stable ICU 2.0 */ + uint16_t size; + + /** unused, set to 0 + * @stable ICU 2.0*/ + uint16_t reservedWord; + + /* platform data properties */ + /** 0 for little-endian machine, 1 for big-endian + * @stable ICU 2.0 */ + uint8_t isBigEndian; + + /** see U_CHARSET_FAMILY values in utypes.h + * @stable ICU 2.0*/ + uint8_t charsetFamily; + + /** sizeof(UChar), one of { 1, 2, 4 } + * @stable ICU 2.0*/ + uint8_t sizeofUChar; + + /** unused, set to 0 + * @stable ICU 2.0*/ + uint8_t reservedByte; + + /** data format identifier + * @stable ICU 2.0*/ + uint8_t dataFormat[4]; + + /** versions: [0] major [1] minor [2] milli [3] micro + * @stable ICU 2.0*/ + uint8_t formatVersion[4]; + + /** versions: [0] major [1] minor [2] milli [3] micro + * @stable ICU 2.0*/ + uint8_t dataVersion[4]; +} UDataInfo; + +/* API for reading data -----------------------------------------------------*/ + +/** + * Forward declaration of the data memory type. + * @stable ICU 2.0 + */ +typedef struct UDataMemory UDataMemory; + +/** + * Callback function for udata_openChoice(). + * @param context parameter passed into udata_openChoice(). + * @param type The type of the data as passed into udata_openChoice(). + * It may be NULL. + * @param name The name of the data as passed into udata_openChoice(). + * @param pInfo A pointer to the UDataInfo structure + * of data that has been loaded and will be returned + * by udata_openChoice() if this function + * returns true. + * @return true if the current data memory is acceptable + * @stable ICU 2.0 + */ +typedef UBool U_CALLCONV +UDataMemoryIsAcceptable(void *context, + const char *type, const char *name, + const UDataInfo *pInfo); + + +/** + * Convenience function. + * This function works the same as udata_openChoice + * except that any data that matches the type and name + * is assumed to be acceptable. + * @param path Specifies an absolute path and/or a basename for the + * finding of the data in the file system. + * NULL for ICU data. + * @param type A string that specifies the type of data to be loaded. + * For example, resource bundles are loaded with type "res", + * conversion tables with type "cnv". + * This may be NULL or empty. + * @param name A string that specifies the name of the data. + * @param pErrorCode An ICU UErrorCode parameter. It must not be NULL. + * @return A pointer (handle) to a data memory object, or NULL + * if an error occurs. Call udata_getMemory() + * to get a pointer to the actual data. + * + * @see udata_openChoice + * @stable ICU 2.0 + */ +U_CAPI UDataMemory * U_EXPORT2 +udata_open(const char *path, const char *type, const char *name, + UErrorCode *pErrorCode); + +/** + * Data loading function. + * This function is used to find and load efficiently data for + * ICU and applications using ICU. + * It provides an abstract interface that allows to specify a data + * type and name to find and load the data. + * + *

The implementation depends on platform properties and user preferences + * and may involve loading shared libraries (DLLs), mapping + * files into memory, or fopen()/fread() files. + * It may also involve using static memory or database queries etc. + * Several or all data items may be combined into one entity + * (DLL, memory-mappable file).

+ * + *

The data is always preceded by a header that includes + * a UDataInfo structure. + * The caller's isAcceptable() function is called to make + * sure that the data is useful. It may be called several times if it + * rejects the data and there is more than one location with data + * matching the type and name.

+ * + *

If path==NULL, then ICU data is loaded. + * Otherwise, it is separated into a basename and a basename-less directory string. + * The basename is used as the data package name, and the directory is + * logically prepended to the ICU data directory string.

+ * + *

For details about ICU data loading see the User Guide + * Data Management chapter. (https://unicode-org.github.io/icu/userguide/icu_data/)

+ * + * @param path Specifies an absolute path and/or a basename for the + * finding of the data in the file system. + * NULL for ICU data. + * @param type A string that specifies the type of data to be loaded. + * For example, resource bundles are loaded with type "res", + * conversion tables with type "cnv". + * This may be NULL or empty. + * @param name A string that specifies the name of the data. + * @param isAcceptable This function is called to verify that loaded data + * is useful for the client code. If it returns false + * for all data items, then udata_openChoice() + * will return with an error. + * @param context Arbitrary parameter to be passed into isAcceptable. + * @param pErrorCode An ICU UErrorCode parameter. It must not be NULL. + * @return A pointer (handle) to a data memory object, or NULL + * if an error occurs. Call udata_getMemory() + * to get a pointer to the actual data. + * @stable ICU 2.0 + */ +U_CAPI UDataMemory * U_EXPORT2 +udata_openChoice(const char *path, const char *type, const char *name, + UDataMemoryIsAcceptable *isAcceptable, void *context, + UErrorCode *pErrorCode); + +/** + * Close the data memory. + * This function must be called to allow the system to + * release resources associated with this data memory. + * @param pData The pointer to data memory object + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +udata_close(UDataMemory *pData); + +/** + * Get the pointer to the actual data inside the data memory. + * The data is read-only. + * + * ICU data must be at least 8-aligned, and should be 16-aligned. + * + * @param pData The pointer to data memory object + * @stable ICU 2.0 + */ +U_CAPI const void * U_EXPORT2 +udata_getMemory(UDataMemory *pData); + +/** + * Get the information from the data memory header. + * This allows to get access to the header containing + * platform data properties etc. which is not part of + * the data itself and can therefore not be accessed + * via the pointer that udata_getMemory() returns. + * + * @param pData pointer to the data memory object + * @param pInfo pointer to a UDataInfo object; + * its size field must be set correctly, + * typically to sizeof(UDataInfo). + * + * *pInfo will be filled with the UDataInfo structure + * in the data memory object. If this structure is smaller than + * pInfo->size, then the size will be + * adjusted and only part of the structure will be filled. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +udata_getInfo(UDataMemory *pData, UDataInfo *pInfo); + +/** + * This function bypasses the normal ICU data loading process and + * allows you to force ICU's system data to come out of a user-specified + * area in memory. + * + * ICU data must be at least 8-aligned, and should be 16-aligned. + * See https://unicode-org.github.io/icu/userguide/icu_data + * + * The format of this data is that of the icu common data file, as is + * generated by the pkgdata tool with mode=common or mode=dll. + * You can read in a whole common mode file and pass the address to the start of the + * data, or (with the appropriate link options) pass in the pointer to + * the data that has been loaded from a dll by the operating system, + * as shown in this code: + * + * extern const char U_IMPORT U_ICUDATA_ENTRY_POINT []; + * // U_ICUDATA_ENTRY_POINT is same as entry point specified to pkgdata tool + * UErrorCode status = U_ZERO_ERROR; + * + * udata_setCommonData(&U_ICUDATA_ENTRY_POINT, &status); + * + * It is important that the declaration be as above. The entry point + * must not be declared as an extern void*. + * + * Starting with ICU 4.4, it is possible to set several data packages, + * one per call to this function. + * udata_open() will look for data in the multiple data packages in the order + * in which they were set. + * The position of the linked-in or default-name ICU .data package in the + * search list depends on when the first data item is loaded that is not contained + * in the already explicitly set packages. + * If data was loaded implicitly before the first call to this function + * (for example, via opening a converter, constructing a UnicodeString + * from default-codepage data, using formatting or collation APIs, etc.), + * then the default data will be first in the list. + * + * This function has no effect on application (non ICU) data. See udata_setAppData() + * for similar functionality for application data. + * + * @param data pointer to ICU common data + * @param err outgoing error status U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +udata_setCommonData(const void *data, UErrorCode *err); + + +/** + * This function bypasses the normal ICU data loading process for application-specific + * data and allows you to force the it to come out of a user-specified + * pointer. + * + * ICU data must be at least 8-aligned, and should be 16-aligned. + * See https://unicode-org.github.io/icu/userguide/icu_data + * + * The format of this data is that of the icu common data file, like 'icudt26l.dat' + * or the corresponding shared library (DLL) file. + * The application must read in or otherwise construct an image of the data and then + * pass the address of it to this function. + * + * + * Warning: setAppData will set a U_USING_DEFAULT_WARNING code if + * data with the specified path that has already been opened, or + * if setAppData with the same path has already been called. + * Any such calls to setAppData will have no effect. + * + * + * @param packageName the package name by which the application will refer + * to (open) this data + * @param data pointer to the data + * @param err outgoing error status U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR + * @see udata_setCommonData + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +udata_setAppData(const char *packageName, const void *data, UErrorCode *err); + +/** + * Possible settings for udata_setFileAccess() + * @see udata_setFileAccess + * @stable ICU 3.4 + */ +typedef enum UDataFileAccess { + /** ICU looks for data in single files first, then in packages. (default) @stable ICU 3.4 */ + UDATA_FILES_FIRST, + /** An alias for the default access mode. @stable ICU 3.4 */ + UDATA_DEFAULT_ACCESS = UDATA_FILES_FIRST, + /** ICU only loads data from packages, not from single files. @stable ICU 3.4 */ + UDATA_ONLY_PACKAGES, + /** ICU loads data from packages first, and only from single files + if the data cannot be found in a package. @stable ICU 3.4 */ + UDATA_PACKAGES_FIRST, + /** ICU does not access the file system for data loading. @stable ICU 3.4 */ + UDATA_NO_FILES, +#ifndef U_HIDE_DEPRECATED_API + /** + * Number of real UDataFileAccess values. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDATA_FILE_ACCESS_COUNT +#endif // U_HIDE_DEPRECATED_API +} UDataFileAccess; + +/** + * This function may be called to control how ICU loads data. It must be called + * before any ICU data is loaded, including application data loaded with + * ures/ResourceBundle or udata APIs. This function is not multithread safe. + * The results of calling it while other threads are loading data are undefined. + * @param access The type of file access to be used + * @param status Error code. + * @see UDataFileAccess + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +udata_setFileAccess(UDataFileAccess access, UErrorCode *status); + +U_CDECL_END + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDataMemoryPointer + * "Smart pointer" class, closes a UDataMemory via udata_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDataMemoryPointer, UDataMemory, udata_close); + +U_NAMESPACE_END + +#endif // U_SHOW_CPLUSPLUS_API + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udateintervalformat.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udateintervalformat.h new file mode 100644 index 0000000000000000000000000000000000000000..8439444d07961be17c56e44d284a523475ac6103 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udateintervalformat.h @@ -0,0 +1,332 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************************** +* Copyright (C) 2010-2012,2015 International Business Machines +* Corporation and others. All Rights Reserved. +***************************************************************************************** +*/ + +#ifndef UDATEINTERVALFORMAT_H +#define UDATEINTERVALFORMAT_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/ucal.h" +#include "unicode/umisc.h" +#include "unicode/uformattedvalue.h" +#include "unicode/udisplaycontext.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Format a date interval. + * + * A UDateIntervalFormat is used to format the range between two UDate values + * in a locale-sensitive way, using a skeleton that specifies the precision and + * completeness of the information to show. If the range smaller than the resolution + * specified by the skeleton, a single date format will be produced. If the range + * is larger than the format specified by the skeleton, a locale-specific fallback + * will be used to format the items missing from the skeleton. + * + * For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours) + * - The skeleton jm will produce + * for en_US, "7:56 AM - 7:56 PM" + * for en_GB, "7:56 - 19:56" + * - The skeleton MMMd will produce + * for en_US, "Mar 4" + * for en_GB, "4 Mar" + * If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes) + * - The skeleton jm will produce + * for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM" + * for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11" + * - The skeleton MMMd will produce + * for en_US, "Mar 4-8" + * for en_GB, "4-8 Mar" + * + * Note: the "-" characters in the above sample output will actually be + * Unicode 2013, EN_DASH, in all but the last example. + * + * Note, in ICU 4.4 the standard skeletons for which date interval format data + * is usually available are as follows; best results will be obtained by using + * skeletons from this set, or those formed by combining these standard skeletons + * (note that for these skeletons, the length of digit field such as d, y, or + * M vs MM is irrelevant (but for non-digit fields such as MMM vs MMMM it is + * relevant). Note that a skeleton involving h or H generally explicitly requests + * that time style (12- or 24-hour time respectively). For a skeleton that + * requests the locale's default time style (h or H), use 'j' instead of h or H. + * h, H, hm, Hm, + * hv, Hv, hmv, Hmv, + * d, + * M, MMM, MMMM, + * Md, MMMd, + * MEd, MMMEd, + * y, + * yM, yMMM, yMMMM, + * yMd, yMMMd, + * yMEd, yMMMEd + * + * Locales for which ICU 4.4 seems to have a reasonable amount of this data + * include: + * af, am, ar, be, bg, bn, ca, cs, da, de (_AT), el, en (_AU,_CA,_GB,_IE,_IN...), + * eo, es (_AR,_CL,_CO,...,_US) et, fa, fi, fo, fr (_BE,_CH,_CA), fur, gsw, he, + * hr, hu, hy, is, it (_CH), ja, kk, km, ko, lt, lv, mk, ml, mt, nb, nl )_BE), + * nn, pl, pt (_PT), rm, ro, ru (_UA), sk, sl, so, sq, sr, sr_Latn, sv, th, to, + * tr, uk, ur, vi, zh (_SG), zh_Hant (_HK,_MO) + */ + +/** + * Opaque UDateIntervalFormat object for use in C programs. + * @stable ICU 4.8 + */ +struct UDateIntervalFormat; +typedef struct UDateIntervalFormat UDateIntervalFormat; /**< C typedef for struct UDateIntervalFormat. @stable ICU 4.8 */ + +struct UFormattedDateInterval; +/** + * Opaque struct to contain the results of a UDateIntervalFormat operation. + * @stable ICU 64 + */ +typedef struct UFormattedDateInterval UFormattedDateInterval; + +/** + * Open a new UDateIntervalFormat object using the predefined rules for a + * given locale plus a specified skeleton. + * @param locale + * The locale for whose rules should be used; may be NULL for + * default locale. + * @param skeleton + * A pattern containing only the fields desired for the interval + * format, for example "Hm", "yMMMd", or "yMMMEdHm". + * @param skeletonLength + * The length of skeleton; may be -1 if the skeleton is zero-terminated. + * @param tzID + * A timezone ID specifying the timezone to use. If 0, use the default + * timezone. + * @param tzIDLength + * The length of tzID, or -1 if null-terminated. If 0, use the default + * timezone. + * @param status + * A pointer to a UErrorCode to receive any errors. + * @return + * A pointer to a UDateIntervalFormat object for the specified locale, + * or NULL if an error occurred. + * @stable ICU 4.8 + */ +U_CAPI UDateIntervalFormat* U_EXPORT2 +udtitvfmt_open(const char* locale, + const UChar* skeleton, + int32_t skeletonLength, + const UChar* tzID, + int32_t tzIDLength, + UErrorCode* status); + +/** + * Close a UDateIntervalFormat object. Once closed it may no longer be used. + * @param formatter + * The UDateIntervalFormat object to close. + * @stable ICU 4.8 + */ +U_CAPI void U_EXPORT2 +udtitvfmt_close(UDateIntervalFormat *formatter); + +/** + * Creates an object to hold the result of a UDateIntervalFormat + * operation. The object can be used repeatedly; it is cleared whenever + * passed to a format function. + * + * @param ec Set if an error occurs. + * @return A pointer needing ownership. + * @stable ICU 64 + */ +U_CAPI UFormattedDateInterval* U_EXPORT2 +udtitvfmt_openResult(UErrorCode* ec); + +/** + * Returns a representation of a UFormattedDateInterval as a UFormattedValue, + * which can be subsequently passed to any API requiring that type. + * + * The returned object is owned by the UFormattedDateInterval and is valid + * only as long as the UFormattedDateInterval is present and unchanged in memory. + * + * You can think of this method as a cast between types. + * + * When calling ufmtval_nextPosition(): + * The fields are returned from left to right. The special field category + * UFIELD_CATEGORY_DATE_INTERVAL_SPAN is used to indicate which datetime + * primitives came from which arguments: 0 means fromCalendar, and 1 means + * toCalendar. The span category will always occur before the + * corresponding fields in UFIELD_CATEGORY_DATE + * in the ufmtval_nextPosition() iterator. + * + * @param uresult The object containing the formatted string. + * @param ec Set if an error occurs. + * @return A UFormattedValue owned by the input object. + * @stable ICU 64 + */ +U_CAPI const UFormattedValue* U_EXPORT2 +udtitvfmt_resultAsValue(const UFormattedDateInterval* uresult, UErrorCode* ec); + +/** + * Releases the UFormattedDateInterval created by udtitvfmt_openResult(). + * + * @param uresult The object to release. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +udtitvfmt_closeResult(UFormattedDateInterval* uresult); + + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDateIntervalFormatPointer + * "Smart pointer" class, closes a UDateIntervalFormat via udtitvfmt_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.8 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateIntervalFormatPointer, UDateIntervalFormat, udtitvfmt_close); + +/** + * \class LocalUFormattedDateIntervalPointer + * "Smart pointer" class, closes a UFormattedDateInterval via udtitvfmt_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 64 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedDateIntervalPointer, UFormattedDateInterval, udtitvfmt_closeResult); + +U_NAMESPACE_END + +#endif + + +/** + * Formats a date/time range using the conventions established for the + * UDateIntervalFormat object. + * @param formatter + * The UDateIntervalFormat object specifying the format conventions. + * @param fromDate + * The starting point of the range. + * @param toDate + * The ending point of the range. + * @param result + * A pointer to a buffer to receive the formatted range. + * @param resultCapacity + * The maximum size of result. + * @param position + * A pointer to a UFieldPosition. On input, position->field is read. + * On output, position->beginIndex and position->endIndex indicate + * the beginning and ending indices of field number position->field, + * if such a field exists. This parameter may be NULL, in which case + * no field position data is returned. + * There may be multiple instances of a given field type in an + * interval format; in this case the position indices refer to the + * first instance. + * @param status + * A pointer to a UErrorCode to receive any errors. + * @return + * The total buffer size needed; if greater than resultLength, the + * output was truncated. + * @stable ICU 4.8 + */ +U_CAPI int32_t U_EXPORT2 +udtitvfmt_format(const UDateIntervalFormat* formatter, + UDate fromDate, + UDate toDate, + UChar* result, + int32_t resultCapacity, + UFieldPosition* position, + UErrorCode* status); + + +/** + * Formats a date/time range using the conventions established for the + * UDateIntervalFormat object. + * @param formatter + * The UDateIntervalFormat object specifying the format conventions. + * @param fromDate + * The starting point of the range. + * @param toDate + * The ending point of the range. + * @param result + * The UFormattedDateInterval to contain the result of the + * formatting operation. + * @param status + * A pointer to a UErrorCode to receive any errors. + * @stable ICU 67 + */ +U_CAPI void U_EXPORT2 +udtitvfmt_formatToResult( + const UDateIntervalFormat* formatter, + UDate fromDate, + UDate toDate, + UFormattedDateInterval* result, + UErrorCode* status); + +/** + * Formats a date/time range using the conventions established for the + * UDateIntervalFormat object. + * @param formatter + * The UDateIntervalFormat object specifying the format conventions. + * @param fromCalendar + * The starting point of the range. + * @param toCalendar + * The ending point of the range. + * @param result + * The UFormattedDateInterval to contain the result of the + * formatting operation. + * @param status + * A pointer to a UErrorCode to receive any errors. + * @stable ICU 67 + */ + +U_CAPI void U_EXPORT2 +udtitvfmt_formatCalendarToResult( + const UDateIntervalFormat* formatter, + UCalendar* fromCalendar, + UCalendar* toCalendar, + UFormattedDateInterval* result, + UErrorCode* status); + +/** + * Set a particular UDisplayContext value in the formatter, such as + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. This causes the formatted + * result to be capitalized appropriately for the context in which + * it is intended to be used, considering both the locale and the + * type of field at the beginning of the formatted result. + * @param formatter The formatter for which to set a UDisplayContext value. + * @param value The UDisplayContext value to set. + * @param status A pointer to an UErrorCode to receive any errors + * @stable ICU 68 + */ +U_CAPI void U_EXPORT2 +udtitvfmt_setContext(UDateIntervalFormat* formatter, UDisplayContext value, UErrorCode* status); + +/** + * Get the formatter's UDisplayContext value for the specified UDisplayContextType, + * such as UDISPCTX_TYPE_CAPITALIZATION. + * @param formatter The formatter to query. + * @param type The UDisplayContextType whose value to return + * @param status A pointer to an UErrorCode to receive any errors + * @return The UDisplayContextValue for the specified type. + * @stable ICU 68 + */ +U_CAPI UDisplayContext U_EXPORT2 +udtitvfmt_getContext(const UDateIntervalFormat* formatter, UDisplayContextType type, UErrorCode* status); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udatpg.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udatpg.h new file mode 100644 index 0000000000000000000000000000000000000000..1d3060350ec0f14896b46eabb93f3af675c598ab --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udatpg.h @@ -0,0 +1,751 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2007-2015, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: udatpg.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2007jul30 +* created by: Markus W. Scherer +*/ + +#ifndef __UDATPG_H__ +#define __UDATPG_H__ + +#include "unicode/utypes.h" +#include "unicode/udat.h" +#include "unicode/uenum.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Wrapper for icu::DateTimePatternGenerator (unicode/dtptngen.h). + * + * UDateTimePatternGenerator provides flexible generation of date format patterns, + * like "yy-MM-dd". The user can build up the generator by adding successive + * patterns. Once that is done, a query can be made using a "skeleton", which is + * a pattern which just includes the desired fields and lengths. The generator + * will return the "best fit" pattern corresponding to that skeleton. + *

The main method people will use is udatpg_getBestPattern, since normally + * UDateTimePatternGenerator is pre-built with data from a particular locale. + * However, generators can be built directly from other data as well. + *

Issue: may be useful to also have a function that returns the list of + * fields in a pattern, in order, since we have that internally. + * That would be useful for getting the UI order of field elements. + */ + +/** + * Opaque type for a date/time pattern generator object. + * @stable ICU 3.8 + */ +typedef void *UDateTimePatternGenerator; + +/** + * Field number constants for udatpg_getAppendItemFormats() and similar functions. + * These constants are separate from UDateFormatField despite semantic overlap + * because some fields are merged for the date/time pattern generator. + * @stable ICU 3.8 + */ +typedef enum UDateTimePatternField { + /** @stable ICU 3.8 */ + UDATPG_ERA_FIELD, + /** @stable ICU 3.8 */ + UDATPG_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_QUARTER_FIELD, + /** @stable ICU 3.8 */ + UDATPG_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEK_OF_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEK_OF_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_WEEKDAY_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_OF_YEAR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAY_FIELD, + /** @stable ICU 3.8 */ + UDATPG_DAYPERIOD_FIELD, + /** @stable ICU 3.8 */ + UDATPG_HOUR_FIELD, + /** @stable ICU 3.8 */ + UDATPG_MINUTE_FIELD, + /** @stable ICU 3.8 */ + UDATPG_SECOND_FIELD, + /** @stable ICU 3.8 */ + UDATPG_FRACTIONAL_SECOND_FIELD, + /** @stable ICU 3.8 */ + UDATPG_ZONE_FIELD, + + /* Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, + * it is needed for layout of DateTimePatternGenerator object. */ +#ifndef U_FORCE_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateTimePatternField value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDATPG_FIELD_COUNT +#endif // U_FORCE_HIDE_DEPRECATED_API +} UDateTimePatternField; + +/** + * Field display name width constants for udatpg_getFieldDisplayName(). + * @stable ICU 61 + */ +typedef enum UDateTimePGDisplayWidth { + /** @stable ICU 61 */ + UDATPG_WIDE, + /** @stable ICU 61 */ + UDATPG_ABBREVIATED, + /** @stable ICU 61 */ + UDATPG_NARROW +} UDateTimePGDisplayWidth; + +/** + * Masks to control forcing the length of specified fields in the returned + * pattern to match those in the skeleton (when this would not happen + * otherwise). These may be combined to force the length of multiple fields. + * Used with udatpg_getBestPatternWithOptions, udatpg_replaceFieldTypesWithOptions. + * @stable ICU 4.4 + */ +typedef enum UDateTimePatternMatchOptions { + /** @stable ICU 4.4 */ + UDATPG_MATCH_NO_OPTIONS = 0, + /** @stable ICU 4.4 */ + UDATPG_MATCH_HOUR_FIELD_LENGTH = 1 << UDATPG_HOUR_FIELD, +#ifndef U_HIDE_INTERNAL_API + /** @internal ICU 4.4 */ + UDATPG_MATCH_MINUTE_FIELD_LENGTH = 1 << UDATPG_MINUTE_FIELD, + /** @internal ICU 4.4 */ + UDATPG_MATCH_SECOND_FIELD_LENGTH = 1 << UDATPG_SECOND_FIELD, +#endif /* U_HIDE_INTERNAL_API */ + /** @stable ICU 4.4 */ + UDATPG_MATCH_ALL_FIELDS_LENGTH = (1 << UDATPG_FIELD_COUNT) - 1 +} UDateTimePatternMatchOptions; + +/** + * Status return values from udatpg_addPattern(). + * @stable ICU 3.8 + */ +typedef enum UDateTimePatternConflict { + /** @stable ICU 3.8 */ + UDATPG_NO_CONFLICT, + /** @stable ICU 3.8 */ + UDATPG_BASE_CONFLICT, + /** @stable ICU 3.8 */ + UDATPG_CONFLICT, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UDateTimePatternConflict value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UDATPG_CONFLICT_COUNT +#endif // U_HIDE_DEPRECATED_API +} UDateTimePatternConflict; + +/** + * Open a generator according to a given locale. + * @param locale + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_CAPI UDateTimePatternGenerator * U_EXPORT2 +udatpg_open(const char *locale, UErrorCode *pErrorCode); + +/** + * Open an empty generator, to be constructed with udatpg_addPattern(...) etc. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_CAPI UDateTimePatternGenerator * U_EXPORT2 +udatpg_openEmpty(UErrorCode *pErrorCode); + +/** + * Close a generator. + * @param dtpg a pointer to UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +udatpg_close(UDateTimePatternGenerator *dtpg); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUDateTimePatternGeneratorPointer + * "Smart pointer" class, closes a UDateTimePatternGenerator via udatpg_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateTimePatternGeneratorPointer, UDateTimePatternGenerator, udatpg_close); + +U_NAMESPACE_END + +#endif + +/** + * Create a copy pf a generator. + * @param dtpg a pointer to UDateTimePatternGenerator to be copied. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a pointer to a new UDateTimePatternGenerator. + * @stable ICU 3.8 + */ +U_CAPI UDateTimePatternGenerator * U_EXPORT2 +udatpg_clone(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Get the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param length the length of skeleton + * @param bestPattern + * The best pattern found from the given skeleton. + * @param capacity the capacity of bestPattern. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of bestPattern. + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_getBestPattern(UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t length, + UChar *bestPattern, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get the best pattern matching the input skeleton. It is guaranteed to + * have all of the fields in the skeleton. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * The skeleton is a pattern containing only the variable fields. + * For example, "MMMdd" and "mmhh" are skeletons. + * @param length the length of skeleton + * @param options + * Options for forcing the length of specified fields in the + * returned pattern to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param bestPattern + * The best pattern found from the given skeleton. + * @param capacity + * the capacity of bestPattern. + * @param pErrorCode + * a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of bestPattern. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_getBestPatternWithOptions(UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t length, + UDateTimePatternMatchOptions options, + UChar *bestPattern, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get a unique skeleton from a given pattern. For example, + * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param unusedDtpg a pointer to UDateTimePatternGenerator. + * This parameter is no longer used. Callers may pass NULL. + * @param pattern input pattern, such as "dd/MMM". + * @param length the length of pattern. + * @param skeleton such as "MMMdd" + * @param capacity the capacity of skeleton. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of skeleton. + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_getSkeleton(UDateTimePatternGenerator *unusedDtpg, + const UChar *pattern, int32_t length, + UChar *skeleton, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Get a unique base skeleton from a given pattern. This is the same + * as the skeleton, except that differences in length are minimized so + * as to only preserve the difference between string and numeric form. So + * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" + * (notice the single d). + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param unusedDtpg a pointer to UDateTimePatternGenerator. + * This parameter is no longer used. Callers may pass NULL. + * @param pattern input pattern, such as "dd/MMM". + * @param length the length of pattern. + * @param baseSkeleton such as "Md" + * @param capacity the capacity of base skeleton. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of baseSkeleton. + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_getBaseSkeleton(UDateTimePatternGenerator *unusedDtpg, + const UChar *pattern, int32_t length, + UChar *baseSkeleton, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * Adds a pattern to the generator. If the pattern has the same skeleton as + * an existing pattern, and the override parameter is set, then the previous + * value is overridden. Otherwise, the previous value is retained. In either + * case, the conflicting status is set and previous vale is stored in + * conflicting pattern. + *

+ * Note that single-field patterns (like "MMM") are automatically added, and + * don't need to be added explicitly! + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern input pattern, such as "dd/MMM" + * @param patternLength the length of pattern. + * @param override When existing values are to be overridden use true, + * otherwise use false. + * @param conflictingPattern Previous pattern with the same skeleton. + * @param capacity the capacity of conflictingPattern. + * @param pLength a pointer to the length of conflictingPattern. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return conflicting status. The value could be UDATPG_NO_CONFLICT, + * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. + * @stable ICU 3.8 + */ +U_CAPI UDateTimePatternConflict U_EXPORT2 +udatpg_addPattern(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + UBool override, + UChar *conflictingPattern, int32_t capacity, int32_t *pLength, + UErrorCode *pErrorCode); + +/** + * An AppendItem format is a pattern used to append a field if there is no + * good match. For example, suppose that the input skeleton is "GyyyyMMMd", + * and there is no matching pattern internally, but there is a pattern + * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the + * G. The way these two are conjoined is by using the AppendItemFormat for G + * (era). So if that value is, say "{0}, {1}" then the final resulting + * pattern is "d-MM-yyyy, G". + *

+ * There are actually three available variables: {0} is the pattern so far, + * {1} is the element we are adding, and {2} is the name of the element. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param value pattern, such as "{0}, {1}" + * @param length the length of value. + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +udatpg_setAppendItemFormat(UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + const UChar *value, int32_t length); + +/** + * Getter corresponding to setAppendItemFormat. Values below 0 or at or + * above UDATPG_FIELD_COUNT are illegal arguments. + * + * @param dtpg A pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param pLength A pointer that will receive the length of appendItemFormat. + * @return appendItemFormat for field. + * @stable ICU 3.8 + */ +U_CAPI const UChar * U_EXPORT2 +udatpg_getAppendItemFormat(const UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + int32_t *pLength); + +/** + * Set the name of field, eg "era" in English for ERA. These are only + * used if the corresponding AppendItemFormat is used, and if it contains a + * {2} variable. + *

+ * This reflects the way that the CLDR data is organized. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField + * @param value name for the field. + * @param length the length of value. + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +udatpg_setAppendItemName(UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + const UChar *value, int32_t length); + +/** + * Getter corresponding to setAppendItemNames. Values below 0 or at or above + * UDATPG_FIELD_COUNT are illegal arguments. Note: The more general function + * for getting date/time field display names is udatpg_getFieldDisplayName. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD + * @param pLength A pointer that will receive the length of the name for field. + * @return name for field + * @see udatpg_getFieldDisplayName + * @stable ICU 3.8 + */ +U_CAPI const UChar * U_EXPORT2 +udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + int32_t *pLength); + +/** + * The general interface to get a display name for a particular date/time field, + * in one of several possible display widths. + * + * @param dtpg + * A pointer to the UDateTimePatternGenerator object with the localized + * display names. + * @param field + * The desired UDateTimePatternField, such as UDATPG_ERA_FIELD. + * @param width + * The desired UDateTimePGDisplayWidth, such as UDATPG_ABBREVIATED. + * @param fieldName + * A pointer to a buffer to receive the NULL-terminated display name. If the name + * fits into fieldName but cannot be NULL-terminated (length == capacity) then + * the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the name doesn't + * fit into fieldName then the error code is set to U_BUFFER_OVERFLOW_ERROR. + * @param capacity + * The size of fieldName (in UChars). + * @param pErrorCode + * A pointer to a UErrorCode to receive any errors + * @return + * The full length of the name; if greater than capacity, fieldName contains a + * truncated result. + * @stable ICU 61 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_getFieldDisplayName(const UDateTimePatternGenerator *dtpg, + UDateTimePatternField field, + UDateTimePGDisplayWidth width, + UChar *fieldName, int32_t capacity, + UErrorCode *pErrorCode); + +/** + * The DateTimeFormat is a message format pattern used to compose date and + * time patterns. The default pattern in the root locale is "{1} {0}", where + * {1} will be replaced by the date pattern and {0} will be replaced by the + * time pattern; however, other locales may specify patterns such as + * "{1}, {0}" or "{1} 'at' {0}", etc. + *

+ * This is used when the input skeleton contains both date and time fields, + * but there is not a close match among the added patterns. For example, + * suppose that this object was created by adding "dd-MMM" and "hh:mm", and + * its DateTimeFormat is the default "{1} {0}". Then if the input skeleton + * is "MMMdhmm", there is not an exact match, so the input skeleton is + * broken up into two components "MMMd" and "hmm". There are close matches + * for those two skeletons, so the result is put together with this pattern, + * resulting in "d-MMM h:mm". + * + * There are four DateTimeFormats in a UDateTimePatternGenerator object, + * corresponding to date styles UDAT_FULL..UDAT_SHORT. This method sets + * all of them to the specified pattern. To set them individually, see + * udatpg_setDateTimeFormatForStyle. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param dtFormat + * message format pattern, here {1} will be replaced by the date + * pattern and {0} will be replaced by the time pattern. + * @param length the length of dtFormat. + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg, + const UChar *dtFormat, int32_t length); + +/** + * Getter corresponding to setDateTimeFormat. + * + * There are four DateTimeFormats in a UDateTimePatternGenerator object, + * corresponding to date styles UDAT_FULL..UDAT_SHORT. This method gets + * the style for UDAT_MEDIUM (the default). To get them individually, see + * udatpg_getDateTimeFormatForStyle. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pLength A pointer that will receive the length of the format + * @return dateTimeFormat. + * @stable ICU 3.8 + */ +U_CAPI const UChar * U_EXPORT2 +udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg, + int32_t *pLength); + +#if !UCONFIG_NO_FORMATTING +/** + * dateTimeFormats are message patterns used to compose combinations of date + * and time patterns. There are four length styles, corresponding to the + * inferred style of the date pattern; these are UDateFormatStyle values: + * - UDAT_FULL (for date pattern with weekday and long month), else + * - UDAT_LONG (for a date pattern with long month), else + * - UDAT_MEDIUM (for a date pattern with abbreviated month), else + * - UDAT_SHORT (for any other date pattern). + * For details on dateTimeFormats, see + * https://www.unicode.org/reports/tr35/tr35-dates.html#dateTimeFormats. + * The default pattern in the root locale for all styles is "{1} {0}". + * + * @param udtpg + * a pointer to the UDateTimePatternGenerator + * @param style + * one of UDAT_FULL..UDAT_SHORT. Error if out of range. + * @param dateTimeFormat + * the new dateTimeFormat to set for the the specified style + * @param length + * the length of dateTimeFormat, or -1 if unknown and pattern + * is null-terminated + * @param pErrorCode + * a pointer to the UErrorCode (in/out parameter); if no failure + * status is already set, it will be set according to result of the + * function (e.g. U_ILLEGAL_ARGUMENT_ERROR for style out of range). + * @stable ICU 71 + */ +U_CAPI void U_EXPORT2 +udatpg_setDateTimeFormatForStyle(UDateTimePatternGenerator *udtpg, + UDateFormatStyle style, + const UChar *dateTimeFormat, int32_t length, + UErrorCode *pErrorCode); + +/** + * Getter corresponding to udatpg_setDateTimeFormatForStyle. + * + * @param udtpg + * a pointer to the UDateTimePatternGenerator + * @param style + * one of UDAT_FULL..UDAT_SHORT. Error if out of range. + * @param pLength + * a pointer that will receive the length of the format. May be NULL + * if length is not desired. + * @param pErrorCode + * a pointer to the UErrorCode (in/out parameter); if no failure + * status is already set, it will be set according to result of the + * function (e.g. U_ILLEGAL_ARGUMENT_ERROR for style out of range). + * @return + * pointer to the current dateTimeFormat (0 terminated) for the specified + * style, or empty string in case of error. The pointer and its contents + * may no longer be valid if udatpg_setDateTimeFormat is called, or + * udatpg_setDateTimeFormatForStyle for the same style is called, or the + * UDateTimePatternGenerator object is closed. + * @stable ICU 71 + */ +U_CAPI const UChar* U_EXPORT2 +udatpg_getDateTimeFormatForStyle(const UDateTimePatternGenerator *udtpg, + UDateFormatStyle style, int32_t *pLength, + UErrorCode *pErrorCode); +#endif /* #if !UCONFIG_NO_FORMATTING */ + +/** + * The decimal value is used in formatting fractions of seconds. If the + * skeleton contains fractional seconds, then this is used with the + * fractional seconds. For example, suppose that the input pattern is + * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and + * the decimal string is ",". Then the resulting pattern is modified to be + * "H:mm:ss,SSSS" + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param decimal + * @param length the length of decimal. + * @stable ICU 3.8 + */ +U_CAPI void U_EXPORT2 +udatpg_setDecimal(UDateTimePatternGenerator *dtpg, + const UChar *decimal, int32_t length); + +/** + * Getter corresponding to setDecimal. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pLength A pointer that will receive the length of the decimal string. + * @return corresponding to the decimal point. + * @stable ICU 3.8 + */ +U_CAPI const UChar * U_EXPORT2 +udatpg_getDecimal(const UDateTimePatternGenerator *dtpg, + int32_t *pLength); + +/** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern Input pattern + * @param patternLength the length of input pattern. + * @param skeleton + * @param skeletonLength the length of input skeleton. + * @param dest pattern adjusted to match the skeleton fields widths and subtypes. + * @param destCapacity the capacity of dest. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of dest. + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_replaceFieldTypes(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + const UChar *skeleton, int32_t skeletonLength, + UChar *dest, int32_t destCapacity, + UErrorCode *pErrorCode); + +/** + * Adjusts the field types (width and subtype) of a pattern to match what is + * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a + * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be + * "dd-MMMM hh:mm". This is used internally to get the best match for the + * input skeleton, but can also be used externally. + * + * Note that this function uses a non-const UDateTimePatternGenerator: + * It uses a stateful pattern parser which is set up for each generator object, + * rather than creating one for each function call. + * Consecutive calls to this function do not affect each other, + * but this function cannot be used concurrently on a single generator object. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pattern Input pattern + * @param patternLength the length of input pattern. + * @param skeleton + * @param skeletonLength the length of input skeleton. + * @param options + * Options controlling whether the length of specified fields in the + * pattern are adjusted to match those in the skeleton (when this + * would not happen otherwise). For default behavior, use + * UDATPG_MATCH_NO_OPTIONS. + * @param dest pattern adjusted to match the skeleton fields widths and subtypes. + * @param destCapacity the capacity of dest. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return the length of dest. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +udatpg_replaceFieldTypesWithOptions(UDateTimePatternGenerator *dtpg, + const UChar *pattern, int32_t patternLength, + const UChar *skeleton, int32_t skeletonLength, + UDateTimePatternMatchOptions options, + UChar *dest, int32_t destCapacity, + UErrorCode *pErrorCode); + +/** + * Return a UEnumeration list of all the skeletons in canonical form. + * Call udatpg_getPatternForSkeleton() to get the corresponding pattern. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call + * @return a UEnumeration list of all the skeletons + * The caller must close the object. + * @stable ICU 3.8 + */ +U_CAPI UEnumeration * U_EXPORT2 +udatpg_openSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Return a UEnumeration list of all the base skeletons in canonical form. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. + * @return a UEnumeration list of all the base skeletons + * The caller must close the object. + * @stable ICU 3.8 + */ +U_CAPI UEnumeration * U_EXPORT2 +udatpg_openBaseSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); + +/** + * Get the pattern corresponding to a given skeleton. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param skeleton + * @param skeletonLength pointer to the length of skeleton. + * @param pLength pointer to the length of return pattern. + * @return pattern corresponding to a given skeleton. + * @stable ICU 3.8 + */ +U_CAPI const UChar * U_EXPORT2 +udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg, + const UChar *skeleton, int32_t skeletonLength, + int32_t *pLength); + +#if !UCONFIG_NO_FORMATTING + +/** + * Return the default hour cycle for a locale. Uses the locale that the + * UDateTimePatternGenerator was initially created with. + * + * Cannot be used on an empty UDateTimePatternGenerator instance. + * + * @param dtpg a pointer to UDateTimePatternGenerator. + * @param pErrorCode a pointer to the UErrorCode which must not indicate a + * failure before the function call. Set to U_UNSUPPORTED_ERROR + * if used on an empty instance. + * @return the default hour cycle. + * @stable ICU 67 + */ +U_CAPI UDateFormatHourCycle U_EXPORT2 +udatpg_getDefaultHourCycle(const UDateTimePatternGenerator *dtpg, UErrorCode* pErrorCode); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplaycontext.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplaycontext.h new file mode 100644 index 0000000000000000000000000000000000000000..6e1421798054f633bf39e4bc27077f12a241bcdf --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplaycontext.h @@ -0,0 +1,173 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************************** +* Copyright (C) 2014-2016, International Business Machines +* Corporation and others. All Rights Reserved. +***************************************************************************************** +*/ + +#ifndef UDISPLAYCONTEXT_H +#define UDISPLAYCONTEXT_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +/** + * \file + * \brief C API: Display context types (enum values) + */ + +/** + * Display context types, for getting values of a particular setting. + * Note, the specific numeric values are internal and may change. + * @stable ICU 51 + */ +enum UDisplayContextType { + /** + * Type to retrieve the dialect handling setting, e.g. + * UDISPCTX_STANDARD_NAMES or UDISPCTX_DIALECT_NAMES. + * @stable ICU 51 + */ + UDISPCTX_TYPE_DIALECT_HANDLING = 0, + /** + * Type to retrieve the capitalization context setting, e.g. + * UDISPCTX_CAPITALIZATION_NONE, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, + * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, etc. + * @stable ICU 51 + */ + UDISPCTX_TYPE_CAPITALIZATION = 1, + /** + * Type to retrieve the display length setting, e.g. + * UDISPCTX_LENGTH_FULL, UDISPCTX_LENGTH_SHORT. + * @stable ICU 54 + */ + UDISPCTX_TYPE_DISPLAY_LENGTH = 2, + /** + * Type to retrieve the substitute handling setting, e.g. + * UDISPCTX_SUBSTITUTE, UDISPCTX_NO_SUBSTITUTE. + * @stable ICU 58 + */ + UDISPCTX_TYPE_SUBSTITUTE_HANDLING = 3 +}; +/** +* @stable ICU 51 +*/ +typedef enum UDisplayContextType UDisplayContextType; + +/** + * Display context settings. + * Note, the specific numeric values are internal and may change. + * @stable ICU 51 + */ +enum UDisplayContext { + /** + * ================================ + * DIALECT_HANDLING can be set to one of UDISPCTX_STANDARD_NAMES or + * UDISPCTX_DIALECT_NAMES. Use UDisplayContextType UDISPCTX_TYPE_DIALECT_HANDLING + * to get the value. + */ + /** + * A possible setting for DIALECT_HANDLING: + * use standard names when generating a locale name, + * e.g. en_GB displays as 'English (United Kingdom)'. + * @stable ICU 51 + */ + UDISPCTX_STANDARD_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 0, + /** + * A possible setting for DIALECT_HANDLING: + * use dialect names, when generating a locale name, + * e.g. en_GB displays as 'British English'. + * @stable ICU 51 + */ + UDISPCTX_DIALECT_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 1, + /** + * ================================ + * CAPITALIZATION can be set to one of UDISPCTX_CAPITALIZATION_NONE, + * UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, + * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, + * UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, or + * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. + * Use UDisplayContextType UDISPCTX_TYPE_CAPITALIZATION to get the value. + */ + /** + * The capitalization context to be used is unknown (this is the default value). + * @stable ICU 51 + */ + UDISPCTX_CAPITALIZATION_NONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 0, + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for the middle of a sentence. + * @stable ICU 51 + */ + UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 1, + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for the beginning of a sentence. + * @stable ICU 51 + */ + UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 2, + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for a user-interface list or menu item. + * @stable ICU 51 + */ + UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 3, + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for stand-alone usage such as an + * isolated name on a calendar page. + * @stable ICU 51 + */ + UDISPCTX_CAPITALIZATION_FOR_STANDALONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 4, + /** + * ================================ + * DISPLAY_LENGTH can be set to one of UDISPCTX_LENGTH_FULL or + * UDISPCTX_LENGTH_SHORT. Use UDisplayContextType UDISPCTX_TYPE_DISPLAY_LENGTH + * to get the value. + */ + /** + * A possible setting for DISPLAY_LENGTH: + * use full names when generating a locale name, + * e.g. "United States" for US. + * @stable ICU 54 + */ + UDISPCTX_LENGTH_FULL = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 0, + /** + * A possible setting for DISPLAY_LENGTH: + * use short names when generating a locale name, + * e.g. "U.S." for US. + * @stable ICU 54 + */ + UDISPCTX_LENGTH_SHORT = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 1, + /** + * ================================ + * SUBSTITUTE_HANDLING can be set to one of UDISPCTX_SUBSTITUTE or + * UDISPCTX_NO_SUBSTITUTE. Use UDisplayContextType UDISPCTX_TYPE_SUBSTITUTE_HANDLING + * to get the value. + */ + /** + * A possible setting for SUBSTITUTE_HANDLING: + * Returns a fallback value (e.g., the input code) when no data is available. + * This is the default value. + * @stable ICU 58 + */ + UDISPCTX_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 0, + /** + * A possible setting for SUBSTITUTE_HANDLING: + * Returns a null value with error code set to U_ILLEGAL_ARGUMENT_ERROR when no + * data is available. + * @stable ICU 58 + */ + UDISPCTX_NO_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 1 + +}; +/** +* @stable ICU 51 +*/ +typedef enum UDisplayContext UDisplayContext; + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplayoptions.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplayoptions.h new file mode 100644 index 0000000000000000000000000000000000000000..1ecdf1d8e94463fd1b75f3f13690f466d0c4df2b --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/udisplayoptions.h @@ -0,0 +1,325 @@ +// © 2022 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __UDISPLAYOPTIONS_H__ +#define __UDISPLAYOPTIONS_H__ + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +/** + * \file + * \brief C API: Display options (enum types, values, helper functions) + * + * These display options are designed to be used in class DisplayOptions + * as a more modern version of the UDisplayContext mechanism. + */ + +#include "unicode/uversion.h" + +#ifndef U_HIDE_DRAFT_API + +/** + * Represents all the grammatical cases that are supported by CLDR. + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsGrammaticalCase { + /** + * A possible setting for GrammaticalCase. + * The grammatical case context to be used is unknown (this is the default value). + * @draft ICU 72 + */ + UDISPOPT_GRAMMATICAL_CASE_UNDEFINED = 0, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_ABLATIVE = 1, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_ACCUSATIVE = 2, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_COMITATIVE = 3, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_DATIVE = 4, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_ERGATIVE = 5, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_GENITIVE = 6, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_INSTRUMENTAL = 7, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_LOCATIVE = 8, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_LOCATIVE_COPULATIVE = 9, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_NOMINATIVE = 10, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_OBLIQUE = 11, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_PREPOSITIONAL = 12, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_SOCIATIVE = 13, + /** @draft ICU 72 */ + UDISPOPT_GRAMMATICAL_CASE_VOCATIVE = 14, +} UDisplayOptionsGrammaticalCase; + +/** + * @param grammaticalCase The grammatical case. + * @return the lowercase CLDR keyword string for the grammatical case. + * + * @draft ICU 72 + */ +U_CAPI const char * U_EXPORT2 +udispopt_getGrammaticalCaseIdentifier(UDisplayOptionsGrammaticalCase grammaticalCase); + +/** + * @param identifier in lower case such as "dative" or "nominative" + * @return the plural category corresponding to the identifier, or `UDISPOPT_GRAMMATICAL_CASE_UNDEFINED` + * + * @draft ICU 72 + */ +U_CAPI UDisplayOptionsGrammaticalCase U_EXPORT2 +udispopt_fromGrammaticalCaseIdentifier(const char *identifier); + +/** + * Standard CLDR plural form/category constants. + * See https://www.unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsPluralCategory { + + /** + * A possible setting for PluralCategory. + * The plural category case context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_PLURAL_CATEGORY_UNDEFINED = 0, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_ZERO = 1, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_ONE = 2, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_TWO = 3, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_FEW = 4, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_MANY = 5, + /** @draft ICU 72 */ + UDISPOPT_PLURAL_CATEGORY_OTHER = 6, +} UDisplayOptionsPluralCategory; + +/** + * @param pluralCategory The plural category. + * @return the lowercase CLDR identifier string for the plural category. + * + * @draft ICU 72 + */ +U_CAPI const char * U_EXPORT2 +udispopt_getPluralCategoryIdentifier(UDisplayOptionsPluralCategory pluralCategory); + +/** + * @param identifier for example "few" or "other" + * @return the plural category corresponding to the identifier (plural keyword), + * or `UDISPOPT_PLURAL_CATEGORY_UNDEFINED` + * + * @draft ICU 72 + */ +U_CAPI UDisplayOptionsPluralCategory U_EXPORT2 +udispopt_fromPluralCategoryIdentifier(const char *identifier); + +/** + * Represents all the grammatical noun classes that are supported by CLDR. + * + * @draft ICU 72. + */ +typedef enum UDisplayOptionsNounClass { + /** + * A possible setting for NounClass. + * The noun class case context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_NOUN_CLASS_UNDEFINED = 0, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_OTHER = 1, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_NEUTER = 2, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_FEMININE = 3, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_MASCULINE = 4, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_ANIMATE = 5, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_INANIMATE = 6, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_PERSONAL = 7, + /** ICU 72 */ + UDISPOPT_NOUN_CLASS_COMMON = 8, +} UDisplayOptionsNounClass; + +/** + * @param nounClass The noun class. + * @return the lowercase CLDR keyword string for the noun class. + * + * @draft ICU 72 + */ +U_CAPI const char * U_EXPORT2 +udispopt_getNounClassIdentifier(UDisplayOptionsNounClass nounClass); + +/** + * @param identifier in lower case such as "feminine" or "masculine" + * @return the plural category corresponding to the identifier, or `UDISPOPT_NOUN_CLASS_UNDEFINED` + * + * @draft ICU 72 + */ +U_CAPI UDisplayOptionsNounClass U_EXPORT2 +udispopt_fromNounClassIdentifier(const char *identifier); + +/** + * Represents all the capitalization options. + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsCapitalization { + /** + * A possible setting for Capitalization. + * The capitalization context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_CAPITALIZATION_UNDEFINED = 0, + + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for the beginning of a sentence. + * + * @draft ICU 72 + */ + UDISPOPT_CAPITALIZATION_BEGINNING_OF_SENTENCE = 1, + + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for the middle of a sentence. + * + * @draft ICU 72 + */ + UDISPOPT_CAPITALIZATION_MIDDLE_OF_SENTENCE = 2, + + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for stand-alone usage such as an + * isolated name on a calendar page. + * + * @draft ICU 72 + */ + UDISPOPT_CAPITALIZATION_STANDALONE = 3, + + /** + * The capitalization context if a date, date symbol or display name is to be + * formatted with capitalization appropriate for a user-interface list or menu item. + * + * @draft ICU 72 + */ + UDISPOPT_CAPITALIZATION_UI_LIST_OR_MENU = 4, +} UDisplayOptionsCapitalization; + +/** + * Represents all the dialect handlings. + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsNameStyle { + /** + * A possible setting for NameStyle. + * The NameStyle context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_NAME_STYLE_UNDEFINED = 0, + + /** + * Use standard names when generating a locale name, + * e.g. en_GB displays as 'English (United Kingdom)'. + * + * @draft ICU 72 + */ + UDISPOPT_NAME_STYLE_STANDARD_NAMES = 1, + + /** + * Use dialect names, when generating a locale name, + * e.g. en_GB displays as 'British English'. + * + * @draft ICU 72 + */ + UDISPOPT_NAME_STYLE_DIALECT_NAMES = 2, +} UDisplayOptionsNameStyle; + +/** + * Represents all the display lengths. + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsDisplayLength { + /** + * A possible setting for DisplayLength. + * The DisplayLength context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_DISPLAY_LENGTH_UNDEFINED = 0, + + /** + * Uses full names when generating a locale name, + * e.g. "United States" for US. + * + * @draft ICU 72 + */ + UDISPOPT_DISPLAY_LENGTH_FULL = 1, + + /** + * Use short names when generating a locale name, + * e.g. "U.S." for US. + * + * @draft ICU 72 + */ + UDISPOPT_DISPLAY_LENGTH_SHORT = 2, +} UDisplayOptionsDisplayLength; + +/** + * Represents all the substitute handling. + * + * @draft ICU 72 + */ +typedef enum UDisplayOptionsSubstituteHandling { + + /** + * A possible setting for SubstituteHandling. + * The SubstituteHandling context to be used is unknown (this is the default value). + * + * @draft ICU 72 + */ + UDISPOPT_SUBSTITUTE_HANDLING_UNDEFINED = 0, + + /** + * Returns a fallback value (e.g., the input code) when no data is available. + * This is the default behaviour. + * + * @draft ICU 72 + */ + UDISPOPT_SUBSTITUTE_HANDLING_SUBSTITUTE = 1, + + /** + * Returns a null value when no data is available. + * + * @draft ICU 72 + */ + UDISPOPT_SUBSTITUTE_HANDLING_NO_SUBSTITUTE = 2, +} UDisplayOptionsSubstituteHandling; + +#endif // U_HIDE_DRAFT_API + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif // __UDISPLAYOPTIONS_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uenum.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uenum.h new file mode 100644 index 0000000000000000000000000000000000000000..d9c893e06d92b275b1c4ee1e9539a308abacf0b2 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uenum.h @@ -0,0 +1,209 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2002-2013, International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: uenum.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:2 +* +* created on: 2002jul08 +* created by: Vladimir Weinstein +*/ + +#ifndef __UENUM_H +#define __UENUM_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" + +U_NAMESPACE_BEGIN +class StringEnumeration; +U_NAMESPACE_END +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: String Enumeration + */ + +/** + * An enumeration object. + * For usage in C programs. + * @stable ICU 2.2 + */ +struct UEnumeration; +/** structure representing an enumeration object instance @stable ICU 2.2 */ +typedef struct UEnumeration UEnumeration; + +/** + * Disposes of resources in use by the iterator. If en is NULL, + * does nothing. After this call, any char* or UChar* pointer + * returned by uenum_unext() or uenum_next() is invalid. + * @param en UEnumeration structure pointer + * @stable ICU 2.2 + */ +U_CAPI void U_EXPORT2 +uenum_close(UEnumeration* en); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUEnumerationPointer + * "Smart pointer" class, closes a UEnumeration via uenum_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUEnumerationPointer, UEnumeration, uenum_close); + +U_NAMESPACE_END + +#endif + +/** + * Returns the number of elements that the iterator traverses. If + * the iterator is out-of-sync with its service, status is set to + * U_ENUM_OUT_OF_SYNC_ERROR. + * This is a convenience function. It can end up being very + * expensive as all the items might have to be pre-fetched (depending + * on the type of data being traversed). Use with caution and only + * when necessary. + * @param en UEnumeration structure pointer + * @param status error code, can be U_ENUM_OUT_OF_SYNC_ERROR if the + * iterator is out of sync. + * @return number of elements in the iterator + * @stable ICU 2.2 + */ +U_CAPI int32_t U_EXPORT2 +uenum_count(UEnumeration* en, UErrorCode* status); + +/** + * Returns the next element in the iterator's list. If there are + * no more elements, returns NULL. If the iterator is out-of-sync + * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and + * NULL is returned. If the native service string is a char* string, + * it is converted to UChar* with the invariant converter. + * The result is terminated by (UChar)0. + * @param en the iterator object + * @param resultLength pointer to receive the length of the result + * (not including the terminating \\0). + * If the pointer is NULL it is ignored. + * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if + * the iterator is out of sync with its service. + * @return a pointer to the string. The string will be + * zero-terminated. The return pointer is owned by this iterator + * and must not be deleted by the caller. The pointer is valid + * until the next call to any uenum_... method, including + * uenum_next() or uenum_unext(). When all strings have been + * traversed, returns NULL. + * @stable ICU 2.2 + */ +U_CAPI const UChar* U_EXPORT2 +uenum_unext(UEnumeration* en, + int32_t* resultLength, + UErrorCode* status); + +/** + * Returns the next element in the iterator's list. If there are + * no more elements, returns NULL. If the iterator is out-of-sync + * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and + * NULL is returned. If the native service string is a UChar* + * string, it is converted to char* with the invariant converter. + * The result is terminated by (char)0. If the conversion fails + * (because a character cannot be converted) then status is set to + * U_INVARIANT_CONVERSION_ERROR and the return value is undefined + * (but non-NULL). + * @param en the iterator object + * @param resultLength pointer to receive the length of the result + * (not including the terminating \\0). + * If the pointer is NULL it is ignored. + * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if + * the iterator is out of sync with its service. Set to + * U_INVARIANT_CONVERSION_ERROR if the underlying native string is + * UChar* and conversion to char* with the invariant converter + * fails. This error pertains only to current string, so iteration + * might be able to continue successfully. + * @return a pointer to the string. The string will be + * zero-terminated. The return pointer is owned by this iterator + * and must not be deleted by the caller. The pointer is valid + * until the next call to any uenum_... method, including + * uenum_next() or uenum_unext(). When all strings have been + * traversed, returns NULL. + * @stable ICU 2.2 + */ +U_CAPI const char* U_EXPORT2 +uenum_next(UEnumeration* en, + int32_t* resultLength, + UErrorCode* status); + +/** + * Resets the iterator to the current list of service IDs. This + * re-establishes sync with the service and rewinds the iterator + * to start at the first element. + * @param en the iterator object + * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if + * the iterator is out of sync with its service. + * @stable ICU 2.2 + */ +U_CAPI void U_EXPORT2 +uenum_reset(UEnumeration* en, UErrorCode* status); + +#if U_SHOW_CPLUSPLUS_API + +/** + * Given a StringEnumeration, wrap it in a UEnumeration. The + * StringEnumeration is adopted; after this call, the caller must not + * delete it (regardless of error status). + * @param adopted the C++ StringEnumeration to be wrapped in a UEnumeration. + * @param ec the error code. + * @return a UEnumeration wrapping the adopted StringEnumeration. + * @stable ICU 4.2 + */ +U_CAPI UEnumeration* U_EXPORT2 +uenum_openFromStringEnumeration(icu::StringEnumeration* adopted, UErrorCode* ec); + +#endif + +/** + * Given an array of const UChar* strings, return a UEnumeration. String pointers from 0..count-1 must not be null. + * Do not free or modify either the string array or the characters it points to until this object has been destroyed with uenum_close. + * \snippet test/cintltst/uenumtst.c uenum_openUCharStringsEnumeration + * @param strings array of const UChar* strings (each null terminated). All storage is owned by the caller. + * @param count length of the array + * @param ec error code + * @return the new UEnumeration object. Caller is responsible for calling uenum_close to free memory. + * @see uenum_close + * @stable ICU 50 + */ +U_CAPI UEnumeration* U_EXPORT2 +uenum_openUCharStringsEnumeration(const UChar* const strings[], int32_t count, + UErrorCode* ec); + +/** + * Given an array of const char* strings (invariant chars only), return a UEnumeration. String pointers from 0..count-1 must not be null. + * Do not free or modify either the string array or the characters it points to until this object has been destroyed with uenum_close. + * \snippet test/cintltst/uenumtst.c uenum_openCharStringsEnumeration + * @param strings array of char* strings (each null terminated). All storage is owned by the caller. + * @param count length of the array + * @param ec error code + * @return the new UEnumeration object. Caller is responsible for calling uenum_close to free memory + * @see uenum_close + * @stable ICU 50 + */ +U_CAPI UEnumeration* U_EXPORT2 +uenum_openCharStringsEnumeration(const char* const strings[], int32_t count, + UErrorCode* ec); + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ufieldpositer.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ufieldpositer.h new file mode 100644 index 0000000000000000000000000000000000000000..83df184f0a5958312fbc1751472adbf819382d39 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ufieldpositer.h @@ -0,0 +1,123 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************************** +* Copyright (C) 2015-2016, International Business Machines +* Corporation and others. All Rights Reserved. +***************************************************************************************** +*/ + +#ifndef UFIELDPOSITER_H +#define UFIELDPOSITER_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: UFieldPositionIterator for use with format APIs. + * + * Usage: + * ufieldpositer_open creates an empty (unset) UFieldPositionIterator. + * This can be passed to format functions such as {@link #udat_formatForFields}, + * which will set it to apply to the fields in a particular formatted string. + * ufieldpositer_next can then be used to iterate over those fields, + * providing for each field its type (using values that are specific to the + * particular format type, such as date or number formats), as well as the + * start and end positions of the field in the formatted string. + * A given UFieldPositionIterator can be re-used for different format calls; + * each such call resets it to apply to that format string. + * ufieldpositer_close should be called to dispose of the UFieldPositionIterator + * when it is no longer needed. + * + * @see FieldPositionIterator + */ + +/** + * Opaque UFieldPositionIterator object for use in C. + * @stable ICU 55 + */ +struct UFieldPositionIterator; +typedef struct UFieldPositionIterator UFieldPositionIterator; /**< C typedef for struct UFieldPositionIterator. @stable ICU 55 */ + +/** + * Open a new, unset UFieldPositionIterator object. + * @param status + * A pointer to a UErrorCode to receive any errors. + * @return + * A pointer to an empty (unset) UFieldPositionIterator object, + * or NULL if an error occurred. + * @stable ICU 55 + */ +U_CAPI UFieldPositionIterator* U_EXPORT2 +ufieldpositer_open(UErrorCode* status); + +/** + * Close a UFieldPositionIterator object. Once closed it may no longer be used. + * @param fpositer + * A pointer to the UFieldPositionIterator object to close. + * @stable ICU 55 + */ +U_CAPI void U_EXPORT2 +ufieldpositer_close(UFieldPositionIterator *fpositer); + + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUFieldPositionIteratorPointer + * "Smart pointer" class, closes a UFieldPositionIterator via ufieldpositer_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 55 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUFieldPositionIteratorPointer, UFieldPositionIterator, ufieldpositer_close); + +U_NAMESPACE_END + +#endif + +/** + * Get information for the next field in the formatted string to which this + * UFieldPositionIterator currently applies, or return a negative value if there + * are no more fields. + * @param fpositer + * A pointer to the UFieldPositionIterator object containing iteration + * state for the format fields. + * @param beginIndex + * A pointer to an int32_t to receive information about the start offset + * of the field in the formatted string (undefined if the function + * returns a negative value). May be NULL if this information is not needed. + * @param endIndex + * A pointer to an int32_t to receive information about the end offset + * of the field in the formatted string (undefined if the function + * returns a negative value). May be NULL if this information is not needed. + * @return + * The field type (non-negative value), or a negative value if there are + * no more fields for which to provide information. If negative, then any + * values pointed to by beginIndex and endIndex are undefined. + * + * The values for field type depend on what type of formatter the + * UFieldPositionIterator has been set by; for a date formatter, the + * values from the UDateFormatField enum. For more information, see the + * descriptions of format functions that take a UFieldPositionIterator* + * parameter, such as {@link #udat_formatForFields}. + * + * @stable ICU 55 + */ +U_CAPI int32_t U_EXPORT2 +ufieldpositer_next(UFieldPositionIterator *fpositer, + int32_t *beginIndex, int32_t *endIndex); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattable.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattable.h new file mode 100644 index 0000000000000000000000000000000000000000..4c4a307a24b4a1257c5c59b694c33cd971f4472e --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattable.h @@ -0,0 +1,290 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************** +* Copyright (C) 2013-2014, International Business Machines Corporation and others. +* All Rights Reserved. +******************************************************************************** +* +* File UFORMATTABLE.H +* +* Modification History: +* +* Date Name Description +* 2013 Jun 7 srl New +******************************************************************************** +*/ + +/** + * \file + * \brief C API: UFormattable is a thin wrapper for primitive types used for formatting and parsing. + * + * This is a C interface to the icu::Formattable class. Static functions on this class convert + * to and from this interface (via reinterpret_cast). Note that Formattables (and thus UFormattables) + * are mutable, and many operations (even getters) may actually modify the internal state. For this + * reason, UFormattables are not thread safe, and should not be shared between threads. + * + * See {@link unum_parseToUFormattable} for example code. + */ + +#ifndef UFORMATTABLE_H +#define UFORMATTABLE_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * Enum designating the type of a UFormattable instance. + * Practically, this indicates which of the getters would return without conversion + * or error. + * @see icu::Formattable::Type + * @stable ICU 52 + */ +typedef enum UFormattableType { + UFMT_DATE = 0, /**< ufmt_getDate() will return without conversion. @see ufmt_getDate*/ + UFMT_DOUBLE, /**< ufmt_getDouble() will return without conversion. @see ufmt_getDouble*/ + UFMT_LONG, /**< ufmt_getLong() will return without conversion. @see ufmt_getLong */ + UFMT_STRING, /**< ufmt_getUChars() will return without conversion. @see ufmt_getUChars*/ + UFMT_ARRAY, /**< ufmt_countArray() and ufmt_getArray() will return the value. @see ufmt_getArrayItemByIndex */ + UFMT_INT64, /**< ufmt_getInt64() will return without conversion. @see ufmt_getInt64 */ + UFMT_OBJECT, /**< ufmt_getObject() will return without conversion. @see ufmt_getObject*/ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UFormattableType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UFMT_COUNT +#endif /* U_HIDE_DEPRECATED_API */ +} UFormattableType; + + +/** + * Opaque type representing various types of data which may be used for formatting + * and parsing operations. + * @see icu::Formattable + * @stable ICU 52 + */ +typedef void *UFormattable; + +/** + * Initialize a UFormattable, to type UNUM_LONG, value 0 + * may return error if memory allocation failed. + * parameter status error code. + * See {@link unum_parseToUFormattable} for example code. + * @stable ICU 52 + * @return the new UFormattable + * @see ufmt_close + * @see icu::Formattable::Formattable() + */ +U_CAPI UFormattable* U_EXPORT2 +ufmt_open(UErrorCode* status); + +/** + * Cleanup any additional memory allocated by this UFormattable. + * @param fmt the formatter + * @stable ICU 52 + * @see ufmt_open + */ +U_CAPI void U_EXPORT2 +ufmt_close(UFormattable* fmt); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUFormattablePointer + * "Smart pointer" class, closes a UFormattable via ufmt_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 52 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattablePointer, UFormattable, ufmt_close); + +U_NAMESPACE_END + +#endif + +/** + * Return the type of this object + * @param fmt the UFormattable object + * @param status status code - U_ILLEGAL_ARGUMENT_ERROR is returned if the UFormattable contains data not supported by + * the API + * @return the value as a UFormattableType + * @see ufmt_isNumeric + * @see icu::Formattable::getType() const + * @stable ICU 52 + */ +U_CAPI UFormattableType U_EXPORT2 +ufmt_getType(const UFormattable* fmt, UErrorCode *status); + +/** + * Return whether the object is numeric. + * @param fmt the UFormattable object + * @return true if the object is a double, long, or int64 value, else false. + * @see ufmt_getType + * @see icu::Formattable::isNumeric() const + * @stable ICU 52 + */ +U_CAPI UBool U_EXPORT2 +ufmt_isNumeric(const UFormattable* fmt); + +/** + * Gets the UDate value of this object. If the type is not of type UFMT_DATE, + * status is set to U_INVALID_FORMAT_ERROR and the return value is + * undefined. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @return the value + * @stable ICU 52 + * @see icu::Formattable::getDate(UErrorCode&) const + */ +U_CAPI UDate U_EXPORT2 +ufmt_getDate(const UFormattable* fmt, UErrorCode *status); + +/** + * Gets the double value of this object. If the type is not a UFMT_DOUBLE, or + * if there are additional significant digits than fit in a double type, + * a conversion is performed with possible loss of precision. + * If the type is UFMT_OBJECT and the + * object is a Measure, then the result of + * getNumber().getDouble(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @return the value + * @stable ICU 52 + * @see icu::Formattable::getDouble(UErrorCode&) const + */ +U_CAPI double U_EXPORT2 +ufmt_getDouble(UFormattable* fmt, UErrorCode *status); + +/** + * Gets the long (int32_t) value of this object. If the magnitude is too + * large to fit in a long, then the maximum or minimum long value, + * as appropriate, is returned and the status is set to + * U_INVALID_FORMAT_ERROR. If this object is of type UFMT_INT64 and + * it fits within a long, then no precision is lost. If it is of + * type kDouble or kDecimalNumber, then a conversion is performed, with + * truncation of any fractional part. If the type is UFMT_OBJECT and + * the object is a Measure, then the result of + * getNumber().getLong(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @return the value + * @stable ICU 52 + * @see icu::Formattable::getLong(UErrorCode&) const + */ +U_CAPI int32_t U_EXPORT2 +ufmt_getLong(UFormattable* fmt, UErrorCode *status); + + +/** + * Gets the int64_t value of this object. If this object is of a numeric + * type and the magnitude is too large to fit in an int64, then + * the maximum or minimum int64 value, as appropriate, is returned + * and the status is set to U_INVALID_FORMAT_ERROR. If the + * magnitude fits in an int64, then a casting conversion is + * performed, with truncation of any fractional part. If the type + * is UFMT_OBJECT and the object is a Measure, then the result of + * getNumber().getDouble(status) is returned. If this object is + * neither a numeric type nor a Measure, then 0 is returned and + * the status is set to U_INVALID_FORMAT_ERROR. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @return the value + * @stable ICU 52 + * @see icu::Formattable::getInt64(UErrorCode&) const + */ +U_CAPI int64_t U_EXPORT2 +ufmt_getInt64(UFormattable* fmt, UErrorCode *status); + +/** + * Returns a pointer to the UObject contained within this + * formattable (as a const void*), or NULL if this object + * is not of type UFMT_OBJECT. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @return the value as a const void*. It is a polymorphic C++ object. + * @stable ICU 52 + * @see icu::Formattable::getObject() const + */ +U_CAPI const void *U_EXPORT2 +ufmt_getObject(const UFormattable* fmt, UErrorCode *status); + +/** + * Gets the string value of this object as a UChar string. If the type is not a + * string, status is set to U_INVALID_FORMAT_ERROR and a NULL pointer is returned. + * This function is not thread safe and may modify the UFormattable if need be to terminate the string. + * The returned pointer is not valid if any other functions are called on this UFormattable, or if the UFormattable is closed. + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors + * @param len if non null, contains the string length on return + * @return the null terminated string value - must not be referenced after any other functions are called on this UFormattable. + * @stable ICU 52 + * @see icu::Formattable::getString(UnicodeString&)const + */ +U_CAPI const UChar* U_EXPORT2 +ufmt_getUChars(UFormattable* fmt, int32_t *len, UErrorCode *status); + +/** + * Get the number of array objects contained, if an array type UFMT_ARRAY + * @param fmt the UFormattable object + * @param status the error code - any conversion or format errors. U_ILLEGAL_ARGUMENT_ERROR if not an array type. + * @return the number of array objects or undefined if not an array type + * @stable ICU 52 + * @see ufmt_getArrayItemByIndex + */ +U_CAPI int32_t U_EXPORT2 +ufmt_getArrayLength(const UFormattable* fmt, UErrorCode *status); + +/** + * Get the specified value from the array of UFormattables. Invalid if the object is not an array type UFMT_ARRAY + * @param fmt the UFormattable object + * @param n the number of the array to return (0 based). + * @param status the error code - any conversion or format errors. Returns an error if n is out of bounds. + * @return the nth array value, only valid while the containing UFormattable is valid. NULL if not an array. + * @stable ICU 52 + * @see icu::Formattable::getArray(int32_t&, UErrorCode&) const + */ +U_CAPI UFormattable * U_EXPORT2 +ufmt_getArrayItemByIndex(UFormattable* fmt, int32_t n, UErrorCode *status); + +/** + * Returns a numeric string representation of the number contained within this + * formattable, or NULL if this object does not contain numeric type. + * For values obtained by parsing, the returned decimal number retains + * the full precision and range of the original input, unconstrained by + * the limits of a double floating point or a 64 bit int. + * + * This function is not thread safe, and therefore is not declared const, + * even though it is logically const. + * The resulting buffer is owned by the UFormattable and is invalid if any other functions are + * called on the UFormattable. + * + * Possible errors include U_MEMORY_ALLOCATION_ERROR, and + * U_INVALID_STATE if the formattable object has not been set to + * a numeric type. + * @param fmt the UFormattable object + * @param len if non-null, on exit contains the string length (not including the terminating null) + * @param status the error code + * @return the character buffer as a NULL terminated string, which is owned by the object and must not be accessed if any other functions are called on this object. + * @stable ICU 52 + * @see icu::Formattable::getDecimalNumber(UErrorCode&) + */ +U_CAPI const char * U_EXPORT2 +ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status); + +#endif + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattednumber.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattednumber.h new file mode 100644 index 0000000000000000000000000000000000000000..174a040a08339dc699621a10a4ecf5642ca728ec --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattednumber.h @@ -0,0 +1,224 @@ +// © 2022 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __UFORMATTEDNUMBER_H__ +#define __UFORMATTEDNUMBER_H__ + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/ufieldpositer.h" +#include "unicode/uformattedvalue.h" +#include "unicode/umisc.h" + +/** + * \file + * \brief C API: Formatted number result from various number formatting functions. + * + * Create a `UFormattedNumber` to hold the result of a number formatting operation. The same + * `UFormattedNumber` can be reused multiple times. + * + *

+ * LocalUFormattedNumberPointer uresult(unumf_openResult(status));
+ *
+ * // pass uresult.getAlias() to your number formatter
+ *
+ * int32_t length;
+ * const UChar* s = ufmtval_getString(unumf_resultAsValue(uresult.getAlias(), status), &length, status));
+ *
+ * // The string result is in `s` with the given `length` (it is also NUL-terminated).
+ * 
+ */ + + +struct UFormattedNumber; +/** + * C-compatible version of icu::number::FormattedNumber. + * + * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead. + * + * @stable ICU 62 + */ +typedef struct UFormattedNumber UFormattedNumber; + + +/** + * Creates an object to hold the result of a UNumberFormatter + * operation. The object can be used repeatedly; it is cleared whenever + * passed to a format function. + * + * @param ec Set if an error occurs. + * @stable ICU 62 + */ +U_CAPI UFormattedNumber* U_EXPORT2 +unumf_openResult(UErrorCode* ec); + + +/** + * Returns a representation of a UFormattedNumber as a UFormattedValue, + * which can be subsequently passed to any API requiring that type. + * + * The returned object is owned by the UFormattedNumber and is valid + * only as long as the UFormattedNumber is present and unchanged in memory. + * + * You can think of this method as a cast between types. + * + * @param uresult The object containing the formatted string. + * @param ec Set if an error occurs. + * @return A UFormattedValue owned by the input object. + * @stable ICU 64 + */ +U_CAPI const UFormattedValue* U_EXPORT2 +unumf_resultAsValue(const UFormattedNumber* uresult, UErrorCode* ec); + + +/** + * Extracts the result number string out of a UFormattedNumber to a UChar buffer if possible. + * If bufferCapacity is greater than the required length, a terminating NUL is written. + * If bufferCapacity is less than the required length, an error code is set. + * + * Also see ufmtval_getString, which returns a NUL-terminated string: + * + * int32_t len; + * const UChar* str = ufmtval_getString(unumf_resultAsValue(uresult, &ec), &len, &ec); + * + * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead. + * + * @param uresult The object containing the formatted number. + * @param buffer Where to save the string output. + * @param bufferCapacity The number of UChars available in the buffer. + * @param ec Set if an error occurs. + * @return The required length. + * @stable ICU 62 + */ +U_CAPI int32_t U_EXPORT2 +unumf_resultToString(const UFormattedNumber* uresult, UChar* buffer, int32_t bufferCapacity, + UErrorCode* ec); + + +/** + * Determines the start and end indices of the next occurrence of the given field in the + * output string. This allows you to determine the locations of, for example, the integer part, + * fraction part, or symbols. + * + * This is a simpler but less powerful alternative to {@link ufmtval_nextPosition}. + * + * If a field occurs just once, calling this method will find that occurrence and return it. If a + * field occurs multiple times, this method may be called repeatedly with the following pattern: + * + *
+ * UFieldPosition ufpos = {UNUM_GROUPING_SEPARATOR_FIELD, 0, 0};
+ * while (unumf_resultNextFieldPosition(uresult, ufpos, &ec)) {
+ *   // do something with ufpos.
+ * }
+ * 
+ * + * This method is useful if you know which field to query. If you want all available field position + * information, use unumf_resultGetAllFieldPositions(). + * + * NOTE: All fields of the UFieldPosition must be initialized before calling this method. + * + * @param uresult The object containing the formatted number. + * @param ufpos + * Input+output variable. On input, the "field" property determines which field to look up, + * and the "endIndex" property determines where to begin the search. On output, the + * "beginIndex" field is set to the beginning of the first occurrence of the field after the + * input "endIndex", and "endIndex" is set to the end of that occurrence of the field + * (exclusive index). If a field position is not found, the FieldPosition is not changed and + * the method returns false. + * @param ec Set if an error occurs. + * @stable ICU 62 + */ +U_CAPI UBool U_EXPORT2 +unumf_resultNextFieldPosition(const UFormattedNumber* uresult, UFieldPosition* ufpos, UErrorCode* ec); + + +/** + * Populates the given iterator with all fields in the formatted output string. This allows you to + * determine the locations of the integer part, fraction part, and sign. + * + * This is an alternative to the more powerful {@link ufmtval_nextPosition} API. + * + * If you need information on only one field, use {@link ufmtval_nextPosition} or + * {@link unumf_resultNextFieldPosition}. + * + * @param uresult The object containing the formatted number. + * @param ufpositer + * A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open}. Iteration + * information already present in the UFieldPositionIterator is deleted, and the iterator is reset + * to apply to the fields in the formatted string created by this function call. The field values + * and indexes returned by {@link #ufieldpositer_next} represent fields denoted by + * the UNumberFormatFields enum. Fields are not returned in a guaranteed order. Fields cannot + * overlap, but they may nest. For example, 1234 could format as "1,234" which might consist of a + * grouping separator field for ',' and an integer field encompassing the entire string. + * @param ec Set if an error occurs. + * @stable ICU 62 + */ +U_CAPI void U_EXPORT2 +unumf_resultGetAllFieldPositions(const UFormattedNumber* uresult, UFieldPositionIterator* ufpositer, + UErrorCode* ec); + + +/** + * Extracts the formatted number as a "numeric string" conforming to the + * syntax defined in the Decimal Arithmetic Specification, available at + * http://speleotrove.com/decimal + * + * This endpoint is useful for obtaining the exact number being printed + * after scaling and rounding have been applied by the number formatter. + * + * @param uresult The input object containing the formatted number. + * @param dest the 8-bit char buffer into which the decimal number is placed + * @param destCapacity The size, in chars, of the destination buffer. May be zero + * for precomputing the required size. + * @param ec receives any error status. + * If U_BUFFER_OVERFLOW_ERROR: Returns number of chars for + * preflighting. + * @return Number of chars in the data. Does not include a trailing NUL. + * @stable ICU 68 + */ +U_CAPI int32_t U_EXPORT2 +unumf_resultToDecimalNumber( + const UFormattedNumber* uresult, + char* dest, + int32_t destCapacity, + UErrorCode* ec); + + +/** + * Releases the UFormattedNumber created by unumf_openResult(). + * + * @param uresult An object created by unumf_openResult(). + * @stable ICU 62 + */ +U_CAPI void U_EXPORT2 +unumf_closeResult(UFormattedNumber* uresult); + + +#if U_SHOW_CPLUSPLUS_API +U_NAMESPACE_BEGIN + +/** + * \class LocalUFormattedNumberPointer + * "Smart pointer" class; closes a UFormattedNumber via unumf_closeResult(). + * For most methods see the LocalPointerBase base class. + * + * Usage: + *
+ * LocalUFormattedNumberPointer uformatter(unumf_openResult(...));
+ * // no need to explicitly call unumf_closeResult()
+ * 
+ * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 62 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedNumberPointer, UFormattedNumber, unumf_closeResult); + +U_NAMESPACE_END +#endif // U_SHOW_CPLUSPLUS_API + + +#endif /* #if !UCONFIG_NO_FORMATTING */ +#endif //__UFORMATTEDNUMBER_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattedvalue.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattedvalue.h new file mode 100644 index 0000000000000000000000000000000000000000..af6d18f3bc99c2e3c801a2df687fa5695c536d6a --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uformattedvalue.h @@ -0,0 +1,445 @@ +// © 2018 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +#ifndef __UFORMATTEDVALUE_H__ +#define __UFORMATTEDVALUE_H__ + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/ufieldpositer.h" + +/** + * \file + * \brief C API: Abstract operations for localized strings. + * + * This file contains declarations for classes that deal with formatted strings. A number + * of APIs throughout ICU use these classes for expressing their localized output. + */ + + +/** + * All possible field categories in ICU. Every entry in this enum corresponds + * to another enum that exists in ICU. + * + * In the APIs that take a UFieldCategory, an int32_t type is used. Field + * categories having any of the top four bits turned on are reserved as + * private-use for external APIs implementing FormattedValue. This means that + * categories 2^28 and higher or below zero (with the highest bit turned on) + * are private-use and will not be used by ICU in the future. + * + * @stable ICU 64 + */ +typedef enum UFieldCategory { + /** + * For an undefined field category. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_UNDEFINED = 0, + + /** + * For fields in UDateFormatField (udat.h), from ICU 3.0. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_DATE, + + /** + * For fields in UNumberFormatFields (unum.h), from ICU 49. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_NUMBER, + + /** + * For fields in UListFormatterField (ulistformatter.h), from ICU 63. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_LIST, + + /** + * For fields in URelativeDateTimeFormatterField (ureldatefmt.h), from ICU 64. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_RELATIVE_DATETIME, + + /** + * Reserved for possible future fields in UDateIntervalFormatField. + * + * @internal + */ + UFIELD_CATEGORY_DATE_INTERVAL, + +#ifndef U_HIDE_INTERNAL_API + /** @internal */ + UFIELD_CATEGORY_COUNT, +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Category for spans in a list. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_LIST_SPAN = 0x1000 + UFIELD_CATEGORY_LIST, + + /** + * Category for spans in a date interval. + * + * @stable ICU 64 + */ + UFIELD_CATEGORY_DATE_INTERVAL_SPAN = 0x1000 + UFIELD_CATEGORY_DATE_INTERVAL, + + /** + * Category for spans in a number range. + * + * @stable ICU 69 + */ + UFIELD_CATEGORY_NUMBER_RANGE_SPAN = 0x1000 + UFIELD_CATEGORY_NUMBER, + +} UFieldCategory; + + +struct UConstrainedFieldPosition; +/** + * Represents a span of a string containing a given field. + * + * This struct differs from UFieldPosition in the following ways: + * + * 1. It has information on the field category. + * 2. It allows you to set constraints to use when iterating over field positions. + * 3. It is used for the newer FormattedValue APIs. + * + * @stable ICU 64 + */ +typedef struct UConstrainedFieldPosition UConstrainedFieldPosition; + + +/** + * Creates a new UConstrainedFieldPosition. + * + * By default, the UConstrainedFieldPosition has no iteration constraints. + * + * @param ec Set if an error occurs. + * @return The new object, or NULL if an error occurs. + * @stable ICU 64 + */ +U_CAPI UConstrainedFieldPosition* U_EXPORT2 +ucfpos_open(UErrorCode* ec); + + +/** + * Resets a UConstrainedFieldPosition to its initial state, as if it were newly created. + * + * Removes any constraints that may have been set on the instance. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_reset( + UConstrainedFieldPosition* ucfpos, + UErrorCode* ec); + + +/** + * Destroys a UConstrainedFieldPosition and releases its memory. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_close(UConstrainedFieldPosition* ucfpos); + + +/** + * Sets a constraint on the field category. + * + * When this instance of UConstrainedFieldPosition is passed to ufmtval_nextPosition, + * positions are skipped unless they have the given category. + * + * Any previously set constraints are cleared. + * + * For example, to loop over only the number-related fields: + * + * UConstrainedFieldPosition* ucfpos = ucfpos_open(ec); + * ucfpos_constrainCategory(ucfpos, UFIELDCATEGORY_NUMBER_FORMAT, ec); + * while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) { + * // handle the number-related field position + * } + * ucfpos_close(ucfpos); + * + * Changing the constraint while in the middle of iterating over a FormattedValue + * does not generally have well-defined behavior. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param category The field category to fix when iterating. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_constrainCategory( + UConstrainedFieldPosition* ucfpos, + int32_t category, + UErrorCode* ec); + + +/** + * Sets a constraint on the category and field. + * + * When this instance of UConstrainedFieldPosition is passed to ufmtval_nextPosition, + * positions are skipped unless they have the given category and field. + * + * Any previously set constraints are cleared. + * + * For example, to loop over all grouping separators: + * + * UConstrainedFieldPosition* ucfpos = ucfpos_open(ec); + * ucfpos_constrainField(ucfpos, UFIELDCATEGORY_NUMBER_FORMAT, UNUM_GROUPING_SEPARATOR_FIELD, ec); + * while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) { + * // handle the grouping separator position + * } + * ucfpos_close(ucfpos); + * + * Changing the constraint while in the middle of iterating over a FormattedValue + * does not generally have well-defined behavior. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param category The field category to fix when iterating. + * @param field The field to fix when iterating. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_constrainField( + UConstrainedFieldPosition* ucfpos, + int32_t category, + int32_t field, + UErrorCode* ec); + + +/** + * Gets the field category for the current position. + * + * If a category or field constraint was set, this function returns the constrained + * category. Otherwise, the return value is well-defined only after + * ufmtval_nextPosition returns true. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param ec Set if an error occurs. + * @return The field category saved in the instance. + * @stable ICU 64 + */ +U_CAPI int32_t U_EXPORT2 +ucfpos_getCategory( + const UConstrainedFieldPosition* ucfpos, + UErrorCode* ec); + + +/** + * Gets the field for the current position. + * + * If a field constraint was set, this function returns the constrained + * field. Otherwise, the return value is well-defined only after + * ufmtval_nextPosition returns true. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param ec Set if an error occurs. + * @return The field saved in the instance. + * @stable ICU 64 + */ +U_CAPI int32_t U_EXPORT2 +ucfpos_getField( + const UConstrainedFieldPosition* ucfpos, + UErrorCode* ec); + + +/** + * Gets the INCLUSIVE start and EXCLUSIVE end index stored for the current position. + * + * The output values are well-defined only after ufmtval_nextPosition returns true. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param pStart Set to the start index saved in the instance. Ignored if nullptr. + * @param pLimit Set to the end index saved in the instance. Ignored if nullptr. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_getIndexes( + const UConstrainedFieldPosition* ucfpos, + int32_t* pStart, + int32_t* pLimit, + UErrorCode* ec); + + +/** + * Gets an int64 that FormattedValue implementations may use for storage. + * + * The initial value is zero. + * + * Users of FormattedValue should not need to call this method. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param ec Set if an error occurs. + * @return The current iteration context from ucfpos_setInt64IterationContext. + * @stable ICU 64 + */ +U_CAPI int64_t U_EXPORT2 +ucfpos_getInt64IterationContext( + const UConstrainedFieldPosition* ucfpos, + UErrorCode* ec); + + +/** + * Sets an int64 that FormattedValue implementations may use for storage. + * + * Intended to be used by FormattedValue implementations. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param context The new iteration context. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_setInt64IterationContext( + UConstrainedFieldPosition* ucfpos, + int64_t context, + UErrorCode* ec); + + +/** + * Determines whether a given field should be included given the + * constraints. + * + * Intended to be used by FormattedValue implementations. + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param category The category to test. + * @param field The field to test. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI UBool U_EXPORT2 +ucfpos_matchesField( + const UConstrainedFieldPosition* ucfpos, + int32_t category, + int32_t field, + UErrorCode* ec); + + +/** + * Sets new values for the primary public getters. + * + * Intended to be used by FormattedValue implementations. + * + * It is up to the implementation to ensure that the user-requested + * constraints are satisfied. This method does not check! + * + * @param ucfpos The instance of UConstrainedFieldPosition. + * @param category The new field category. + * @param field The new field. + * @param start The new inclusive start index. + * @param limit The new exclusive end index. + * @param ec Set if an error occurs. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ucfpos_setState( + UConstrainedFieldPosition* ucfpos, + int32_t category, + int32_t field, + int32_t start, + int32_t limit, + UErrorCode* ec); + + +struct UFormattedValue; +/** + * An abstract formatted value: a string with associated field attributes. + * Many formatters format to types compatible with UFormattedValue. + * + * @stable ICU 64 + */ +typedef struct UFormattedValue UFormattedValue; + + +/** + * Returns a pointer to the formatted string. The pointer is owned by the UFormattedValue. The + * return value is valid only as long as the UFormattedValue is present and unchanged in memory. + * + * The return value is NUL-terminated but could contain internal NULs. + * + * @param ufmtval + * The object containing the formatted string and attributes. + * @param pLength Output variable for the length of the string. Ignored if NULL. + * @param ec Set if an error occurs. + * @return A NUL-terminated char16 string owned by the UFormattedValue. + * @stable ICU 64 + */ +U_CAPI const UChar* U_EXPORT2 +ufmtval_getString( + const UFormattedValue* ufmtval, + int32_t* pLength, + UErrorCode* ec); + + +/** + * Iterates over field positions in the UFormattedValue. This lets you determine the position + * of specific types of substrings, like a month or a decimal separator. + * + * To loop over all field positions: + * + * UConstrainedFieldPosition* ucfpos = ucfpos_open(ec); + * while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) { + * // handle the field position; get information from ucfpos + * } + * ucfpos_close(ucfpos); + * + * @param ufmtval + * The object containing the formatted string and attributes. + * @param ucfpos + * The object used for iteration state; can provide constraints to iterate over only + * one specific category or field; + * see ucfpos_constrainCategory + * and ucfpos_constrainField. + * @param ec Set if an error occurs. + * @return true if another position was found; false otherwise. + * @stable ICU 64 + */ +U_CAPI UBool U_EXPORT2 +ufmtval_nextPosition( + const UFormattedValue* ufmtval, + UConstrainedFieldPosition* ucfpos, + UErrorCode* ec); + + +#if U_SHOW_CPLUSPLUS_API +U_NAMESPACE_BEGIN + +/** + * \class LocalUConstrainedFieldPositionPointer + * "Smart pointer" class; closes a UConstrainedFieldPosition via ucfpos_close(). + * For most methods see the LocalPointerBase base class. + * + * Usage: + * + * LocalUConstrainedFieldPositionPointer ucfpos(ucfpos_open(ec)); + * // no need to explicitly call ucfpos_close() + * + * @stable ICU 64 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUConstrainedFieldPositionPointer, + UConstrainedFieldPosition, + ucfpos_close); + +U_NAMESPACE_END +#endif // U_SHOW_CPLUSPLUS_API + + +#endif /* #if !UCONFIG_NO_FORMATTING */ +#endif // __UFORMATTEDVALUE_H__ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ugender.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ugender.h new file mode 100644 index 0000000000000000000000000000000000000000..7093686b8fdab5f58d4ec53ce5aae97bc96cfba2 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ugender.h @@ -0,0 +1,86 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************************** +* Copyright (C) 2010-2013, International Business Machines +* Corporation and others. All Rights Reserved. +***************************************************************************************** +*/ + +#ifndef UGENDER_H +#define UGENDER_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: The purpose of this API is to compute the gender of a list as a + * whole given the gender of each element. + * + */ + +/** + * Genders + * @stable ICU 50 + */ +enum UGender { + /** + * Male gender. + * @stable ICU 50 + */ + UGENDER_MALE, + /** + * Female gender. + * @stable ICU 50 + */ + UGENDER_FEMALE, + /** + * Neutral gender. + * @stable ICU 50 + */ + UGENDER_OTHER +}; +/** + * @stable ICU 50 + */ +typedef enum UGender UGender; + +struct UGenderInfo; +/** + * Opaque UGenderInfo object for use in C programs. + * @stable ICU 50 + */ +typedef struct UGenderInfo UGenderInfo; + +/** + * Opens a new UGenderInfo object given locale. + * @param locale The locale for which the rules are desired. + * @param status UErrorCode pointer + * @return A UGenderInfo for the specified locale, or NULL if an error occurred. + * @stable ICU 50 + */ +U_CAPI const UGenderInfo* U_EXPORT2 +ugender_getInstance(const char *locale, UErrorCode *status); + + +/** + * Given a list, returns the gender of the list as a whole. + * @param genderInfo pointer that ugender_getInstance returns. + * @param genders the gender of each element in the list. + * @param size the size of the list. + * @param status A pointer to a UErrorCode to receive any errors. + * @return The gender of the list. + * @stable ICU 50 + */ +U_CAPI UGender U_EXPORT2 +ugender_getListGender(const UGenderInfo* genderInfo, const UGender *genders, int32_t size, UErrorCode *status); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uidna.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uidna.h new file mode 100644 index 0000000000000000000000000000000000000000..24a81ceaddf58d4fb372e70a38b71a1203f4fe91 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uidna.h @@ -0,0 +1,776 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* + ******************************************************************************* + * + * Copyright (C) 2003-2014, International Business Machines + * Corporation and others. All Rights Reserved. + * + ******************************************************************************* + * file name: uidna.h + * encoding: UTF-8 + * tab size: 8 (not used) + * indentation:4 + * + * created on: 2003feb1 + * created by: Ram Viswanadha + */ + +#ifndef __UIDNA_H__ +#define __UIDNA_H__ + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_IDNA + +#include +#include "unicode/parseerr.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Internationalizing Domain Names in Applications (IDNA) + * + * IDNA2008 is implemented according to UTS #46, see the IDNA C++ class in idna.h. + * + * The C API functions which do take a UIDNA * service object pointer + * implement UTS #46 and IDNA2008. + * + * IDNA2003 is obsolete. + * The C API functions which do not take a service object pointer + * implement IDNA2003. They are all deprecated. + */ + +/* + * IDNA option bit set values. + */ +enum { + /** + * Default options value: None of the other options are set. + * For use in static worker and factory methods. + * @stable ICU 2.6 + */ + UIDNA_DEFAULT=0, +#ifndef U_HIDE_DEPRECATED_API + /** + * Option to allow unassigned code points in domain names and labels. + * For use in static worker and factory methods. + *

This option is ignored by the UTS46 implementation. + * (UTS #46 disallows unassigned code points.) + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ + UIDNA_ALLOW_UNASSIGNED=1, +#endif /* U_HIDE_DEPRECATED_API */ + /** + * Option to check whether the input conforms to the STD3 ASCII rules, + * for example the restriction of labels to LDH characters + * (ASCII Letters, Digits and Hyphen-Minus). + * For use in static worker and factory methods. + * @stable ICU 2.6 + */ + UIDNA_USE_STD3_RULES=2, + /** + * IDNA option to check for whether the input conforms to the BiDi rules. + * For use in static worker and factory methods. + *

This option is ignored by the IDNA2003 implementation. + * (IDNA2003 always performs a BiDi check.) + * @stable ICU 4.6 + */ + UIDNA_CHECK_BIDI=4, + /** + * IDNA option to check for whether the input conforms to the CONTEXTJ rules. + * For use in static worker and factory methods. + *

This option is ignored by the IDNA2003 implementation. + * (The CONTEXTJ check is new in IDNA2008.) + * @stable ICU 4.6 + */ + UIDNA_CHECK_CONTEXTJ=8, + /** + * IDNA option for nontransitional processing in ToASCII(). + * For use in static worker and factory methods. + *

By default, ToASCII() uses transitional processing. + *

This option is ignored by the IDNA2003 implementation. + * (This is only relevant for compatibility of newer IDNA implementations with IDNA2003.) + * @stable ICU 4.6 + */ + UIDNA_NONTRANSITIONAL_TO_ASCII=0x10, + /** + * IDNA option for nontransitional processing in ToUnicode(). + * For use in static worker and factory methods. + *

By default, ToUnicode() uses transitional processing. + *

This option is ignored by the IDNA2003 implementation. + * (This is only relevant for compatibility of newer IDNA implementations with IDNA2003.) + * @stable ICU 4.6 + */ + UIDNA_NONTRANSITIONAL_TO_UNICODE=0x20, + /** + * IDNA option to check for whether the input conforms to the CONTEXTO rules. + * For use in static worker and factory methods. + *

This option is ignored by the IDNA2003 implementation. + * (The CONTEXTO check is new in IDNA2008.) + *

This is for use by registries for IDNA2008 conformance. + * UTS #46 does not require the CONTEXTO check. + * @stable ICU 49 + */ + UIDNA_CHECK_CONTEXTO=0x40 +}; + +/** + * Opaque C service object type for the new IDNA API. + * @stable ICU 4.6 + */ +struct UIDNA; +typedef struct UIDNA UIDNA; /**< C typedef for struct UIDNA. @stable ICU 4.6 */ + +/** + * Returns a UIDNA instance which implements UTS #46. + * Returns an unmodifiable instance, owned by the caller. + * Cache it for multiple operations, and uidna_close() it when done. + * The instance is thread-safe, that is, it can be used concurrently. + * + * For details about the UTS #46 implementation see the IDNA C++ class in idna.h. + * + * @param options Bit set to modify the processing and error checking. + * See option bit set values in uidna.h. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return the UTS #46 UIDNA instance, if successful + * @stable ICU 4.6 + */ +U_CAPI UIDNA * U_EXPORT2 +uidna_openUTS46(uint32_t options, UErrorCode *pErrorCode); + +/** + * Closes a UIDNA instance. + * @param idna UIDNA instance to be closed + * @stable ICU 4.6 + */ +U_CAPI void U_EXPORT2 +uidna_close(UIDNA *idna); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUIDNAPointer + * "Smart pointer" class, closes a UIDNA via uidna_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.6 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUIDNAPointer, UIDNA, uidna_close); + +U_NAMESPACE_END + +#endif + +/** + * Output container for IDNA processing errors. + * Initialize with UIDNA_INFO_INITIALIZER: + * \code + * UIDNAInfo info = UIDNA_INFO_INITIALIZER; + * int32_t length = uidna_nameToASCII(..., &info, &errorCode); + * if(U_SUCCESS(errorCode) && info.errors!=0) { ... } + * \endcode + * @stable ICU 4.6 + */ +typedef struct UIDNAInfo { + /** sizeof(UIDNAInfo) @stable ICU 4.6 */ + int16_t size; + /** + * Set to true if transitional and nontransitional processing produce different results. + * For details see C++ IDNAInfo::isTransitionalDifferent(). + * @stable ICU 4.6 + */ + UBool isTransitionalDifferent; + UBool reservedB3; /**< Reserved field, do not use. @internal */ + /** + * Bit set indicating IDNA processing errors. 0 if no errors. + * See UIDNA_ERROR_... constants. + * @stable ICU 4.6 + */ + uint32_t errors; + int32_t reservedI2; /**< Reserved field, do not use. @internal */ + int32_t reservedI3; /**< Reserved field, do not use. @internal */ +} UIDNAInfo; + +/** + * Static initializer for a UIDNAInfo struct. + * @stable ICU 4.6 + */ +#define UIDNA_INFO_INITIALIZER { \ + (int16_t)sizeof(UIDNAInfo), \ + false, false, \ + 0, 0, 0 } + +/** + * Converts a single domain name label into its ASCII form for DNS lookup. + * If any processing step fails, then pInfo->errors will be non-zero and + * the result might not be an ASCII string. + * The label might be modified according to the types of errors. + * Labels with severe errors will be left in (or turned into) their Unicode form. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param idna UIDNA instance + * @param label Input domain name label + * @param length Label length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_labelToASCII(const UIDNA *idna, + const UChar *label, int32_t length, + UChar *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a single domain name label into its Unicode form for human-readable display. + * If any processing step fails, then pInfo->errors will be non-zero. + * The label might be modified according to the types of errors. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param idna UIDNA instance + * @param label Input domain name label + * @param length Label length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_labelToUnicode(const UIDNA *idna, + const UChar *label, int32_t length, + UChar *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a whole domain name into its ASCII form for DNS lookup. + * If any processing step fails, then pInfo->errors will be non-zero and + * the result might not be an ASCII string. + * The domain name might be modified according to the types of errors. + * Labels with severe errors will be left in (or turned into) their Unicode form. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param idna UIDNA instance + * @param name Input domain name + * @param length Domain name length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_nameToASCII(const UIDNA *idna, + const UChar *name, int32_t length, + UChar *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a whole domain name into its Unicode form for human-readable display. + * If any processing step fails, then pInfo->errors will be non-zero. + * The domain name might be modified according to the types of errors. + * + * The UErrorCode indicates an error only in exceptional cases, + * such as a U_MEMORY_ALLOCATION_ERROR. + * + * @param idna UIDNA instance + * @param name Input domain name + * @param length Domain name length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_nameToUnicode(const UIDNA *idna, + const UChar *name, int32_t length, + UChar *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/* UTF-8 versions of the processing methods --------------------------------- */ + +/** + * Converts a single domain name label into its ASCII form for DNS lookup. + * UTF-8 version of uidna_labelToASCII(), same behavior. + * + * @param idna UIDNA instance + * @param label Input domain name label + * @param length Label length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_labelToASCII_UTF8(const UIDNA *idna, + const char *label, int32_t length, + char *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a single domain name label into its Unicode form for human-readable display. + * UTF-8 version of uidna_labelToUnicode(), same behavior. + * + * @param idna UIDNA instance + * @param label Input domain name label + * @param length Label length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_labelToUnicodeUTF8(const UIDNA *idna, + const char *label, int32_t length, + char *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a whole domain name into its ASCII form for DNS lookup. + * UTF-8 version of uidna_nameToASCII(), same behavior. + * + * @param idna UIDNA instance + * @param name Input domain name + * @param length Domain name length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_nameToASCII_UTF8(const UIDNA *idna, + const char *name, int32_t length, + char *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/** + * Converts a whole domain name into its Unicode form for human-readable display. + * UTF-8 version of uidna_nameToUnicode(), same behavior. + * + * @param idna UIDNA instance + * @param name Input domain name + * @param length Domain name length, or -1 if NUL-terminated + * @param dest Destination string buffer + * @param capacity Destination buffer capacity + * @param pInfo Output container of IDNA processing details. + * @param pErrorCode Standard ICU error code. Its input value must + * pass the U_SUCCESS() test, or else the function returns + * immediately. Check for U_FAILURE() on output or use with + * function chaining. (See User Guide for details.) + * @return destination string length + * @stable ICU 4.6 + */ +U_CAPI int32_t U_EXPORT2 +uidna_nameToUnicodeUTF8(const UIDNA *idna, + const char *name, int32_t length, + char *dest, int32_t capacity, + UIDNAInfo *pInfo, UErrorCode *pErrorCode); + +/* + * IDNA error bit set values. + * When a domain name or label fails a processing step or does not meet the + * validity criteria, then one or more of these error bits are set. + */ +enum { + /** + * A non-final domain name label (or the whole domain name) is empty. + * @stable ICU 4.6 + */ + UIDNA_ERROR_EMPTY_LABEL=1, + /** + * A domain name label is longer than 63 bytes. + * (See STD13/RFC1034 3.1. Name space specifications and terminology.) + * This is only checked in ToASCII operations, and only if the output label is all-ASCII. + * @stable ICU 4.6 + */ + UIDNA_ERROR_LABEL_TOO_LONG=2, + /** + * A domain name is longer than 255 bytes in its storage form. + * (See STD13/RFC1034 3.1. Name space specifications and terminology.) + * This is only checked in ToASCII operations, and only if the output domain name is all-ASCII. + * @stable ICU 4.6 + */ + UIDNA_ERROR_DOMAIN_NAME_TOO_LONG=4, + /** + * A label starts with a hyphen-minus ('-'). + * @stable ICU 4.6 + */ + UIDNA_ERROR_LEADING_HYPHEN=8, + /** + * A label ends with a hyphen-minus ('-'). + * @stable ICU 4.6 + */ + UIDNA_ERROR_TRAILING_HYPHEN=0x10, + /** + * A label contains hyphen-minus ('-') in the third and fourth positions. + * @stable ICU 4.6 + */ + UIDNA_ERROR_HYPHEN_3_4=0x20, + /** + * A label starts with a combining mark. + * @stable ICU 4.6 + */ + UIDNA_ERROR_LEADING_COMBINING_MARK=0x40, + /** + * A label or domain name contains disallowed characters. + * @stable ICU 4.6 + */ + UIDNA_ERROR_DISALLOWED=0x80, + /** + * A label starts with "xn--" but does not contain valid Punycode. + * That is, an xn-- label failed Punycode decoding. + * @stable ICU 4.6 + */ + UIDNA_ERROR_PUNYCODE=0x100, + /** + * A label contains a dot=full stop. + * This can occur in an input string for a single-label function. + * @stable ICU 4.6 + */ + UIDNA_ERROR_LABEL_HAS_DOT=0x200, + /** + * An ACE label does not contain a valid label string. + * The label was successfully ACE (Punycode) decoded but the resulting + * string had severe validation errors. For example, + * it might contain characters that are not allowed in ACE labels, + * or it might not be normalized. + * @stable ICU 4.6 + */ + UIDNA_ERROR_INVALID_ACE_LABEL=0x400, + /** + * A label does not meet the IDNA BiDi requirements (for right-to-left characters). + * @stable ICU 4.6 + */ + UIDNA_ERROR_BIDI=0x800, + /** + * A label does not meet the IDNA CONTEXTJ requirements. + * @stable ICU 4.6 + */ + UIDNA_ERROR_CONTEXTJ=0x1000, + /** + * A label does not meet the IDNA CONTEXTO requirements for punctuation characters. + * Some punctuation characters "Would otherwise have been DISALLOWED" + * but are allowed in certain contexts. (RFC 5892) + * @stable ICU 49 + */ + UIDNA_ERROR_CONTEXTO_PUNCTUATION=0x2000, + /** + * A label does not meet the IDNA CONTEXTO requirements for digits. + * Arabic-Indic Digits (U+066x) must not be mixed with Extended Arabic-Indic Digits (U+06Fx). + * @stable ICU 49 + */ + UIDNA_ERROR_CONTEXTO_DIGITS=0x4000 +}; + +#ifndef U_HIDE_DEPRECATED_API + +/* IDNA2003 API ------------------------------------------------------------- */ + +/** + * IDNA2003: This function implements the ToASCII operation as defined in the IDNA RFC. + * This operation is done on single labels before sending it to something that expects + * ASCII names. A label is an individual part of a domain name. Labels are usually + * separated by dots; e.g. "www.example.com" is composed of 3 labels "www","example", and "com". + * + * IDNA2003 API Overview: + * + * The uidna_ API implements the IDNA protocol as defined in the IDNA RFC + * (http://www.ietf.org/rfc/rfc3490.txt). + * The RFC defines 2 operations: ToASCII and ToUnicode. Domain name labels + * containing non-ASCII code points are processed by the + * ToASCII operation before passing it to resolver libraries. Domain names + * that are obtained from resolver libraries are processed by the + * ToUnicode operation before displaying the domain name to the user. + * IDNA requires that implementations process input strings with Nameprep + * (http://www.ietf.org/rfc/rfc3491.txt), + * which is a profile of Stringprep (http://www.ietf.org/rfc/rfc3454.txt), + * and then with Punycode (http://www.ietf.org/rfc/rfc3492.txt). + * Implementations of IDNA MUST fully implement Nameprep and Punycode; + * neither Nameprep nor Punycode are optional. + * The input and output of ToASCII and ToUnicode operations are Unicode + * and are designed to be chainable, i.e., applying ToASCII or ToUnicode operations + * multiple times to an input string will yield the same result as applying the operation + * once. + * ToUnicode(ToUnicode(ToUnicode...(ToUnicode(string)))) == ToUnicode(string) + * ToASCII(ToASCII(ToASCII...(ToASCII(string))) == ToASCII(string). + * + * @param src Input UChar array containing label in Unicode. + * @param srcLength Number of UChars in src, or -1 if NUL-terminated. + * @param dest Output UChar array with ASCII (ACE encoded) label. + * @param destCapacity Size of dest. + * @param options A bit set of options: + * + * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points + * and do not use STD3 ASCII rules + * If unassigned code points are found the operation fails with + * U_UNASSIGNED_ERROR error code. + * + * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations + * If this option is set, the unassigned code points are in the input + * are treated as normal Unicode code points. + * + * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions + * If this option is set and the input does not satisfy STD3 rules, + * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR + * + * @param parseError Pointer to UParseError struct to receive information on position + * of error if an error is encountered. Can be NULL. + * @param status ICU in/out error code parameter. + * U_INVALID_CHAR_FOUND if src contains + * unmatched single surrogates. + * U_INDEX_OUTOFBOUNDS_ERROR if src contains + * too many code points. + * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ +U_DEPRECATED int32_t U_EXPORT2 +uidna_toASCII(const UChar* src, int32_t srcLength, + UChar* dest, int32_t destCapacity, + int32_t options, + UParseError* parseError, + UErrorCode* status); + + +/** + * IDNA2003: This function implements the ToUnicode operation as defined in the IDNA RFC. + * This operation is done on single labels before sending it to something that expects + * Unicode names. A label is an individual part of a domain name. Labels are usually + * separated by dots; for e.g. "www.example.com" is composed of 3 labels "www","example", and "com". + * + * @param src Input UChar array containing ASCII (ACE encoded) label. + * @param srcLength Number of UChars in src, or -1 if NUL-terminated. + * @param dest Output Converted UChar array containing Unicode equivalent of label. + * @param destCapacity Size of dest. + * @param options A bit set of options: + * + * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points + * and do not use STD3 ASCII rules + * If unassigned code points are found the operation fails with + * U_UNASSIGNED_ERROR error code. + * + * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations + * If this option is set, the unassigned code points are in the input + * are treated as normal Unicode code points. Note: This option is + * required on toUnicode operation because the RFC mandates + * verification of decoded ACE input by applying toASCII and comparing + * its output with source + * + * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions + * If this option is set and the input does not satisfy STD3 rules, + * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR + * + * @param parseError Pointer to UParseError struct to receive information on position + * of error if an error is encountered. Can be NULL. + * @param status ICU in/out error code parameter. + * U_INVALID_CHAR_FOUND if src contains + * unmatched single surrogates. + * U_INDEX_OUTOFBOUNDS_ERROR if src contains + * too many code points. + * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ +U_DEPRECATED int32_t U_EXPORT2 +uidna_toUnicode(const UChar* src, int32_t srcLength, + UChar* dest, int32_t destCapacity, + int32_t options, + UParseError* parseError, + UErrorCode* status); + + +/** + * IDNA2003: Convenience function that implements the IDNToASCII operation as defined in the IDNA RFC. + * This operation is done on complete domain names, e.g: "www.example.com". + * It is important to note that this operation can fail. If it fails, then the input + * domain name cannot be used as an Internationalized Domain Name and the application + * should have methods defined to deal with the failure. + * + * Note: IDNA RFC specifies that a conformant application should divide a domain name + * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, + * and then convert. This function does not offer that level of granularity. The options once + * set will apply to all labels in the domain name + * + * @param src Input UChar array containing IDN in Unicode. + * @param srcLength Number of UChars in src, or -1 if NUL-terminated. + * @param dest Output UChar array with ASCII (ACE encoded) IDN. + * @param destCapacity Size of dest. + * @param options A bit set of options: + * + * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points + * and do not use STD3 ASCII rules + * If unassigned code points are found the operation fails with + * U_UNASSIGNED_CODE_POINT_FOUND error code. + * + * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations + * If this option is set, the unassigned code points are in the input + * are treated as normal Unicode code points. + * + * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions + * If this option is set and the input does not satisfy STD3 rules, + * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR + * + * @param parseError Pointer to UParseError struct to receive information on position + * of error if an error is encountered. Can be NULL. + * @param status ICU in/out error code parameter. + * U_INVALID_CHAR_FOUND if src contains + * unmatched single surrogates. + * U_INDEX_OUTOFBOUNDS_ERROR if src contains + * too many code points. + * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ +U_DEPRECATED int32_t U_EXPORT2 +uidna_IDNToASCII( const UChar* src, int32_t srcLength, + UChar* dest, int32_t destCapacity, + int32_t options, + UParseError* parseError, + UErrorCode* status); + +/** + * IDNA2003: Convenience function that implements the IDNToUnicode operation as defined in the IDNA RFC. + * This operation is done on complete domain names, e.g: "www.example.com". + * + * Note: IDNA RFC specifies that a conformant application should divide a domain name + * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, + * and then convert. This function does not offer that level of granularity. The options once + * set will apply to all labels in the domain name + * + * @param src Input UChar array containing IDN in ASCII (ACE encoded) form. + * @param srcLength Number of UChars in src, or -1 if NUL-terminated. + * @param dest Output UChar array containing Unicode equivalent of source IDN. + * @param destCapacity Size of dest. + * @param options A bit set of options: + * + * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points + * and do not use STD3 ASCII rules + * If unassigned code points are found the operation fails with + * U_UNASSIGNED_CODE_POINT_FOUND error code. + * + * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations + * If this option is set, the unassigned code points are in the input + * are treated as normal Unicode code points. + * + * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions + * If this option is set and the input does not satisfy STD3 rules, + * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR + * + * @param parseError Pointer to UParseError struct to receive information on position + * of error if an error is encountered. Can be NULL. + * @param status ICU in/out error code parameter. + * U_INVALID_CHAR_FOUND if src contains + * unmatched single surrogates. + * U_INDEX_OUTOFBOUNDS_ERROR if src contains + * too many code points. + * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough + * @return The length of the result string, if successful - or in case of a buffer overflow, + * in which case it will be greater than destCapacity. + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ +U_DEPRECATED int32_t U_EXPORT2 +uidna_IDNToUnicode( const UChar* src, int32_t srcLength, + UChar* dest, int32_t destCapacity, + int32_t options, + UParseError* parseError, + UErrorCode* status); + +/** + * IDNA2003: Compare two IDN strings for equivalence. + * This function splits the domain names into labels and compares them. + * According to IDN RFC, whenever two labels are compared, they are + * considered equal if and only if their ASCII forms (obtained by + * applying toASCII) match using an case-insensitive ASCII comparison. + * Two domain names are considered a match if and only if all labels + * match regardless of whether label separators match. + * + * @param s1 First source string. + * @param length1 Length of first source string, or -1 if NUL-terminated. + * + * @param s2 Second source string. + * @param length2 Length of second source string, or -1 if NUL-terminated. + * @param options A bit set of options: + * + * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points + * and do not use STD3 ASCII rules + * If unassigned code points are found the operation fails with + * U_UNASSIGNED_CODE_POINT_FOUND error code. + * + * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations + * If this option is set, the unassigned code points are in the input + * are treated as normal Unicode code points. + * + * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions + * If this option is set and the input does not satisfy STD3 rules, + * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR + * + * @param status ICU error code in/out parameter. + * Must fulfill U_SUCCESS before the function call. + * @return <0 or 0 or >0 as usual for string comparisons + * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. + */ +U_DEPRECATED int32_t U_EXPORT2 +uidna_compare( const UChar *s1, int32_t length1, + const UChar *s2, int32_t length2, + int32_t options, + UErrorCode* status); + +#endif /* U_HIDE_DEPRECATED_API */ + +#endif /* #if !UCONFIG_NO_IDNA */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uiter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uiter.h new file mode 100644 index 0000000000000000000000000000000000000000..be232c774dc614e48fca28a002c5b95b3bd0e15c --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uiter.h @@ -0,0 +1,709 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* +* Copyright (C) 2002-2011 International Business Machines +* Corporation and others. All Rights Reserved. +* +******************************************************************************* +* file name: uiter.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2002jan18 +* created by: Markus W. Scherer +*/ + +#ifndef __UITER_H__ +#define __UITER_H__ + +/** + * \file + * \brief C API: Unicode Character Iteration + * + * @see UCharIterator + */ + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + U_NAMESPACE_BEGIN + + class CharacterIterator; + class Replaceable; + + U_NAMESPACE_END +#endif + +U_CDECL_BEGIN + +struct UCharIterator; +typedef struct UCharIterator UCharIterator; /**< C typedef for struct UCharIterator. @stable ICU 2.1 */ + +/** + * Origin constants for UCharIterator.getIndex() and UCharIterator.move(). + * @see UCharIteratorMove + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef enum UCharIteratorOrigin { + UITER_START, UITER_CURRENT, UITER_LIMIT, UITER_ZERO, UITER_LENGTH +} UCharIteratorOrigin; + +/** Constants for UCharIterator. @stable ICU 2.6 */ +enum { + /** + * Constant value that may be returned by UCharIteratorMove + * indicating that the final UTF-16 index is not known, but that the move succeeded. + * This can occur when moving relative to limit or length, or + * when moving relative to the current index after a setState() + * when the current UTF-16 index is not known. + * + * It would be very inefficient to have to count from the beginning of the text + * just to get the current/limit/length index after moving relative to it. + * The actual index can be determined with getIndex(UITER_CURRENT) + * which will count the UChars if necessary. + * + * @stable ICU 2.6 + */ + UITER_UNKNOWN_INDEX=-2 +}; + + +/** + * Constant for UCharIterator getState() indicating an error or + * an unknown state. + * Returned by uiter_getState()/UCharIteratorGetState + * when an error occurs. + * Also, some UCharIterator implementations may not be able to return + * a valid state for each position. This will be clearly documented + * for each such iterator (none of the public ones here). + * + * @stable ICU 2.6 + */ +#define UITER_NO_STATE ((uint32_t)0xffffffff) + +/** + * Function type declaration for UCharIterator.getIndex(). + * + * Gets the current position, or the start or limit of the + * iteration range. + * + * This function may perform slowly for UITER_CURRENT after setState() was called, + * or for UITER_LENGTH, because an iterator implementation may have to count + * UChars if the underlying storage is not UTF-16. + * + * @param iter the UCharIterator structure ("this pointer") + * @param origin get the 0, start, limit, length, or current index + * @return the requested index, or U_SENTINEL in an error condition + * + * @see UCharIteratorOrigin + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef int32_t U_CALLCONV +UCharIteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin); + +/** + * Function type declaration for UCharIterator.move(). + * + * Use iter->move(iter, index, UITER_ZERO) like CharacterIterator::setIndex(index). + * + * Moves the current position relative to the start or limit of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code units forward + * or backward by specifying a positive or negative delta. + * Out of bounds movement will be pinned to the start or limit. + * + * This function may perform slowly for moving relative to UITER_LENGTH + * because an iterator implementation may have to count the rest of the + * UChars if the native storage is not UTF-16. + * + * When moving relative to the limit or length, or + * relative to the current position after setState() was called, + * move() may return UITER_UNKNOWN_INDEX (-2) to avoid an inefficient + * determination of the actual UTF-16 index. + * The actual index can be determined with getIndex(UITER_CURRENT) + * which will count the UChars if necessary. + * See UITER_UNKNOWN_INDEX for details. + * + * @param iter the UCharIterator structure ("this pointer") + * @param delta can be positive, zero, or negative + * @param origin move relative to the 0, start, limit, length, or current index + * @return the new index, or U_SENTINEL on an error condition, + * or UITER_UNKNOWN_INDEX when the index is not known. + * + * @see UCharIteratorOrigin + * @see UCharIterator + * @see UITER_UNKNOWN_INDEX + * @stable ICU 2.1 + */ +typedef int32_t U_CALLCONV +UCharIteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin); + +/** + * Function type declaration for UCharIterator.hasNext(). + * + * Check if current() and next() can still + * return another code unit. + * + * @param iter the UCharIterator structure ("this pointer") + * @return boolean value for whether current() and next() can still return another code unit + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef UBool U_CALLCONV +UCharIteratorHasNext(UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.hasPrevious(). + * + * Check if previous() can still return another code unit. + * + * @param iter the UCharIterator structure ("this pointer") + * @return boolean value for whether previous() can still return another code unit + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef UBool U_CALLCONV +UCharIteratorHasPrevious(UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.current(). + * + * Return the code unit at the current position, + * or U_SENTINEL if there is none (index is at the limit). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the current code unit + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef UChar32 U_CALLCONV +UCharIteratorCurrent(UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.next(). + * + * Return the code unit at the current index and increment + * the index (post-increment, like s[i++]), + * or return U_SENTINEL if there is none (index is at the limit). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the current code unit (and post-increment the current index) + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef UChar32 U_CALLCONV +UCharIteratorNext(UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.previous(). + * + * Decrement the index and return the code unit from there + * (pre-decrement, like s[--i]), + * or return U_SENTINEL if there is none (index is at the start). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the previous code unit (after pre-decrementing the current index) + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef UChar32 U_CALLCONV +UCharIteratorPrevious(UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.reservedFn(). + * Reserved for future use. + * + * @param iter the UCharIterator structure ("this pointer") + * @param something some integer argument + * @return some integer + * + * @see UCharIterator + * @stable ICU 2.1 + */ +typedef int32_t U_CALLCONV +UCharIteratorReserved(UCharIterator *iter, int32_t something); + +/** + * Function type declaration for UCharIterator.getState(). + * + * Get the "state" of the iterator in the form of a single 32-bit word. + * It is recommended that the state value be calculated to be as small as + * is feasible. For strings with limited lengths, fewer than 32 bits may + * be sufficient. + * + * This is used together with setState()/UCharIteratorSetState + * to save and restore the iterator position more efficiently than with + * getIndex()/move(). + * + * The iterator state is defined as a uint32_t value because it is designed + * for use in ucol_nextSortKeyPart() which provides 32 bits to store the state + * of the character iterator. + * + * With some UCharIterator implementations (e.g., UTF-8), + * getting and setting the UTF-16 index with existing functions + * (getIndex(UITER_CURRENT) followed by move(pos, UITER_ZERO)) is possible but + * relatively slow because the iterator has to "walk" from a known index + * to the requested one. + * This takes more time the farther it needs to go. + * + * An opaque state value allows an iterator implementation to provide + * an internal index (UTF-8: the source byte array index) for + * fast, constant-time restoration. + * + * After calling setState(), a getIndex(UITER_CURRENT) may be slow because + * the UTF-16 index may not be restored as well, but the iterator can deliver + * the correct text contents and move relative to the current position + * without performance degradation. + * + * Some UCharIterator implementations may not be able to return + * a valid state for each position, in which case they return UITER_NO_STATE instead. + * This will be clearly documented for each such iterator (none of the public ones here). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the state word + * + * @see UCharIterator + * @see UCharIteratorSetState + * @see UITER_NO_STATE + * @stable ICU 2.6 + */ +typedef uint32_t U_CALLCONV +UCharIteratorGetState(const UCharIterator *iter); + +/** + * Function type declaration for UCharIterator.setState(). + * + * Restore the "state" of the iterator using a state word from a getState() call. + * The iterator object need not be the same one as for which getState() was called, + * but it must be of the same type (set up using the same uiter_setXYZ function) + * and it must iterate over the same string + * (binary identical regardless of memory address). + * For more about the state word see UCharIteratorGetState. + * + * After calling setState(), a getIndex(UITER_CURRENT) may be slow because + * the UTF-16 index may not be restored as well, but the iterator can deliver + * the correct text contents and move relative to the current position + * without performance degradation. + * + * @param iter the UCharIterator structure ("this pointer") + * @param state the state word from a getState() call + * on a same-type, same-string iterator + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * + * @see UCharIterator + * @see UCharIteratorGetState + * @stable ICU 2.6 + */ +typedef void U_CALLCONV +UCharIteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode); + + +/** + * C API for code unit iteration. + * This can be used as a C wrapper around + * CharacterIterator, Replaceable, or implemented using simple strings, etc. + * + * There are two roles for using UCharIterator: + * + * A "provider" sets the necessary function pointers and controls the "protected" + * fields of the UCharIterator structure. A "provider" passes a UCharIterator + * into C APIs that need a UCharIterator as an abstract, flexible string interface. + * + * Implementations of such C APIs are "callers" of UCharIterator functions; + * they only use the "public" function pointers and never access the "protected" + * fields directly. + * + * The current() and next() functions only check the current index against the + * limit, and previous() only checks the current index against the start, + * to see if the iterator already reached the end of the iteration range. + * + * The assumption - in all iterators - is that the index is moved via the API, + * which means it won't go out of bounds, or the index is modified by + * user code that knows enough about the iterator implementation to set valid + * index values. + * + * UCharIterator functions return code unit values 0..0xffff, + * or U_SENTINEL if the iteration bounds are reached. + * + * @stable ICU 2.1 + */ +struct UCharIterator { + /** + * (protected) Pointer to string or wrapped object or similar. + * Not used by caller. + * @stable ICU 2.1 + */ + const void *context; + + /** + * (protected) Length of string or similar. + * Not used by caller. + * @stable ICU 2.1 + */ + int32_t length; + + /** + * (protected) Start index or similar. + * Not used by caller. + * @stable ICU 2.1 + */ + int32_t start; + + /** + * (protected) Current index or similar. + * Not used by caller. + * @stable ICU 2.1 + */ + int32_t index; + + /** + * (protected) Limit index or similar. + * Not used by caller. + * @stable ICU 2.1 + */ + int32_t limit; + + /** + * (protected) Used by UTF-8 iterators and possibly others. + * @stable ICU 2.1 + */ + int32_t reservedField; + + /** + * (public) Returns the current position or the + * start or limit index of the iteration range. + * + * @see UCharIteratorGetIndex + * @stable ICU 2.1 + */ + UCharIteratorGetIndex *getIndex; + + /** + * (public) Moves the current position relative to the start or limit of the + * iteration range, or relative to the current position itself. + * The movement is expressed in numbers of code units forward + * or backward by specifying a positive or negative delta. + * + * @see UCharIteratorMove + * @stable ICU 2.1 + */ + UCharIteratorMove *move; + + /** + * (public) Check if current() and next() can still + * return another code unit. + * + * @see UCharIteratorHasNext + * @stable ICU 2.1 + */ + UCharIteratorHasNext *hasNext; + + /** + * (public) Check if previous() can still return another code unit. + * + * @see UCharIteratorHasPrevious + * @stable ICU 2.1 + */ + UCharIteratorHasPrevious *hasPrevious; + + /** + * (public) Return the code unit at the current position, + * or U_SENTINEL if there is none (index is at the limit). + * + * @see UCharIteratorCurrent + * @stable ICU 2.1 + */ + UCharIteratorCurrent *current; + + /** + * (public) Return the code unit at the current index and increment + * the index (post-increment, like s[i++]), + * or return U_SENTINEL if there is none (index is at the limit). + * + * @see UCharIteratorNext + * @stable ICU 2.1 + */ + UCharIteratorNext *next; + + /** + * (public) Decrement the index and return the code unit from there + * (pre-decrement, like s[--i]), + * or return U_SENTINEL if there is none (index is at the start). + * + * @see UCharIteratorPrevious + * @stable ICU 2.1 + */ + UCharIteratorPrevious *previous; + + /** + * (public) Reserved for future use. Currently NULL. + * + * @see UCharIteratorReserved + * @stable ICU 2.1 + */ + UCharIteratorReserved *reservedFn; + + /** + * (public) Return the state of the iterator, to be restored later with setState(). + * This function pointer is NULL if the iterator does not implement it. + * + * @see UCharIteratorGet + * @stable ICU 2.6 + */ + UCharIteratorGetState *getState; + + /** + * (public) Restore the iterator state from the state word from a call + * to getState(). + * This function pointer is NULL if the iterator does not implement it. + * + * @see UCharIteratorSet + * @stable ICU 2.6 + */ + UCharIteratorSetState *setState; +}; + +/** + * Helper function for UCharIterator to get the code point + * at the current index. + * + * Return the code point that includes the code unit at the current position, + * or U_SENTINEL if there is none (index is at the limit). + * If the current code unit is a lead or trail surrogate, + * then the following or preceding surrogate is used to form + * the code point value. + * + * @param iter the UCharIterator structure ("this pointer") + * @return the current code point + * + * @see UCharIterator + * @see U16_GET + * @see UnicodeString::char32At() + * @stable ICU 2.1 + */ +U_CAPI UChar32 U_EXPORT2 +uiter_current32(UCharIterator *iter); + +/** + * Helper function for UCharIterator to get the next code point. + * + * Return the code point at the current index and increment + * the index (post-increment, like s[i++]), + * or return U_SENTINEL if there is none (index is at the limit). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the current code point (and post-increment the current index) + * + * @see UCharIterator + * @see U16_NEXT + * @stable ICU 2.1 + */ +U_CAPI UChar32 U_EXPORT2 +uiter_next32(UCharIterator *iter); + +/** + * Helper function for UCharIterator to get the previous code point. + * + * Decrement the index and return the code point from there + * (pre-decrement, like s[--i]), + * or return U_SENTINEL if there is none (index is at the start). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the previous code point (after pre-decrementing the current index) + * + * @see UCharIterator + * @see U16_PREV + * @stable ICU 2.1 + */ +U_CAPI UChar32 U_EXPORT2 +uiter_previous32(UCharIterator *iter); + +/** + * Get the "state" of the iterator in the form of a single 32-bit word. + * This is a convenience function that calls iter->getState(iter) + * if iter->getState is not NULL; + * if it is NULL or any other error occurs, then UITER_NO_STATE is returned. + * + * Some UCharIterator implementations may not be able to return + * a valid state for each position, in which case they return UITER_NO_STATE instead. + * This will be clearly documented for each such iterator (none of the public ones here). + * + * @param iter the UCharIterator structure ("this pointer") + * @return the state word + * + * @see UCharIterator + * @see UCharIteratorGetState + * @see UITER_NO_STATE + * @stable ICU 2.6 + */ +U_CAPI uint32_t U_EXPORT2 +uiter_getState(const UCharIterator *iter); + +/** + * Restore the "state" of the iterator using a state word from a getState() call. + * This is a convenience function that calls iter->setState(iter, state, pErrorCode) + * if iter->setState is not NULL; if it is NULL, then U_UNSUPPORTED_ERROR is set. + * + * @param iter the UCharIterator structure ("this pointer") + * @param state the state word from a getState() call + * on a same-type, same-string iterator + * @param pErrorCode Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * + * @see UCharIterator + * @see UCharIteratorSetState + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +uiter_setState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode); + +/** + * Set up a UCharIterator to iterate over a string. + * + * Sets the UCharIterator function pointers for iteration over the string s + * with iteration boundaries start=index=0 and length=limit=string length. + * The "provider" may set the start, index, and limit values at any time + * within the range 0..length. + * The length field will be ignored. + * + * The string pointer s is set into UCharIterator.context without copying + * or reallocating the string contents. + * + * getState() simply returns the current index. + * move() will always return the final index. + * + * @param iter UCharIterator structure to be set for iteration + * @param s String to iterate over + * @param length Length of s, or -1 if NUL-terminated + * + * @see UCharIterator + * @stable ICU 2.1 + */ +U_CAPI void U_EXPORT2 +uiter_setString(UCharIterator *iter, const UChar *s, int32_t length); + +/** + * Set up a UCharIterator to iterate over a UTF-16BE string + * (byte vector with a big-endian pair of bytes per UChar). + * + * Everything works just like with a normal UChar iterator (uiter_setString), + * except that UChars are assembled from byte pairs, + * and that the length argument here indicates an even number of bytes. + * + * getState() simply returns the current index. + * move() will always return the final index. + * + * @param iter UCharIterator structure to be set for iteration + * @param s UTF-16BE string to iterate over + * @param length Length of s as an even number of bytes, or -1 if NUL-terminated + * (NUL means pair of 0 bytes at even index from s) + * + * @see UCharIterator + * @see uiter_setString + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +uiter_setUTF16BE(UCharIterator *iter, const char *s, int32_t length); + +/** + * Set up a UCharIterator to iterate over a UTF-8 string. + * + * Sets the UCharIterator function pointers for iteration over the UTF-8 string s + * with UTF-8 iteration boundaries 0 and length. + * The implementation counts the UTF-16 index on the fly and + * lazily evaluates the UTF-16 length of the text. + * + * The start field is used as the UTF-8 offset, the limit field as the UTF-8 length. + * When the reservedField is not 0, then it contains a supplementary code point + * and the UTF-16 index is between the two corresponding surrogates. + * At that point, the UTF-8 index is behind that code point. + * + * The UTF-8 string pointer s is set into UCharIterator.context without copying + * or reallocating the string contents. + * + * getState() returns a state value consisting of + * - the current UTF-8 source byte index (bits 31..1) + * - a flag (bit 0) that indicates whether the UChar position is in the middle + * of a surrogate pair + * (from a 4-byte UTF-8 sequence for the corresponding supplementary code point) + * + * getState() cannot also encode the UTF-16 index in the state value. + * move(relative to limit or length), or + * move(relative to current) after setState(), may return UITER_UNKNOWN_INDEX. + * + * @param iter UCharIterator structure to be set for iteration + * @param s UTF-8 string to iterate over + * @param length Length of s in bytes, or -1 if NUL-terminated + * + * @see UCharIterator + * @stable ICU 2.6 + */ +U_CAPI void U_EXPORT2 +uiter_setUTF8(UCharIterator *iter, const char *s, int32_t length); + +#if U_SHOW_CPLUSPLUS_API + +/** + * Set up a UCharIterator to wrap around a C++ CharacterIterator. + * + * Sets the UCharIterator function pointers for iteration using the + * CharacterIterator charIter. + * + * The CharacterIterator pointer charIter is set into UCharIterator.context + * without copying or cloning the CharacterIterator object. + * The other "protected" UCharIterator fields are set to 0 and will be ignored. + * The iteration index and boundaries are controlled by the CharacterIterator. + * + * getState() simply returns the current index. + * move() will always return the final index. + * + * @param iter UCharIterator structure to be set for iteration + * @param charIter CharacterIterator to wrap + * + * @see UCharIterator + * @stable ICU 2.1 + */ +U_CAPI void U_EXPORT2 +uiter_setCharacterIterator(UCharIterator *iter, icu::CharacterIterator *charIter); + +/** + * Set up a UCharIterator to iterate over a C++ Replaceable. + * + * Sets the UCharIterator function pointers for iteration over the + * Replaceable rep with iteration boundaries start=index=0 and + * length=limit=rep->length(). + * The "provider" may set the start, index, and limit values at any time + * within the range 0..length=rep->length(). + * The length field will be ignored. + * + * The Replaceable pointer rep is set into UCharIterator.context without copying + * or cloning/reallocating the Replaceable object. + * + * getState() simply returns the current index. + * move() will always return the final index. + * + * @param iter UCharIterator structure to be set for iteration + * @param rep Replaceable to iterate over + * + * @see UCharIterator + * @stable ICU 2.1 + */ +U_CAPI void U_EXPORT2 +uiter_setReplaceable(UCharIterator *iter, const icu::Replaceable *rep); + +#endif + +U_CDECL_END + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uldnames.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uldnames.h new file mode 100644 index 0000000000000000000000000000000000000000..47b047ece97b80fcb5a2e2629633e96b68e9b3f7 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uldnames.h @@ -0,0 +1,307 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +******************************************************************************* +* Copyright (C) 2010-2016, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +*/ + +#ifndef __ULDNAMES_H__ +#define __ULDNAMES_H__ + +/** + * \file + * \brief C API: Provides display names of Locale ids and their components. + */ + +#include "unicode/utypes.h" +#include "unicode/uscript.h" +#include "unicode/udisplaycontext.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * Enum used in LocaleDisplayNames::createInstance. + * @stable ICU 4.4 + */ +typedef enum { + /** + * Use standard names when generating a locale name, + * e.g. en_GB displays as 'English (United Kingdom)'. + * @stable ICU 4.4 + */ + ULDN_STANDARD_NAMES = 0, + /** + * Use dialect names, when generating a locale name, + * e.g. en_GB displays as 'British English'. + * @stable ICU 4.4 + */ + ULDN_DIALECT_NAMES +} UDialectHandling; + +/** + * Opaque C service object type for the locale display names API + * @stable ICU 4.4 + */ +struct ULocaleDisplayNames; + +/** + * C typedef for struct ULocaleDisplayNames. + * @stable ICU 4.4 + */ +typedef struct ULocaleDisplayNames ULocaleDisplayNames; + +#if !UCONFIG_NO_FORMATTING + +/** + * Returns an instance of LocaleDisplayNames that returns names + * formatted for the provided locale, using the provided + * dialectHandling. The usual value for dialectHandling is + * ULOC_STANDARD_NAMES. + * + * @param locale the display locale + * @param dialectHandling how to select names for locales + * @return a ULocaleDisplayNames instance + * @param pErrorCode the status code + * @stable ICU 4.4 + */ +U_CAPI ULocaleDisplayNames * U_EXPORT2 +uldn_open(const char * locale, + UDialectHandling dialectHandling, + UErrorCode *pErrorCode); + +/** + * Closes a ULocaleDisplayNames instance obtained from uldn_open(). + * @param ldn the ULocaleDisplayNames instance to be closed + * @stable ICU 4.4 + */ +U_CAPI void U_EXPORT2 +uldn_close(ULocaleDisplayNames *ldn); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalULocaleDisplayNamesPointer + * "Smart pointer" class, closes a ULocaleDisplayNames via uldn_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalULocaleDisplayNamesPointer, ULocaleDisplayNames, uldn_close); + +U_NAMESPACE_END + +#endif + +/* getters for state */ + +/** + * Returns the locale used to determine the display names. This is + * not necessarily the same locale passed to {@link #uldn_open}. + * @param ldn the LocaleDisplayNames instance + * @return the display locale + * @stable ICU 4.4 + */ +U_CAPI const char * U_EXPORT2 +uldn_getLocale(const ULocaleDisplayNames *ldn); + +/** + * Returns the dialect handling used in the display names. + * @param ldn the LocaleDisplayNames instance + * @return the dialect handling enum + * @stable ICU 4.4 + */ +U_CAPI UDialectHandling U_EXPORT2 +uldn_getDialectHandling(const ULocaleDisplayNames *ldn); + +/* names for entire locales */ + +/** + * Returns the display name of the provided locale. + * @param ldn the LocaleDisplayNames instance + * @param locale the locale whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_localeDisplayName(const ULocaleDisplayNames *ldn, + const char *locale, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/* names for components of a locale */ + +/** + * Returns the display name of the provided language code. + * @param ldn the LocaleDisplayNames instance + * @param lang the language code whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_languageDisplayName(const ULocaleDisplayNames *ldn, + const char *lang, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided script. + * @param ldn the LocaleDisplayNames instance + * @param script the script whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_scriptDisplayName(const ULocaleDisplayNames *ldn, + const char *script, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided script code. + * @param ldn the LocaleDisplayNames instance + * @param scriptCode the script code whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_scriptCodeDisplayName(const ULocaleDisplayNames *ldn, + UScriptCode scriptCode, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided region code. + * @param ldn the LocaleDisplayNames instance + * @param region the region code whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_regionDisplayName(const ULocaleDisplayNames *ldn, + const char *region, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided variant + * @param ldn the LocaleDisplayNames instance + * @param variant the variant whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_variantDisplayName(const ULocaleDisplayNames *ldn, + const char *variant, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided locale key + * @param ldn the LocaleDisplayNames instance + * @param key the locale key whose display name to return + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_keyDisplayName(const ULocaleDisplayNames *ldn, + const char *key, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** + * Returns the display name of the provided value (used with the provided key). + * @param ldn the LocaleDisplayNames instance + * @param key the locale key + * @param value the locale key's value + * @param result receives the display name + * @param maxResultSize the size of the result buffer + * @param pErrorCode the status code + * @return the actual buffer size needed for the display name. If it's + * greater than maxResultSize, the returned name will be truncated. + * @stable ICU 4.4 + */ +U_CAPI int32_t U_EXPORT2 +uldn_keyValueDisplayName(const ULocaleDisplayNames *ldn, + const char *key, + const char *value, + UChar *result, + int32_t maxResultSize, + UErrorCode *pErrorCode); + +/** +* Returns an instance of LocaleDisplayNames that returns names formatted +* for the provided locale, using the provided UDisplayContext settings. +* +* @param locale The display locale +* @param contexts List of one or more context settings (e.g. for dialect +* handling, capitalization, etc. +* @param length Number of items in the contexts list +* @param pErrorCode Pointer to UErrorCode input/output status. If at entry this indicates +* a failure status, the function will do nothing; otherwise this will be +* updated with any new status from the function. +* @return a ULocaleDisplayNames instance +* @stable ICU 51 +*/ +U_CAPI ULocaleDisplayNames * U_EXPORT2 +uldn_openForContext(const char * locale, UDisplayContext *contexts, + int32_t length, UErrorCode *pErrorCode); + +/** +* Returns the UDisplayContext value for the specified UDisplayContextType. +* @param ldn the ULocaleDisplayNames instance +* @param type the UDisplayContextType whose value to return +* @param pErrorCode Pointer to UErrorCode input/output status. If at entry this indicates +* a failure status, the function will do nothing; otherwise this will be +* updated with any new status from the function. +* @return the UDisplayContextValue for the specified type. +* @stable ICU 51 +*/ +U_CAPI UDisplayContext U_EXPORT2 +uldn_getContext(const ULocaleDisplayNames *ldn, UDisplayContextType type, + UErrorCode *pErrorCode); + +#endif /* !UCONFIG_NO_FORMATTING */ +#endif /* __ULDNAMES_H__ */ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulistformatter.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulistformatter.h new file mode 100644 index 0000000000000000000000000000000000000000..8334c7852f0cc965599966033936843af652b960 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulistformatter.h @@ -0,0 +1,333 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +***************************************************************************************** +* Copyright (C) 2015-2016, International Business Machines +* Corporation and others. All Rights Reserved. +***************************************************************************************** +*/ + +#ifndef ULISTFORMATTER_H +#define ULISTFORMATTER_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uformattedvalue.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Format a list in a locale-appropriate way. + * + * A UListFormatter is used to format a list of items in a locale-appropriate way, + * using data from CLDR. + * Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted + * as "Alice, Bob, Charlie, and Delta" in English. + */ + +/** + * Opaque UListFormatter object for use in C + * @stable ICU 55 + */ +struct UListFormatter; +typedef struct UListFormatter UListFormatter; /**< C typedef for struct UListFormatter. @stable ICU 55 */ + +struct UFormattedList; +/** + * Opaque struct to contain the results of a UListFormatter operation. + * @stable ICU 64 + */ +typedef struct UFormattedList UFormattedList; + +/** + * FieldPosition and UFieldPosition selectors for format fields + * defined by ListFormatter. + * @stable ICU 63 + */ +typedef enum UListFormatterField { + /** + * The literal text in the result which came from the resources. + * @stable ICU 63 + */ + ULISTFMT_LITERAL_FIELD, + /** + * The element text in the result which came from the input strings. + * @stable ICU 63 + */ + ULISTFMT_ELEMENT_FIELD +} UListFormatterField; + +/** + * Type of meaning expressed by the list. + * + * @stable ICU 67 + */ +typedef enum UListFormatterType { + /** + * Conjunction formatting, e.g. "Alice, Bob, Charlie, and Delta". + * + * @stable ICU 67 + */ + ULISTFMT_TYPE_AND, + + /** + * Disjunction (or alternative, or simply one of) formatting, e.g. + * "Alice, Bob, Charlie, or Delta". + * + * @stable ICU 67 + */ + ULISTFMT_TYPE_OR, + + /** + * Formatting of a list of values with units, e.g. "5 pounds, 12 ounces". + * + * @stable ICU 67 + */ + ULISTFMT_TYPE_UNITS +} UListFormatterType; + +/** + * Verbosity level of the list patterns. + * + * @stable ICU 67 + */ +typedef enum UListFormatterWidth { + /** + * Use list formatting with full words (no abbreviations) when possible. + * + * @stable ICU 67 + */ + ULISTFMT_WIDTH_WIDE, + + /** + * Use list formatting of typical length. + * @stable ICU 67 + */ + ULISTFMT_WIDTH_SHORT, + + /** + * Use list formatting of the shortest possible length. + * @stable ICU 67 + */ + ULISTFMT_WIDTH_NARROW, +} UListFormatterWidth; + +/** + * Open a new UListFormatter object using the rules for a given locale. + * The object will be initialized with AND type and WIDE width. + * + * @param locale + * The locale whose rules should be used; may be NULL for + * default locale. + * @param status + * A pointer to a standard ICU UErrorCode (input/output parameter). + * Its input value must pass the U_SUCCESS() test, or else the + * function returns immediately. The caller should check its output + * value with U_FAILURE(), or use with function chaining (see User + * Guide for details). + * @return + * A pointer to a UListFormatter object for the specified locale, + * or NULL if an error occurred. + * @stable ICU 55 + */ +U_CAPI UListFormatter* U_EXPORT2 +ulistfmt_open(const char* locale, + UErrorCode* status); + +/** + * Open a new UListFormatter object appropriate for the given locale, list type, + * and style. + * + * @param locale + * The locale whose rules should be used; may be NULL for + * default locale. + * @param type + * The type of list formatting to use. + * @param width + * The width of formatting to use. + * @param status + * A pointer to a standard ICU UErrorCode (input/output parameter). + * Its input value must pass the U_SUCCESS() test, or else the + * function returns immediately. The caller should check its output + * value with U_FAILURE(), or use with function chaining (see User + * Guide for details). + * @return + * A pointer to a UListFormatter object for the specified locale, + * or NULL if an error occurred. + * @stable ICU 67 + */ +U_CAPI UListFormatter* U_EXPORT2 +ulistfmt_openForType(const char* locale, UListFormatterType type, + UListFormatterWidth width, UErrorCode* status); + +/** + * Close a UListFormatter object. Once closed it may no longer be used. + * @param listfmt + * The UListFormatter object to close. + * @stable ICU 55 + */ +U_CAPI void U_EXPORT2 +ulistfmt_close(UListFormatter *listfmt); + +/** + * Creates an object to hold the result of a UListFormatter + * operation. The object can be used repeatedly; it is cleared whenever + * passed to a format function. + * + * @param ec Set if an error occurs. + * @return A pointer needing ownership. + * @stable ICU 64 + */ +U_CAPI UFormattedList* U_EXPORT2 +ulistfmt_openResult(UErrorCode* ec); + +/** + * Returns a representation of a UFormattedList as a UFormattedValue, + * which can be subsequently passed to any API requiring that type. + * + * The returned object is owned by the UFormattedList and is valid + * only as long as the UFormattedList is present and unchanged in memory. + * + * You can think of this method as a cast between types. + * + * When calling ufmtval_nextPosition(): + * The fields are returned from start to end. The special field category + * UFIELD_CATEGORY_LIST_SPAN is used to indicate which argument + * was inserted at the given position. The span category will + * always occur before the corresponding instance of UFIELD_CATEGORY_LIST + * in the ufmtval_nextPosition() iterator. + * + * @param uresult The object containing the formatted string. + * @param ec Set if an error occurs. + * @return A UFormattedValue owned by the input object. + * @stable ICU 64 + */ +U_CAPI const UFormattedValue* U_EXPORT2 +ulistfmt_resultAsValue(const UFormattedList* uresult, UErrorCode* ec); + +/** + * Releases the UFormattedList created by ulistfmt_openResult(). + * + * @param uresult The object to release. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ulistfmt_closeResult(UFormattedList* uresult); + + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUListFormatterPointer + * "Smart pointer" class, closes a UListFormatter via ulistfmt_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 55 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUListFormatterPointer, UListFormatter, ulistfmt_close); + +/** + * \class LocalUFormattedListPointer + * "Smart pointer" class, closes a UFormattedList via ulistfmt_closeResult(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 64 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedListPointer, UFormattedList, ulistfmt_closeResult); + +U_NAMESPACE_END + +#endif + +/** + * Formats a list of strings using the conventions established for the + * UListFormatter object. + * @param listfmt + * The UListFormatter object specifying the list conventions. + * @param strings + * An array of pointers to UChar strings; the array length is + * specified by stringCount. Must be non-NULL if stringCount > 0. + * @param stringLengths + * An array of string lengths corresponding to the strings[] + * parameter; any individual length value may be negative to indicate + * that the corresponding strings[] entry is 0-terminated, or + * stringLengths itself may be NULL if all of the strings are + * 0-terminated. If non-NULL, the stringLengths array must have + * stringCount entries. + * @param stringCount + * the number of entries in strings[], and the number of entries + * in the stringLengths array if it is not NULL. Must be >= 0. + * @param result + * A pointer to a buffer to receive the formatted list. + * @param resultCapacity + * The maximum size of result. + * @param status + * A pointer to a standard ICU UErrorCode (input/output parameter). + * Its input value must pass the U_SUCCESS() test, or else the + * function returns immediately. The caller should check its output + * value with U_FAILURE(), or use with function chaining (see User + * Guide for details). + * @return + * The total buffer size needed; if greater than resultLength, the + * output was truncated. May be <=0 if unable to determine the + * total buffer size needed (e.g. for illegal arguments). + * @stable ICU 55 + */ +U_CAPI int32_t U_EXPORT2 +ulistfmt_format(const UListFormatter* listfmt, + const UChar* const strings[], + const int32_t * stringLengths, + int32_t stringCount, + UChar* result, + int32_t resultCapacity, + UErrorCode* status); + +/** + * Formats a list of strings to a UFormattedList, which exposes more + * information than the string exported by ulistfmt_format(). + * + * @param listfmt + * The UListFormatter object specifying the list conventions. + * @param strings + * An array of pointers to UChar strings; the array length is + * specified by stringCount. Must be non-NULL if stringCount > 0. + * @param stringLengths + * An array of string lengths corresponding to the strings[] + * parameter; any individual length value may be negative to indicate + * that the corresponding strings[] entry is 0-terminated, or + * stringLengths itself may be NULL if all of the strings are + * 0-terminated. If non-NULL, the stringLengths array must have + * stringCount entries. + * @param stringCount + * the number of entries in strings[], and the number of entries + * in the stringLengths array if it is not NULL. Must be >= 0. + * @param uresult + * The object in which to store the result of the list formatting + * operation. See ulistfmt_openResult(). + * @param status + * Error code set if an error occurred during formatting. + * @stable ICU 64 + */ +U_CAPI void U_EXPORT2 +ulistfmt_formatStringsToResult( + const UListFormatter* listfmt, + const UChar* const strings[], + const int32_t * stringLengths, + int32_t stringCount, + UFormattedList* uresult, + UErrorCode* status); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uloc.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uloc.h new file mode 100644 index 0000000000000000000000000000000000000000..21179c1b628e1cecbbb8a83fcff64b1d622ef46f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uloc.h @@ -0,0 +1,1393 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1997-2016, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* +* File ULOC.H +* +* Modification History: +* +* Date Name Description +* 04/01/97 aliu Creation. +* 08/22/98 stephen JDK 1.2 sync. +* 12/08/98 rtg New C API for Locale +* 03/30/99 damiba overhaul +* 03/31/99 helena Javadoc for uloc functions. +* 04/15/99 Madhu Updated Javadoc +******************************************************************************** +*/ + +#ifndef ULOC_H +#define ULOC_H + +#include "unicode/utypes.h" +#include "unicode/uenum.h" + +/** + * \file + * \brief C API: Locale ID functionality similar to C++ class Locale + * + *

ULoc C API for Locale

+ * A Locale represents a specific geographical, political, + * or cultural region. An operation that requires a Locale to perform + * its task is called locale-sensitive and uses the Locale + * to tailor information for the user. For example, displaying a number + * is a locale-sensitive operation--the number should be formatted + * according to the customs/conventions of the user's native country, + * region, or culture. In the C APIs, a locales is simply a const char string. + * + *

+ * You create a Locale with one of the three options listed below. + * Each of the component is separated by '_' in the locale string. + * \htmlonly

\endhtmlonly + *
+ * \code
+ *       newLanguage
+ * 
+ *       newLanguage + newCountry
+ * 
+ *       newLanguage + newCountry + newVariant
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * The first option is a valid ISO + * Language Code. These codes are the lower-case two-letter + * codes as defined by ISO-639. + * You can find a full list of these codes at a number of sites, such as: + *
+ * http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt + * + *

+ * The second option includes an additional ISO Country + * Code. These codes are the upper-case two-letter codes + * as defined by ISO-3166. + * You can find a full list of these codes at a number of sites, such as: + *
+ * http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html + * + *

+ * The third option requires another additional information--the + * Variant. + * The Variant codes are vendor and browser-specific. + * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. + * Where there are two variants, separate them with an underscore, and + * put the most important one first. For + * example, a Traditional Spanish collation might be referenced, with + * "ES", "ES", "Traditional_WIN". + * + *

+ * Because a Locale is just an identifier for a region, + * no validity check is performed when you specify a Locale. + * If you want to see whether particular resources are available for the + * Locale you asked for, you must query those resources. For + * example, ask the UNumberFormat for the locales it supports + * using its getAvailable method. + *
Note: When you ask for a resource for a particular + * locale, you get back the best available match, not necessarily + * precisely what you asked for. For more information, look at + * UResourceBundle. + * + *

+ * The Locale provides a number of convenient constants + * that you can use to specify the commonly used + * locales. For example, the following refers to a locale + * for the United States: + * \htmlonly

\endhtmlonly + *
+ * \code
+ *       ULOC_US
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * + *

+ * Once you've specified a locale you can query it for information about + * itself. Use uloc_getCountry to get the ISO Country Code and + * uloc_getLanguage to get the ISO Language Code. You can + * use uloc_getDisplayCountry to get the + * name of the country suitable for displaying to the user. Similarly, + * you can use uloc_getDisplayLanguage to get the name of + * the language suitable for displaying to the user. Interestingly, + * the uloc_getDisplayXXX methods are themselves locale-sensitive + * and have two versions: one that uses the default locale and one + * that takes a locale as an argument and displays the name or country in + * a language appropriate to that locale. + * + *

+ * The ICU provides a number of services that perform locale-sensitive + * operations. For example, the unum_xxx functions format + * numbers, currency, or percentages in a locale-sensitive manner. + *

+ * \htmlonly
\endhtmlonly + *
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     UNumberFormat *nf;
+ *     const char* myLocale = "fr_FR";
+ * 
+ *     nf = unum_open( UNUM_DEFAULT, NULL, success );          
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_CURRENCY, NULL, success );
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_PERCENT, NULL, success );   
+ *     unum_close(nf);
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * Each of these methods has two variants; one with an explicit locale + * and one without; the latter using the default locale. + * \htmlonly
\endhtmlonly + *
+ * \code 
+ * 
+ *     nf = unum_open( UNUM_DEFAULT, myLocale, success );          
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_CURRENCY, myLocale, success );
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_PERCENT, myLocale, success );   
+ *     unum_close(nf);
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + * A Locale is the mechanism for identifying the kind of services + * (UNumberFormat) that you would like to get. The locale is + * just a mechanism for identifying these services. + * + *

+ * Each international service that performs locale-sensitive operations + * allows you + * to get all the available objects of that type. You can sift + * through these objects by language, country, or variant, + * and use the display names to present a menu to the user. + * For example, you can create a menu of all the collation objects + * suitable for a given language. Such classes implement these + * three class methods: + * \htmlonly

\endhtmlonly + *
+ * \code
+ *       const char* uloc_getAvailable(int32_t index);
+ *       int32_t uloc_countAvailable();
+ *       int32_t
+ *       uloc_getDisplayName(const char* localeID,
+ *                 const char* inLocaleID, 
+ *                 UChar* result,
+ *                 int32_t maxResultSize,
+ *                  UErrorCode* err);
+ * 
+ * \endcode
+ * 
+ * \htmlonly
\endhtmlonly + *

+ * Concerning POSIX/RFC1766 Locale IDs, + * the getLanguage/getCountry/getVariant/getName functions do understand + * the POSIX type form of language_COUNTRY.ENCODING\@VARIANT + * and if there is not an ICU-stype variant, uloc_getVariant() for example + * will return the one listed after the \@at sign. As well, the hyphen + * "-" is recognized as a country/variant separator similarly to RFC1766. + * So for example, "en-us" will be interpreted as en_US. + * As a result, uloc_getName() is far from a no-op, and will have the + * effect of converting POSIX/RFC1766 IDs into ICU form, although it does + * NOT map any of the actual codes (i.e. russian->ru) in any way. + * Applications should call uloc_getName() at the point where a locale ID + * is coming from an external source (user entry, OS, web browser) + * and pass the resulting string to other ICU functions. For example, + * don't use de-de\@EURO as an argument to resourcebundle. + * + * @see UResourceBundle + */ + +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_CHINESE "zh" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_ENGLISH "en" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_FRENCH "fr" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_GERMAN "de" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_ITALIAN "it" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_JAPANESE "ja" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_KOREAN "ko" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_SIMPLIFIED_CHINESE "zh_CN" +/** Useful constant for this language. @stable ICU 2.0 */ +#define ULOC_TRADITIONAL_CHINESE "zh_TW" + +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_CANADA "en_CA" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_CANADA_FRENCH "fr_CA" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_CHINA "zh_CN" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_PRC "zh_CN" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_FRANCE "fr_FR" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_GERMANY "de_DE" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_ITALY "it_IT" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_JAPAN "ja_JP" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_KOREA "ko_KR" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_TAIWAN "zh_TW" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_UK "en_GB" +/** Useful constant for this country/region. @stable ICU 2.0 */ +#define ULOC_US "en_US" + +/** + * Useful constant for the maximum size of the language part of a locale ID. + * (including the terminating NULL). + * @stable ICU 2.0 + */ +#define ULOC_LANG_CAPACITY 12 + +/** + * Useful constant for the maximum size of the country part of a locale ID + * (including the terminating NULL). + * @stable ICU 2.0 + */ +#define ULOC_COUNTRY_CAPACITY 4 +/** + * Useful constant for the maximum size of the whole locale ID + * (including the terminating NULL and all keywords). + * @stable ICU 2.0 + */ +#define ULOC_FULLNAME_CAPACITY 157 + +/** + * Useful constant for the maximum size of the script part of a locale ID + * (including the terminating NULL). + * @stable ICU 2.8 + */ +#define ULOC_SCRIPT_CAPACITY 6 + +/** + * Useful constant for the maximum size of keywords in a locale + * @stable ICU 2.8 + */ +#define ULOC_KEYWORDS_CAPACITY 96 + +/** + * Useful constant for the maximum total size of keywords and their values in a locale + * @stable ICU 2.8 + */ +#define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 + +/** + * Invariant character separating keywords from the locale string + * @stable ICU 2.8 + */ +#define ULOC_KEYWORD_SEPARATOR '@' + +/** + * Unicode code point for '@' separating keywords from the locale string. + * @see ULOC_KEYWORD_SEPARATOR + * @stable ICU 4.6 + */ +#define ULOC_KEYWORD_SEPARATOR_UNICODE 0x40 + +/** + * Invariant character for assigning value to a keyword + * @stable ICU 2.8 + */ +#define ULOC_KEYWORD_ASSIGN '=' + +/** + * Unicode code point for '=' for assigning value to a keyword. + * @see ULOC_KEYWORD_ASSIGN + * @stable ICU 4.6 + */ +#define ULOC_KEYWORD_ASSIGN_UNICODE 0x3D + +/** + * Invariant character separating keywords + * @stable ICU 2.8 + */ +#define ULOC_KEYWORD_ITEM_SEPARATOR ';' + +/** + * Unicode code point for ';' separating keywords + * @see ULOC_KEYWORD_ITEM_SEPARATOR + * @stable ICU 4.6 + */ +#define ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE 0x3B + +/** + * Constants for *_getLocale() + * Allow user to select whether she wants information on + * requested, valid or actual locale. + * For example, a collator for "en_US_CALIFORNIA" was + * requested. In the current state of ICU (2.0), + * the requested locale is "en_US_CALIFORNIA", + * the valid locale is "en_US" (most specific locale supported by ICU) + * and the actual locale is "root" (the collation data comes unmodified + * from the UCA) + * The locale is considered supported by ICU if there is a core ICU bundle + * for that locale (although it may be empty). + * @stable ICU 2.1 + */ +typedef enum { + /** This is locale the data actually comes from + * @stable ICU 2.1 + */ + ULOC_ACTUAL_LOCALE = 0, + /** This is the most specific locale supported by ICU + * @stable ICU 2.1 + */ + ULOC_VALID_LOCALE = 1, + +#ifndef U_HIDE_DEPRECATED_API + /** This is the requested locale + * @deprecated ICU 2.8 + */ + ULOC_REQUESTED_LOCALE = 2, + + /** + * One more than the highest normal ULocDataLocaleType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + ULOC_DATA_LOCALE_TYPE_LIMIT = 3 +#endif // U_HIDE_DEPRECATED_API +} ULocDataLocaleType; + +#ifndef U_HIDE_SYSTEM_API +/** + * Gets ICU's default locale. + * The returned string is a snapshot in time, and will remain valid + * and unchanged even when uloc_setDefault() is called. + * The returned storage is owned by ICU, and must not be altered or deleted + * by the caller. + * + * @return the ICU default locale + * @system + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +uloc_getDefault(void); + +/** + * Sets ICU's default locale. + * By default (without calling this function), ICU's default locale will be based + * on information obtained from the underlying system environment. + *

+ * Changes to ICU's default locale do not propagate back to the + * system environment. + *

+ * Changes to ICU's default locale to not affect any ICU services that + * may already be open based on the previous default locale value. + * + * @param localeID the new ICU default locale. A value of NULL will try to get + * the system's default locale. + * @param status the error information if the setting of default locale fails + * @system + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +uloc_setDefault(const char* localeID, + UErrorCode* status); +#endif /* U_HIDE_SYSTEM_API */ + +/** + * Gets the language code for the specified locale. + * + * @param localeID the locale to get the ISO language code with + * @param language the language code for localeID + * @param languageCapacity the size of the language buffer to store the + * language code with + * @param err error information if retrieving the language code failed + * @return the actual buffer size needed for the language code. If it's greater + * than languageCapacity, the returned language code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getLanguage(const char* localeID, + char* language, + int32_t languageCapacity, + UErrorCode* err); + +/** + * Gets the script code for the specified locale. + * + * @param localeID the locale to get the ISO language code with + * @param script the language code for localeID + * @param scriptCapacity the size of the language buffer to store the + * language code with + * @param err error information if retrieving the language code failed + * @return the actual buffer size needed for the language code. If it's greater + * than scriptCapacity, the returned language code will be truncated. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getScript(const char* localeID, + char* script, + int32_t scriptCapacity, + UErrorCode* err); + +/** + * Gets the country code for the specified locale. + * + * @param localeID the locale to get the country code with + * @param country the country code for localeID + * @param countryCapacity the size of the country buffer to store the + * country code with + * @param err error information if retrieving the country code failed + * @return the actual buffer size needed for the country code. If it's greater + * than countryCapacity, the returned country code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getCountry(const char* localeID, + char* country, + int32_t countryCapacity, + UErrorCode* err); + +/** + * Gets the variant code for the specified locale. + * + * @param localeID the locale to get the variant code with + * @param variant the variant code for localeID + * @param variantCapacity the size of the variant buffer to store the + * variant code with + * @param err error information if retrieving the variant code failed + * @return the actual buffer size needed for the variant code. If it's greater + * than variantCapacity, the returned variant code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getVariant(const char* localeID, + char* variant, + int32_t variantCapacity, + UErrorCode* err); + + +/** + * Gets the full name for the specified locale. + * Note: This has the effect of 'canonicalizing' the ICU locale ID to + * a certain extent. Upper and lower case are set as needed. + * It does NOT map aliased names in any way. + * See the top of this header file. + * This API supports preflighting. + * + * @param localeID the locale to get the full name with + * @param name fill in buffer for the name without keywords. + * @param nameCapacity capacity of the fill in buffer. + * @param err error information if retrieving the full name failed + * @return the actual buffer size needed for the full name. If it's greater + * than nameCapacity, the returned full name will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getName(const char* localeID, + char* name, + int32_t nameCapacity, + UErrorCode* err); + +/** + * Gets the full name for the specified locale. + * Note: This has the effect of 'canonicalizing' the string to + * a certain extent. Upper and lower case are set as needed, + * and if the components were in 'POSIX' format they are changed to + * ICU format. It does NOT map aliased names in any way. + * See the top of this header file. + * + * @param localeID the locale to get the full name with + * @param name the full name for localeID + * @param nameCapacity the size of the name buffer to store the + * full name with + * @param err error information if retrieving the full name failed + * @return the actual buffer size needed for the full name. If it's greater + * than nameCapacity, the returned full name will be truncated. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_canonicalize(const char* localeID, + char* name, + int32_t nameCapacity, + UErrorCode* err); + +/** + * Gets the ISO language code for the specified locale. + * + * @param localeID the locale to get the ISO language code with + * @return language the ISO language code for localeID + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +uloc_getISO3Language(const char* localeID); + + +/** + * Gets the ISO country code for the specified locale. + * + * @param localeID the locale to get the ISO country code with + * @return country the ISO country code for localeID + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +uloc_getISO3Country(const char* localeID); + +/** + * Gets the Win32 LCID value for the specified locale. + * If the ICU locale is not recognized by Windows, 0 will be returned. + * + * LCIDs were deprecated with Windows Vista and Microsoft recommends + * that developers use BCP47 style tags instead (uloc_toLanguageTag). + * + * @param localeID the locale to get the Win32 LCID value with + * @return country the Win32 LCID for localeID + * @stable ICU 2.0 + */ +U_CAPI uint32_t U_EXPORT2 +uloc_getLCID(const char* localeID); + +/** + * Gets the language name suitable for display for the specified locale. + * + * @param locale the locale to get the ISO language code with + * @param displayLocale Specifies the locale to be used to display the name. In + * other words, if the locale's language code is "en", passing + * Locale::getFrench() for inLocale would result in "Anglais", + * while passing Locale::getGerman() for inLocale would result + * in "Englisch". + * @param language the displayable language code for localeID + * @param languageCapacity the size of the language buffer to store the + * displayable language code with. + * @param status error information if retrieving the displayable language code + * failed. U_USING_DEFAULT_WARNING indicates that no data was + * found from the locale resources and a case canonicalized + * language code is placed into language as fallback. + * @return the actual buffer size needed for the displayable language code. If + * it's greater than languageCapacity, the returned language + * code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayLanguage(const char* locale, + const char* displayLocale, + UChar* language, + int32_t languageCapacity, + UErrorCode* status); + +/** + * Gets the script name suitable for display for the specified locale. + * + * @param locale the locale to get the displayable script code with. NULL may be + * used to specify the default. + * @param displayLocale Specifies the locale to be used to display the name. In + * other words, if the locale's language code is "en", passing + * Locale::getFrench() for inLocale would result in "", while + * passing Locale::getGerman() for inLocale would result in "". + * NULL may be used to specify the default. + * @param script the displayable script for the localeID. + * @param scriptCapacity the size of the script buffer to store the displayable + * script code with. + * @param status error information if retrieving the displayable script code + * failed. U_USING_DEFAULT_WARNING indicates that no data was + * found from the locale resources and a case canonicalized + * script code is placed into script as fallback. + * @return the actual buffer size needed for the displayable script code. If + * it's greater than scriptCapacity, the returned displayable + * script code will be truncated. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayScript(const char* locale, + const char* displayLocale, + UChar* script, + int32_t scriptCapacity, + UErrorCode* status); + +/** + * Gets the country name suitable for display for the specified locale. + * Warning: this is for the region part of a valid locale ID; it cannot just be + * the region code (like "FR"). To get the display name for a region alone, or + * for other options, use ULocaleDisplayNames instead. + * + * @param locale the locale to get the displayable country code with. NULL may + * be used to specify the default. + * @param displayLocale Specifies the locale to be used to display the name. In + * other words, if the locale's language code is "en", passing + * Locale::getFrench() for inLocale would result in "Anglais", + * while passing Locale::getGerman() for inLocale would result + * in "Englisch". NULL may be used to specify the default. + * @param country the displayable country code for localeID. + * @param countryCapacity the size of the country buffer to store the + * displayable country code with. + * @param status error information if retrieving the displayable country code + * failed. U_USING_DEFAULT_WARNING indicates that no data was + * found from the locale resources and a case canonicalized + * country code is placed into country as fallback. + * @return the actual buffer size needed for the displayable country code. If + * it's greater than countryCapacity, the returned displayable + * country code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayCountry(const char* locale, + const char* displayLocale, + UChar* country, + int32_t countryCapacity, + UErrorCode* status); + + +/** + * Gets the variant name suitable for display for the specified locale. + * + * @param locale the locale to get the displayable variant code with. NULL may + * be used to specify the default. + * @param displayLocale Specifies the locale to be used to display the name. In + * other words, if the locale's language code is "en", passing + * Locale::getFrench() for inLocale would result in "Anglais", + * while passing Locale::getGerman() for inLocale would result + * in "Englisch". NULL may be used to specify the default. + * @param variant the displayable variant code for localeID. + * @param variantCapacity the size of the variant buffer to store the + * displayable variant code with. + * @param status error information if retrieving the displayable variant code + * failed. U_USING_DEFAULT_WARNING indicates that no data was + * found from the locale resources and a case canonicalized + * variant code is placed into variant as fallback. + * @return the actual buffer size needed for the displayable variant code. If + * it's greater than variantCapacity, the returned displayable + * variant code will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayVariant(const char* locale, + const char* displayLocale, + UChar* variant, + int32_t variantCapacity, + UErrorCode* status); + +/** + * Gets the keyword name suitable for display for the specified locale. E.g: + * for the locale string de_DE\@collation=PHONEBOOK, this API gets the display + * string for the keyword collation. + * Usage: + * + * UErrorCode status = U_ZERO_ERROR; + * const char* keyword =NULL; + * int32_t keywordLen = 0; + * int32_t keywordCount = 0; + * UChar displayKeyword[256]; + * int32_t displayKeywordLen = 0; + * UEnumeration* keywordEnum = uloc_openKeywords("de_DE@collation=PHONEBOOK;calendar=TRADITIONAL", &status); + * for(keywordCount = uenum_count(keywordEnum, &status); keywordCount > 0 ; keywordCount--){ + * if(U_FAILURE(status)){ + * ...something went wrong so handle the error... + * break; + * } + * // the uenum_next returns NUL terminated string + * keyword = uenum_next(keywordEnum, &keywordLen, &status); + * displayKeywordLen = uloc_getDisplayKeyword(keyword, "en_US", displayKeyword, 256); + * ... do something interesting ..... + * } + * uenum_close(keywordEnum); + * + * @param keyword The keyword whose display string needs to be returned. + * @param displayLocale Specifies the locale to be used to display the name. In other words, + * if the locale's language code is "en", passing Locale::getFrench() for + * inLocale would result in "Anglais", while passing Locale::getGerman() + * for inLocale would result in "Englisch". NULL may be used to specify the default. + * @param dest the buffer to which the displayable keyword should be written. + * @param destCapacity The size of the buffer (number of UChars). If it is 0, then + * dest may be NULL and the function will only return the length of the + * result without writing any of the result string (pre-flighting). + * @param status error information if retrieving the displayable string failed. + * Should not be NULL and should not indicate failure on entry. + * U_USING_DEFAULT_WARNING indicates that no data was found from the locale + * resources and the keyword is placed into dest as fallback. + * @return the actual buffer size needed for the displayable variant code. + * @see #uloc_openKeywords + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayKeyword(const char* keyword, + const char* displayLocale, + UChar* dest, + int32_t destCapacity, + UErrorCode* status); +/** + * Gets the value of the keyword suitable for display for the specified locale. + * E.g: for the locale string de_DE\@collation=PHONEBOOK, this API gets the display + * string for PHONEBOOK, in the display locale, when "collation" is specified as the keyword. + * + * @param locale The locale to get the displayable variant code with. NULL may be used to specify the default. + * @param keyword The keyword for whose value should be used. + * @param displayLocale Specifies the locale to be used to display the name. In other words, + * if the locale's language code is "en", passing Locale::getFrench() for + * inLocale would result in "Anglais", while passing Locale::getGerman() + * for inLocale would result in "Englisch". NULL may be used to specify the default. + * @param dest the buffer to which the displayable keyword should be written. + * @param destCapacity The size of the buffer (number of UChars). If it is 0, then + * dest may be NULL and the function will only return the length of the + * result without writing any of the result string (pre-flighting). + * @param status error information if retrieving the displayable string failed. + * Should not be NULL and must not indicate failure on entry. + * U_USING_DEFAULT_WARNING indicates that no data was found from the locale + * resources and the value of the keyword is placed into dest as fallback. + * @return the actual buffer size needed for the displayable variant code. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayKeywordValue( const char* locale, + const char* keyword, + const char* displayLocale, + UChar* dest, + int32_t destCapacity, + UErrorCode* status); +/** + * Gets the full name suitable for display for the specified locale. + * + * @param localeID the locale to get the displayable name with. NULL may be used to specify the default. + * @param inLocaleID Specifies the locale to be used to display the name. In other words, + * if the locale's language code is "en", passing Locale::getFrench() for + * inLocale would result in "Anglais", while passing Locale::getGerman() + * for inLocale would result in "Englisch". NULL may be used to specify the default. + * @param result the displayable name for localeID + * @param maxResultSize the size of the name buffer to store the + * displayable full name with + * @param err error information if retrieving the displayable name failed + * @return the actual buffer size needed for the displayable name. If it's greater + * than maxResultSize, the returned displayable name will be truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getDisplayName(const char* localeID, + const char* inLocaleID, + UChar* result, + int32_t maxResultSize, + UErrorCode* err); + + +/** + * Gets the specified locale from a list of available locales. + * + * This method corresponds to uloc_openAvailableByType called with the + * ULOC_AVAILABLE_DEFAULT type argument. + * + * The return value is a pointer to an item of a locale name array. Both this + * array and the pointers it contains are owned by ICU and should not be + * deleted or written through by the caller. The locale name is terminated by + * a null pointer. + * + * @param n the specific locale name index of the available locale list; + * should not exceed the number returned by uloc_countAvailable. + * @return a specified locale name of all available locales + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +uloc_getAvailable(int32_t n); + +/** + * Gets the size of the all available locale list. + * + * @return the size of the locale list + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 uloc_countAvailable(void); + +/** + * Types for uloc_getAvailableByType and uloc_countAvailableByType. + * + * @stable ICU 65 + */ +typedef enum ULocAvailableType { + /** + * Locales that return data when passed to ICU APIs, + * but not including legacy or alias locales. + * + * @stable ICU 65 + */ + ULOC_AVAILABLE_DEFAULT, + + /** + * Legacy or alias locales that return data when passed to ICU APIs. + * Examples of supported legacy or alias locales: + * + * - iw (alias to he) + * - mo (alias to ro) + * - zh_CN (alias to zh_Hans_CN) + * - sr_BA (alias to sr_Cyrl_BA) + * - ars (alias to ar_SA) + * + * The locales in this set are disjoint from the ones in + * ULOC_AVAILABLE_DEFAULT. To get both sets at the same time, use + * ULOC_AVAILABLE_WITH_LEGACY_ALIASES. + * + * @stable ICU 65 + */ + ULOC_AVAILABLE_ONLY_LEGACY_ALIASES, + + /** + * The union of the locales in ULOC_AVAILABLE_DEFAULT and + * ULOC_AVAILABLE_ONLY_LEGACY_ALIAS. + * + * @stable ICU 65 + */ + ULOC_AVAILABLE_WITH_LEGACY_ALIASES, + +#ifndef U_HIDE_INTERNAL_API + /** + * @internal + */ + ULOC_AVAILABLE_COUNT +#endif /* U_HIDE_INTERNAL_API */ +} ULocAvailableType; + +/** + * Gets a list of available locales according to the type argument, allowing + * the user to access different sets of supported locales in ICU. + * + * The returned UEnumeration must be closed by the caller. + * + * @param type Type choice from ULocAvailableType. + * @param status Set if an error occurred. + * @return a UEnumeration owned by the caller, or nullptr on failure. + * @stable ICU 65 + */ +U_CAPI UEnumeration* U_EXPORT2 +uloc_openAvailableByType(ULocAvailableType type, UErrorCode* status); + +/** + * + * Gets a list of all available 2-letter language codes defined in ISO 639, + * plus additional 3-letter codes determined to be useful for locale generation as + * defined by Unicode CLDR. This is a pointer + * to an array of pointers to arrays of char. All of these pointers are owned + * by ICU-- do not delete them, and do not write through them. The array is + * terminated with a null pointer. + * @return a list of all available language codes + * @stable ICU 2.0 + */ +U_CAPI const char* const* U_EXPORT2 +uloc_getISOLanguages(void); + +/** + * + * Gets a list of all available 2-letter country codes defined in ISO 639. This is a + * pointer to an array of pointers to arrays of char. All of these pointers are + * owned by ICU-- do not delete them, and do not write through them. The array is + * terminated with a null pointer. + * @return a list of all available country codes + * @stable ICU 2.0 + */ +U_CAPI const char* const* U_EXPORT2 +uloc_getISOCountries(void); + +/** + * Truncate the locale ID string to get the parent locale ID. + * Copies the part of the string before the last underscore. + * The parent locale ID will be an empty string if there is no + * underscore, or if there is only one underscore at localeID[0]. + * + * @param localeID Input locale ID string. + * @param parent Output string buffer for the parent locale ID. + * @param parentCapacity Size of the output buffer. + * @param err A UErrorCode value. + * @return The length of the parent locale ID. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getParent(const char* localeID, + char* parent, + int32_t parentCapacity, + UErrorCode* err); + + + + +/** + * Gets the full name for the specified locale, like uloc_getName(), + * but without keywords. + * + * Note: This has the effect of 'canonicalizing' the string to + * a certain extent. Upper and lower case are set as needed, + * and if the components were in 'POSIX' format they are changed to + * ICU format. It does NOT map aliased names in any way. + * See the top of this header file. + * + * This API strips off the keyword part, so "de_DE\@collation=phonebook" + * will become "de_DE". + * This API supports preflighting. + * + * @param localeID the locale to get the full name with + * @param name fill in buffer for the name without keywords. + * @param nameCapacity capacity of the fill in buffer. + * @param err error information if retrieving the full name failed + * @return the actual buffer size needed for the full name. If it's greater + * than nameCapacity, the returned full name will be truncated. + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getBaseName(const char* localeID, + char* name, + int32_t nameCapacity, + UErrorCode* err); + +/** + * Gets an enumeration of keywords for the specified locale. Enumeration + * must get disposed of by the client using uenum_close function. + * + * @param localeID the locale to get the variant code with + * @param status error information if retrieving the keywords failed + * @return enumeration of keywords or NULL if there are no keywords. + * @stable ICU 2.8 + */ +U_CAPI UEnumeration* U_EXPORT2 +uloc_openKeywords(const char* localeID, + UErrorCode* status); + +/** + * Get the value for a keyword. Locale name does not need to be normalized. + * + * @param localeID locale name containing the keyword ("de_DE@currency=EURO;collation=PHONEBOOK") + * @param keywordName name of the keyword for which we want the value; must not be + * NULL or empty, and must consist only of [A-Za-z0-9]. Case insensitive. + * @param buffer receiving buffer + * @param bufferCapacity capacity of receiving buffer + * @param status containing error code: e.g. buffer not big enough or ill-formed localeID + * or keywordName parameters. + * @return the length of keyword value + * @stable ICU 2.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getKeywordValue(const char* localeID, + const char* keywordName, + char* buffer, int32_t bufferCapacity, + UErrorCode* status); + + +/** + * Sets or removes the value of the specified keyword. + * + * For removing all keywords, use uloc_getBaseName(). + * + * NOTE: Unlike almost every other ICU function which takes a + * buffer, this function will NOT truncate the output text, and will + * not update the buffer with unterminated text setting a status of + * U_STRING_NOT_TERMINATED_WARNING. If a BUFFER_OVERFLOW_ERROR is received, + * it means a terminated version of the updated locale ID would not fit + * in the buffer, and the original buffer is untouched. This is done to + * prevent incorrect or possibly even malformed locales from being generated + * and used. + * + * @param keywordName name of the keyword to be set; must not be + * NULL or empty, and must consist only of [A-Za-z0-9]. Case insensitive. + * @param keywordValue value of the keyword to be set. If 0-length or + * NULL, will result in the keyword being removed; no error is given if + * that keyword does not exist. Otherwise, must consist only of + * [A-Za-z0-9] and [/_+-]. + * @param buffer input buffer containing well-formed locale ID to be + * modified. + * @param bufferCapacity capacity of receiving buffer + * @param status containing error code: e.g. buffer not big enough + * or ill-formed keywordName or keywordValue parameters, or ill-formed + * locale ID in buffer on input. + * @return the length needed for the buffer + * @see uloc_getKeywordValue + * @stable ICU 3.2 + */ +U_CAPI int32_t U_EXPORT2 +uloc_setKeywordValue(const char* keywordName, + const char* keywordValue, + char* buffer, int32_t bufferCapacity, + UErrorCode* status); + +/** + * Returns whether the locale's script is written right-to-left. + * If there is no script subtag, then the likely script is used, see uloc_addLikelySubtags(). + * If no likely script is known, then false is returned. + * + * A script is right-to-left according to the CLDR script metadata + * which corresponds to whether the script's letters have Bidi_Class=R or AL. + * + * Returns true for "ar" and "en-Hebr", false for "zh" and "fa-Cyrl". + * + * @param locale input locale ID + * @return true if the locale's script is written right-to-left + * @stable ICU 54 + */ +U_CAPI UBool U_EXPORT2 +uloc_isRightToLeft(const char *locale); + +/** + * enums for the return value for the character and line orientation + * functions. + * @stable ICU 4.0 + */ +typedef enum { + ULOC_LAYOUT_LTR = 0, /* left-to-right. */ + ULOC_LAYOUT_RTL = 1, /* right-to-left. */ + ULOC_LAYOUT_TTB = 2, /* top-to-bottom. */ + ULOC_LAYOUT_BTT = 3, /* bottom-to-top. */ + ULOC_LAYOUT_UNKNOWN +} ULayoutType; + +/** + * Get the layout character orientation for the specified locale. + * + * @param localeId locale name + * @param status Error status + * @return an enum indicating the layout orientation for characters. + * @stable ICU 4.0 + */ +U_CAPI ULayoutType U_EXPORT2 +uloc_getCharacterOrientation(const char* localeId, + UErrorCode *status); + +/** + * Get the layout line orientation for the specified locale. + * + * @param localeId locale name + * @param status Error status + * @return an enum indicating the layout orientation for lines. + * @stable ICU 4.0 + */ +U_CAPI ULayoutType U_EXPORT2 +uloc_getLineOrientation(const char* localeId, + UErrorCode *status); + +/** + * Output values which uloc_acceptLanguage() writes to the 'outResult' parameter. + * + * @see uloc_acceptLanguageFromHTTP + * @see uloc_acceptLanguage + * @stable ICU 3.2 + */ +typedef enum { + /** + * No exact match was found. + * @stable ICU 3.2 + */ + ULOC_ACCEPT_FAILED = 0, + /** + * An exact match was found. + * @stable ICU 3.2 + */ + ULOC_ACCEPT_VALID = 1, + /** + * A fallback was found. For example, the Accept-Language list includes 'ja_JP' + * and is matched with available locale 'ja'. + * @stable ICU 3.2 + */ + ULOC_ACCEPT_FALLBACK = 2 /* */ +} UAcceptResult; + +/** + * Based on a HTTP header from a web browser and a list of available locales, + * determine an acceptable locale for the user. + * + * This is a thin wrapper over C++ class LocaleMatcher. + * + * @param result - buffer to accept the result locale + * @param resultAvailable the size of the result buffer. + * @param outResult - An out parameter that contains the fallback status + * @param httpAcceptLanguage - "Accept-Language:" header as per HTTP. + * @param availableLocales - list of available locales to match + * @param status ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return length needed for the locale. + * @stable ICU 3.2 + */ +U_CAPI int32_t U_EXPORT2 +uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable, + UAcceptResult *outResult, + const char *httpAcceptLanguage, + UEnumeration* availableLocales, + UErrorCode *status); + +/** + * Based on a list of available locales, + * determine an acceptable locale for the user. + * + * This is a thin wrapper over C++ class LocaleMatcher. + * + * @param result - buffer to accept the result locale + * @param resultAvailable the size of the result buffer. + * @param outResult - An out parameter that contains the fallback status + * @param acceptList - list of acceptable languages + * @param acceptListCount - count of acceptList items + * @param availableLocales - list of available locales to match + * @param status ICU error code. Its input value must pass the U_SUCCESS() test, + * or else the function returns immediately. Check for U_FAILURE() + * on output or use with function chaining. (See User Guide for details.) + * @return length needed for the locale. + * @stable ICU 3.2 + */ +U_CAPI int32_t U_EXPORT2 +uloc_acceptLanguage(char *result, int32_t resultAvailable, + UAcceptResult *outResult, const char **acceptList, + int32_t acceptListCount, + UEnumeration* availableLocales, + UErrorCode *status); + + +/** + * Gets the ICU locale ID for the specified Win32 LCID value. + * + * @param hostID the Win32 LCID to translate + * @param locale the output buffer for the ICU locale ID, which will be NUL-terminated + * if there is room. + * @param localeCapacity the size of the output buffer + * @param status an error is returned if the LCID is unrecognized or the output buffer + * is too small + * @return actual the actual size of the locale ID, not including NUL-termination + * @stable ICU 3.8 + */ +U_CAPI int32_t U_EXPORT2 +uloc_getLocaleForLCID(uint32_t hostID, char *locale, int32_t localeCapacity, + UErrorCode *status); + + +/** + * Add the likely subtags for a provided locale ID, per the algorithm described + * in the following CLDR technical report: + * + * http://www.unicode.org/reports/tr35/#Likely_Subtags + * + * If localeID is already in the maximal form, or there is no data available + * for maximization, it will be copied to the output buffer. For example, + * "und-Zzzz" cannot be maximized, since there is no reasonable maximization. + * + * Examples: + * + * "en" maximizes to "en_Latn_US" + * + * "de" maximizes to "de_Latn_US" + * + * "sr" maximizes to "sr_Cyrl_RS" + * + * "sh" maximizes to "sr_Latn_RS" (Note this will not reverse.) + * + * "zh_Hani" maximizes to "zh_Hans_CN" (Note this will not reverse.) + * + * @param localeID The locale to maximize + * @param maximizedLocaleID The maximized locale + * @param maximizedLocaleIDCapacity The capacity of the maximizedLocaleID buffer + * @param err Error information if maximizing the locale failed. If the length + * of the localeID and the null-terminator is greater than the maximum allowed size, + * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR. + * @return The actual buffer size needed for the maximized locale. If it's + * greater than maximizedLocaleIDCapacity, the returned ID will be truncated. + * On error, the return value is -1. + * @stable ICU 4.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_addLikelySubtags(const char* localeID, + char* maximizedLocaleID, + int32_t maximizedLocaleIDCapacity, + UErrorCode* err); + + +/** + * Minimize the subtags for a provided locale ID, per the algorithm described + * in the following CLDR technical report: + * + * http://www.unicode.org/reports/tr35/#Likely_Subtags + * + * If localeID is already in the minimal form, or there is no data available + * for minimization, it will be copied to the output buffer. Since the + * minimization algorithm relies on proper maximization, see the comments + * for uloc_addLikelySubtags for reasons why there might not be any data. + * + * Examples: + * + * "en_Latn_US" minimizes to "en" + * + * "de_Latn_US" minimizes to "de" + * + * "sr_Cyrl_RS" minimizes to "sr" + * + * "zh_Hant_TW" minimizes to "zh_TW" (The region is preferred to the + * script, and minimizing to "zh" would imply "zh_Hans_CN".) + * + * @param localeID The locale to minimize + * @param minimizedLocaleID The minimized locale + * @param minimizedLocaleIDCapacity The capacity of the minimizedLocaleID buffer + * @param err Error information if minimizing the locale failed. If the length + * of the localeID and the null-terminator is greater than the maximum allowed size, + * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR. + * @return The actual buffer size needed for the minimized locale. If it's + * greater than minimizedLocaleIDCapacity, the returned ID will be truncated. + * On error, the return value is -1. + * @stable ICU 4.0 + */ +U_CAPI int32_t U_EXPORT2 +uloc_minimizeSubtags(const char* localeID, + char* minimizedLocaleID, + int32_t minimizedLocaleIDCapacity, + UErrorCode* err); + +/** + * Returns a locale ID for the specified BCP47 language tag string. + * If the specified language tag contains any ill-formed subtags, + * the first such subtag and all following subtags are ignored. + *

+ * This implements the 'Language-Tag' production of BCP 47, and so + * supports legacy language tags (marked as “Type: grandfathered” in BCP 47) + * (regular and irregular) as well as private use language tags. + * + * Private use tags are represented as 'x-whatever', + * and legacy tags are converted to their canonical replacements where they exist. + * + * Note that a few legacy tags have no modern replacement; + * these will be converted using the fallback described in + * the first paragraph, so some information might be lost. + * + * @param langtag the input BCP47 language tag. + * @param localeID the output buffer receiving a locale ID for the + * specified BCP47 language tag. + * @param localeIDCapacity the size of the locale ID output buffer. + * @param parsedLength if not NULL, successfully parsed length + * for the input language tag is set. + * @param err error information if receiving the locald ID + * failed. + * @return the length of the locale ID. + * @stable ICU 4.2 + */ +U_CAPI int32_t U_EXPORT2 +uloc_forLanguageTag(const char* langtag, + char* localeID, + int32_t localeIDCapacity, + int32_t* parsedLength, + UErrorCode* err); + +/** + * Returns a well-formed language tag for this locale ID. + *

+ * Note: When strict is false, any locale + * fields which do not satisfy the BCP47 syntax requirement will + * be omitted from the result. When strict is + * true, this function sets U_ILLEGAL_ARGUMENT_ERROR to the + * err if any locale fields do not satisfy the + * BCP47 syntax requirement. + * @param localeID the input locale ID + * @param langtag the output buffer receiving BCP47 language + * tag for the locale ID. + * @param langtagCapacity the size of the BCP47 language tag + * output buffer. + * @param strict boolean value indicating if the function returns + * an error for an ill-formed input locale ID. + * @param err error information if receiving the language + * tag failed. + * @return The length of the BCP47 language tag. + * @stable ICU 4.2 + */ +U_CAPI int32_t U_EXPORT2 +uloc_toLanguageTag(const char* localeID, + char* langtag, + int32_t langtagCapacity, + UBool strict, + UErrorCode* err); + +/** + * Converts the specified keyword (legacy key, or BCP 47 Unicode locale + * extension key) to the equivalent BCP 47 Unicode locale extension key. + * For example, BCP 47 Unicode locale extension key "co" is returned for + * the input keyword "collation". + *

+ * When the specified keyword is unknown, but satisfies the BCP syntax, + * then the pointer to the input keyword itself will be returned. + * For example, + * uloc_toUnicodeLocaleKey("ZZ") returns "ZZ". + * + * @param keyword the input locale keyword (either legacy key + * such as "collation" or BCP 47 Unicode locale extension + * key such as "co"). + * @return the well-formed BCP 47 Unicode locale extension key, + * or NULL if the specified locale keyword cannot be + * mapped to a well-formed BCP 47 Unicode locale extension + * key. + * @see uloc_toLegacyKey + * @stable ICU 54 + */ +U_CAPI const char* U_EXPORT2 +uloc_toUnicodeLocaleKey(const char* keyword); + +/** + * Converts the specified keyword value (legacy type, or BCP 47 + * Unicode locale extension type) to the well-formed BCP 47 Unicode locale + * extension type for the specified keyword (category). For example, BCP 47 + * Unicode locale extension type "phonebk" is returned for the input + * keyword value "phonebook", with the keyword "collation" (or "co"). + *

+ * When the specified keyword is not recognized, but the specified value + * satisfies the syntax of the BCP 47 Unicode locale extension type, + * or when the specified keyword allows 'variable' type and the specified + * value satisfies the syntax, then the pointer to the input type value itself + * will be returned. + * For example, + * uloc_toUnicodeLocaleType("Foo", "Bar") returns "Bar", + * uloc_toUnicodeLocaleType("variableTop", "00A4") returns "00A4". + * + * @param keyword the locale keyword (either legacy key such as + * "collation" or BCP 47 Unicode locale extension + * key such as "co"). + * @param value the locale keyword value (either legacy type + * such as "phonebook" or BCP 47 Unicode locale extension + * type such as "phonebk"). + * @return the well-formed BCP47 Unicode locale extension type, + * or NULL if the locale keyword value cannot be mapped to + * a well-formed BCP 47 Unicode locale extension type. + * @see uloc_toLegacyType + * @stable ICU 54 + */ +U_CAPI const char* U_EXPORT2 +uloc_toUnicodeLocaleType(const char* keyword, const char* value); + +/** + * Converts the specified keyword (BCP 47 Unicode locale extension key, or + * legacy key) to the legacy key. For example, legacy key "collation" is + * returned for the input BCP 47 Unicode locale extension key "co". + * + * @param keyword the input locale keyword (either BCP 47 Unicode locale + * extension key or legacy key). + * @return the well-formed legacy key, or NULL if the specified + * keyword cannot be mapped to a well-formed legacy key. + * @see toUnicodeLocaleKey + * @stable ICU 54 + */ +U_CAPI const char* U_EXPORT2 +uloc_toLegacyKey(const char* keyword); + +/** + * Converts the specified keyword value (BCP 47 Unicode locale extension type, + * or legacy type or type alias) to the canonical legacy type. For example, + * the legacy type "phonebook" is returned for the input BCP 47 Unicode + * locale extension type "phonebk" with the keyword "collation" (or "co"). + *

+ * When the specified keyword is not recognized, but the specified value + * satisfies the syntax of legacy key, or when the specified keyword + * allows 'variable' type and the specified value satisfies the syntax, + * then the pointer to the input type value itself will be returned. + * For example, + * uloc_toLegacyType("Foo", "Bar") returns "Bar", + * uloc_toLegacyType("vt", "00A4") returns "00A4". + * + * @param keyword the locale keyword (either legacy keyword such as + * "collation" or BCP 47 Unicode locale extension + * key such as "co"). + * @param value the locale keyword value (either BCP 47 Unicode locale + * extension type such as "phonebk" or legacy keyword value + * such as "phonebook"). + * @return the well-formed legacy type, or NULL if the specified + * keyword value cannot be mapped to a well-formed legacy + * type. + * @see toUnicodeLocaleType + * @stable ICU 54 + */ +U_CAPI const char* U_EXPORT2 +uloc_toLegacyType(const char* keyword, const char* value); + +#endif /*_ULOC*/ diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulocdata.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulocdata.h new file mode 100644 index 0000000000000000000000000000000000000000..3647df9596ae63be9d8120dbdbca4a7ab91c4179 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/ulocdata.h @@ -0,0 +1,299 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* * +* Copyright (C) 2003-2015, International Business Machines * +* Corporation and others. All Rights Reserved. * +* * +****************************************************************************** +* file name: ulocdata.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 2003Oct21 +* created by: Ram Viswanadha +*/ + +#ifndef __ULOCDATA_H__ +#define __ULOCDATA_H__ + +#include "unicode/ures.h" +#include "unicode/uloc.h" +#include "unicode/uset.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: Provides access to locale data. + */ + +/** Forward declaration of the ULocaleData structure. @stable ICU 3.6 */ +struct ULocaleData; + +/** A locale data object. @stable ICU 3.6 */ +typedef struct ULocaleData ULocaleData; + + + +/** The possible types of exemplar character sets. + * @stable ICU 3.4 + */ +typedef enum ULocaleDataExemplarSetType { + /** Basic set @stable ICU 3.4 */ + ULOCDATA_ES_STANDARD=0, + /** Auxiliary set @stable ICU 3.4 */ + ULOCDATA_ES_AUXILIARY=1, + /** Index Character set @stable ICU 4.8 */ + ULOCDATA_ES_INDEX=2, + /** Punctuation set @stable ICU 51 */ + ULOCDATA_ES_PUNCTUATION=3, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal ULocaleDataExemplarSetType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + ULOCDATA_ES_COUNT=4 +#endif /* U_HIDE_DEPRECATED_API */ +} ULocaleDataExemplarSetType; + +/** The possible types of delimiters. + * @stable ICU 3.4 + */ +typedef enum ULocaleDataDelimiterType { + /** Quotation start @stable ICU 3.4 */ + ULOCDATA_QUOTATION_START = 0, + /** Quotation end @stable ICU 3.4 */ + ULOCDATA_QUOTATION_END = 1, + /** Alternate quotation start @stable ICU 3.4 */ + ULOCDATA_ALT_QUOTATION_START = 2, + /** Alternate quotation end @stable ICU 3.4 */ + ULOCDATA_ALT_QUOTATION_END = 3, +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal ULocaleDataDelimiterType value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + ULOCDATA_DELIMITER_COUNT = 4 +#endif /* U_HIDE_DEPRECATED_API */ +} ULocaleDataDelimiterType; + +/** + * Opens a locale data object for the given locale + * + * @param localeID Specifies the locale associated with this locale + * data object. + * @param status Pointer to error status code. + * @stable ICU 3.4 + */ +U_CAPI ULocaleData* U_EXPORT2 +ulocdata_open(const char *localeID, UErrorCode *status); + +/** + * Closes a locale data object. + * + * @param uld The locale data object to close + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ulocdata_close(ULocaleData *uld); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalULocaleDataPointer + * "Smart pointer" class, closes a ULocaleData via ulocdata_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalULocaleDataPointer, ULocaleData, ulocdata_close); + +U_NAMESPACE_END + +#endif + +/** + * Sets the "no Substitute" attribute of the locale data + * object. If true, then any methods associated with the + * locale data object will return null when there is no + * data available for that method, given the locale ID + * supplied to ulocdata_open(). + * + * @param uld The locale data object to set. + * @param setting Value of the "no substitute" attribute. + * @stable ICU 3.4 + */ +U_CAPI void U_EXPORT2 +ulocdata_setNoSubstitute(ULocaleData *uld, UBool setting); + +/** + * Retrieves the current "no Substitute" value of the locale data + * object. If true, then any methods associated with the + * locale data object will return null when there is no + * data available for that method, given the locale ID + * supplied to ulocdata_open(). + * + * @param uld Pointer to the The locale data object to set. + * @return UBool Value of the "no substitute" attribute. + * @stable ICU 3.4 + */ +U_CAPI UBool U_EXPORT2 +ulocdata_getNoSubstitute(ULocaleData *uld); + +/** + * Returns the set of exemplar characters for a locale. + * + * @param uld Pointer to the locale data object from which the + * exemplar character set is to be retrieved. + * @param fillIn Pointer to a USet object to receive the + * exemplar character set for the given locale. Previous + * contents of fillIn are lost. If fillIn is NULL, + * then a new USet is created and returned. The caller + * owns the result and must dispose of it by calling + * uset_close. + * @param options Bitmask for options to apply to the exemplar pattern. + * Specify zero to retrieve the exemplar set as it is + * defined in the locale data. Specify + * USET_CASE_INSENSITIVE to retrieve a case-folded + * exemplar set. See uset_applyPattern for a complete + * list of valid options. The USET_IGNORE_SPACE bit is + * always set, regardless of the value of 'options'. + * @param extype Specifies the type of exemplar set to be retrieved. + * @param status Pointer to an input-output error code value; + * must not be NULL. Will be set to U_MISSING_RESOURCE_ERROR + * if the requested data is not available. + * @return USet* Either fillIn, or if fillIn is NULL, a pointer to + * a newly-allocated USet that the user must close. + * In case of error, NULL is returned. + * @stable ICU 3.4 + */ +U_CAPI USet* U_EXPORT2 +ulocdata_getExemplarSet(ULocaleData *uld, USet *fillIn, + uint32_t options, ULocaleDataExemplarSetType extype, UErrorCode *status); + +/** + * Returns one of the delimiter strings associated with a locale. + * + * @param uld Pointer to the locale data object from which the + * delimiter string is to be retrieved. + * @param type the type of delimiter to be retrieved. + * @param result A pointer to a buffer to receive the result. + * @param resultLength The maximum size of result. + * @param status Pointer to an error code value + * @return int32_t The total buffer size needed; if greater than resultLength, + * the output was truncated. + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +ulocdata_getDelimiter(ULocaleData *uld, ULocaleDataDelimiterType type, UChar *result, int32_t resultLength, UErrorCode *status); + +/** + * Enumeration for representing the measurement systems. + * @stable ICU 2.8 + */ +typedef enum UMeasurementSystem { + UMS_SI, /**< Measurement system specified by SI otherwise known as Metric system. @stable ICU 2.8 */ + UMS_US, /**< Measurement system followed in the United States of America. @stable ICU 2.8 */ + UMS_UK, /**< Mix of metric and imperial units used in Great Britain. @stable ICU 55 */ +#ifndef U_HIDE_DEPRECATED_API + /** + * One more than the highest normal UMeasurementSystem value. + * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. + */ + UMS_LIMIT +#endif /* U_HIDE_DEPRECATED_API */ +} UMeasurementSystem; + +/** + * Returns the measurement system used in the locale specified by the localeID. + * Please note that this API will change in ICU 3.6 and will use an ulocdata object. + * + * @param localeID The id of the locale for which the measurement system to be retrieved. + * @param status Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return UMeasurementSystem the measurement system used in the locale. + * @stable ICU 2.8 + */ +U_CAPI UMeasurementSystem U_EXPORT2 +ulocdata_getMeasurementSystem(const char *localeID, UErrorCode *status); + +/** + * Returns the element gives the normal business letter size, and customary units. + * The units for the numbers are always in milli-meters. + * For US since 8.5 and 11 do not yield an integral value when converted to milli-meters, + * the values are rounded off. + * So for A4 size paper the height and width are 297 mm and 210 mm respectively, + * and for US letter size the height and width are 279 mm and 216 mm respectively. + * Please note that this API will change in ICU 3.6 and will use an ulocdata object. + * + * @param localeID The id of the locale for which the paper size information to be retrieved. + * @param height A pointer to int to receive the height information. + * @param width A pointer to int to receive the width information. + * @param status Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @stable ICU 2.8 + */ +U_CAPI void U_EXPORT2 +ulocdata_getPaperSize(const char *localeID, int32_t *height, int32_t *width, UErrorCode *status); + +/** + * Return the current CLDR version used by the library. + * @param versionArray fill-in that will receive the version number + * @param status error code - could be U_MISSING_RESOURCE_ERROR if the version was not found. + * @stable ICU 4.2 + */ +U_CAPI void U_EXPORT2 +ulocdata_getCLDRVersion(UVersionInfo versionArray, UErrorCode *status); + +/** + * Returns locale display pattern associated with a locale. + * + * @param uld Pointer to the locale data object from which the + * exemplar character set is to be retrieved. + * @param pattern locale display pattern for locale. + * @param patternCapacity the size of the buffer to store the locale display + * pattern with. + * @param status Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return the actual buffer size needed for localeDisplayPattern. If it's greater + * than patternCapacity, the returned pattern will be truncated. + * + * @stable ICU 4.2 + */ +U_CAPI int32_t U_EXPORT2 +ulocdata_getLocaleDisplayPattern(ULocaleData *uld, + UChar *pattern, + int32_t patternCapacity, + UErrorCode *status); + + +/** + * Returns locale separator associated with a locale. + * + * @param uld Pointer to the locale data object from which the + * exemplar character set is to be retrieved. + * @param separator locale separator for locale. + * @param separatorCapacity the size of the buffer to store the locale + * separator with. + * @param status Must be a valid pointer to an error code value, + * which must not indicate a failure before the function call. + * @return the actual buffer size needed for localeSeparator. If it's greater + * than separatorCapacity, the returned separator will be truncated. + * + * @stable ICU 4.2 + */ +U_CAPI int32_t U_EXPORT2 +ulocdata_getLocaleSeparator(ULocaleData *uld, + UChar *separator, + int32_t separatorCapacity, + UErrorCode *status); +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umachine.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umachine.h new file mode 100644 index 0000000000000000000000000000000000000000..545abef59569646ca557416a47b03ea416b71dd1 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umachine.h @@ -0,0 +1,459 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +****************************************************************************** +* +* Copyright (C) 1999-2015, International Business Machines +* Corporation and others. All Rights Reserved. +* +****************************************************************************** +* file name: umachine.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 1999sep13 +* created by: Markus W. Scherer +* +* This file defines basic types and constants for ICU to be +* platform-independent. umachine.h and utf.h are included into +* utypes.h to provide all the general definitions for ICU. +* All of these definitions used to be in utypes.h before +* the UTF-handling macros made this unmaintainable. +*/ + +#ifndef __UMACHINE_H__ +#define __UMACHINE_H__ + + +/** + * \file + * \brief Basic types and constants for UTF + * + *

Basic types and constants for UTF

+ * This file defines basic types and constants for utf.h to be + * platform-independent. umachine.h and utf.h are included into + * utypes.h to provide all the general definitions for ICU. + * All of these definitions used to be in utypes.h before + * the UTF-handling macros made this unmaintainable. + * + */ +/*==========================================================================*/ +/* Include platform-dependent definitions */ +/* which are contained in the platform-specific file platform.h */ +/*==========================================================================*/ + +#include "unicode/ptypes.h" /* platform.h is included in ptypes.h */ + +/* + * ANSI C headers: + * stddef.h defines wchar_t + */ +#include +#include + +/*==========================================================================*/ +/* For C wrappers, we use the symbol U_CAPI. */ +/* This works properly if the includer is C or C++. */ +/* Functions are declared U_CAPI return-type U_EXPORT2 function-name()... */ +/*==========================================================================*/ + +/** + * \def U_CFUNC + * This is used in a declaration of a library private ICU C function. + * @stable ICU 2.4 + */ + +/** + * \def U_CDECL_BEGIN + * This is used to begin a declaration of a library private ICU C API. + * @stable ICU 2.4 + */ + +/** + * \def U_CDECL_END + * This is used to end a declaration of a library private ICU C API + * @stable ICU 2.4 + */ + +#ifdef __cplusplus +# define U_CFUNC extern "C" +# define U_CDECL_BEGIN extern "C" { +# define U_CDECL_END } +#else +# define U_CFUNC extern +# define U_CDECL_BEGIN +# define U_CDECL_END +#endif + +#ifndef U_ATTRIBUTE_DEPRECATED +/** + * \def U_ATTRIBUTE_DEPRECATED + * This is used for GCC specific attributes + * @internal + */ +#if U_GCC_MAJOR_MINOR >= 302 +# define U_ATTRIBUTE_DEPRECATED __attribute__ ((deprecated)) +/** + * \def U_ATTRIBUTE_DEPRECATED + * This is used for Visual C++ specific attributes + * @internal + */ +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) +# define U_ATTRIBUTE_DEPRECATED __declspec(deprecated) +#else +# define U_ATTRIBUTE_DEPRECATED +#endif +#endif + +/** This is used to declare a function as a public ICU C API @stable ICU 2.0*/ +#define U_CAPI U_CFUNC U_EXPORT +/** Obsolete/same as U_CAPI; was used to declare a function as a stable public ICU C API*/ +#define U_STABLE U_CAPI +/** Obsolete/same as U_CAPI; was used to declare a function as a draft public ICU C API */ +#define U_DRAFT U_CAPI +/** This is used to declare a function as a deprecated public ICU C API */ +#define U_DEPRECATED U_CAPI U_ATTRIBUTE_DEPRECATED +/** Obsolete/same as U_CAPI; was used to declare a function as an obsolete public ICU C API */ +#define U_OBSOLETE U_CAPI +/** Obsolete/same as U_CAPI; was used to declare a function as an internal ICU C API */ +#define U_INTERNAL U_CAPI + +// Before ICU 65, function-like, multi-statement ICU macros were just defined as +// series of statements wrapped in { } blocks and the caller could choose to +// either treat them as if they were actual functions and end the invocation +// with a trailing ; creating an empty statement after the block or else omit +// this trailing ; using the knowledge that the macro would expand to { }. +// +// But doing so doesn't work well with macros that look like functions and +// compiler warnings about empty statements (ICU-20601) and ICU 65 therefore +// switches to the standard solution of wrapping such macros in do { } while. +// +// This will however break existing code that depends on being able to invoke +// these macros without a trailing ; so to be able to remain compatible with +// such code the wrapper is itself defined as macros so that it's possible to +// build ICU 65 and later with the old macro behaviour, like this: +// +// export CPPFLAGS='-DUPRV_BLOCK_MACRO_BEGIN="" -DUPRV_BLOCK_MACRO_END=""' +// runConfigureICU ... +// + +/** + * \def UPRV_BLOCK_MACRO_BEGIN + * Defined as the "do" keyword by default. + * @internal + */ +#ifndef UPRV_BLOCK_MACRO_BEGIN +#define UPRV_BLOCK_MACRO_BEGIN do +#endif + +/** + * \def UPRV_BLOCK_MACRO_END + * Defined as "while (false)" by default. + * @internal + */ +#ifndef UPRV_BLOCK_MACRO_END +#define UPRV_BLOCK_MACRO_END while (false) +#endif + +/*==========================================================================*/ +/* limits for int32_t etc., like in POSIX inttypes.h */ +/*==========================================================================*/ + +#ifndef INT8_MIN +/** The smallest value an 8 bit signed integer can hold @stable ICU 2.0 */ +# define INT8_MIN ((int8_t)(-128)) +#endif +#ifndef INT16_MIN +/** The smallest value a 16 bit signed integer can hold @stable ICU 2.0 */ +# define INT16_MIN ((int16_t)(-32767-1)) +#endif +#ifndef INT32_MIN +/** The smallest value a 32 bit signed integer can hold @stable ICU 2.0 */ +# define INT32_MIN ((int32_t)(-2147483647-1)) +#endif + +#ifndef INT8_MAX +/** The largest value an 8 bit signed integer can hold @stable ICU 2.0 */ +# define INT8_MAX ((int8_t)(127)) +#endif +#ifndef INT16_MAX +/** The largest value a 16 bit signed integer can hold @stable ICU 2.0 */ +# define INT16_MAX ((int16_t)(32767)) +#endif +#ifndef INT32_MAX +/** The largest value a 32 bit signed integer can hold @stable ICU 2.0 */ +# define INT32_MAX ((int32_t)(2147483647)) +#endif + +#ifndef UINT8_MAX +/** The largest value an 8 bit unsigned integer can hold @stable ICU 2.0 */ +# define UINT8_MAX ((uint8_t)(255U)) +#endif +#ifndef UINT16_MAX +/** The largest value a 16 bit unsigned integer can hold @stable ICU 2.0 */ +# define UINT16_MAX ((uint16_t)(65535U)) +#endif +#ifndef UINT32_MAX +/** The largest value a 32 bit unsigned integer can hold @stable ICU 2.0 */ +# define UINT32_MAX ((uint32_t)(4294967295U)) +#endif + +#if defined(U_INT64_T_UNAVAILABLE) +# error int64_t is required for decimal format and rule-based number format. +#else +# ifndef INT64_C +/** + * Provides a platform independent way to specify a signed 64-bit integer constant. + * note: may be wrong for some 64 bit platforms - ensure your compiler provides INT64_C + * @stable ICU 2.8 + */ +# define INT64_C(c) c ## LL +# endif +# ifndef UINT64_C +/** + * Provides a platform independent way to specify an unsigned 64-bit integer constant. + * note: may be wrong for some 64 bit platforms - ensure your compiler provides UINT64_C + * @stable ICU 2.8 + */ +# define UINT64_C(c) c ## ULL +# endif +# ifndef U_INT64_MIN +/** The smallest value a 64 bit signed integer can hold @stable ICU 2.8 */ +# define U_INT64_MIN ((int64_t)(INT64_C(-9223372036854775807)-1)) +# endif +# ifndef U_INT64_MAX +/** The largest value a 64 bit signed integer can hold @stable ICU 2.8 */ +# define U_INT64_MAX ((int64_t)(INT64_C(9223372036854775807))) +# endif +# ifndef U_UINT64_MAX +/** The largest value a 64 bit unsigned integer can hold @stable ICU 2.8 */ +# define U_UINT64_MAX ((uint64_t)(UINT64_C(18446744073709551615))) +# endif +#endif + +/*==========================================================================*/ +/* Boolean data type */ +/*==========================================================================*/ + +/** + * The ICU boolean type, a signed-byte integer. + * ICU-specific for historical reasons: The C and C++ standards used to not define type bool. + * Also provides a fixed type definition, as opposed to + * type bool whose details (e.g., sizeof) may vary by compiler and between C and C++. + * + * @stable ICU 2.0 + */ +typedef int8_t UBool; + +/** + * \def U_DEFINE_FALSE_AND_TRUE + * Normally turns off defining macros FALSE=0 & TRUE=1 in public ICU headers. + * These obsolete macros sometimes break compilation of other code that + * defines enum constants or similar with these names. + * C++ has long defined bool/false/true. + * C99 also added definitions for these, although as macros; see stdbool.h. + * + * You may transitionally define U_DEFINE_FALSE_AND_TRUE=1 if you need time to migrate code. + * + * @internal ICU 68 + */ +#ifdef U_DEFINE_FALSE_AND_TRUE + // Use the predefined value. +#else + // Default to avoiding collision with non-macro definitions of FALSE & TRUE. +# define U_DEFINE_FALSE_AND_TRUE 0 +#endif + +#if U_DEFINE_FALSE_AND_TRUE || defined(U_IN_DOXYGEN) +#ifndef TRUE +/** + * The TRUE value of a UBool. + * + * @deprecated ICU 68 Use standard "true" instead. + */ +# define TRUE 1 +#endif +#ifndef FALSE +/** + * The FALSE value of a UBool. + * + * @deprecated ICU 68 Use standard "false" instead. + */ +# define FALSE 0 +#endif +#endif // U_DEFINE_FALSE_AND_TRUE + +/*==========================================================================*/ +/* Unicode data types */ +/*==========================================================================*/ + +/* wchar_t-related definitions -------------------------------------------- */ + +/* + * \def U_WCHAR_IS_UTF16 + * Defined if wchar_t uses UTF-16. + * + * @stable ICU 2.0 + */ +/* + * \def U_WCHAR_IS_UTF32 + * Defined if wchar_t uses UTF-32. + * + * @stable ICU 2.0 + */ +#if !defined(U_WCHAR_IS_UTF16) && !defined(U_WCHAR_IS_UTF32) +# ifdef __STDC_ISO_10646__ +# if (U_SIZEOF_WCHAR_T==2) +# define U_WCHAR_IS_UTF16 +# elif (U_SIZEOF_WCHAR_T==4) +# define U_WCHAR_IS_UTF32 +# endif +# elif defined __UCS2__ +# if (U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400) && (U_SIZEOF_WCHAR_T==2) +# define U_WCHAR_IS_UTF16 +# endif +# elif defined(__UCS4__) || (U_PLATFORM == U_PF_OS400 && defined(__UTF32__)) +# if (U_SIZEOF_WCHAR_T==4) +# define U_WCHAR_IS_UTF32 +# endif +# elif U_PLATFORM_IS_DARWIN_BASED || (U_SIZEOF_WCHAR_T==4 && U_PLATFORM_IS_LINUX_BASED) +# define U_WCHAR_IS_UTF32 +# elif U_PLATFORM_HAS_WIN32_API +# define U_WCHAR_IS_UTF16 +# endif +#endif + +/* UChar and UChar32 definitions -------------------------------------------- */ + +/** Number of bytes in a UChar (always 2). @stable ICU 2.0 */ +#define U_SIZEOF_UCHAR 2 + +/** + * \def U_CHAR16_IS_TYPEDEF + * If 1, then char16_t is a typedef and not a real type (yet) + * @internal + */ +#if defined(_MSC_VER) && (_MSC_VER < 1900) +// Versions of Visual Studio/MSVC below 2015 do not support char16_t as a real type, +// and instead use a typedef. https://msdn.microsoft.com/library/bb531344.aspx +# define U_CHAR16_IS_TYPEDEF 1 +#else +# define U_CHAR16_IS_TYPEDEF 0 +#endif + + +/** + * \var UChar + * + * The base type for UTF-16 code units and pointers. + * Unsigned 16-bit integer. + * Starting with ICU 59, C++ API uses char16_t directly, while C API continues to use UChar. + * + * UChar is configurable by defining the macro UCHAR_TYPE + * on the preprocessor or compiler command line: + * -DUCHAR_TYPE=uint16_t or -DUCHAR_TYPE=wchar_t (if U_SIZEOF_WCHAR_T==2) etc. + * (The UCHAR_TYPE can also be \#defined earlier in this file, for outside the ICU library code.) + * This is for transitional use from application code that uses uint16_t or wchar_t for UTF-16. + * + * The default is UChar=char16_t. + * + * C++11 defines char16_t as bit-compatible with uint16_t, but as a distinct type. + * + * In C, char16_t is a simple typedef of uint_least16_t. + * ICU requires uint_least16_t=uint16_t for data memory mapping. + * On macOS, char16_t is not available because the uchar.h standard header is missing. + * + * @stable ICU 4.4 + */ + +#if 1 + // #if 1 is normal. UChar defaults to char16_t in C++. + // For configuration testing of UChar=uint16_t temporarily change this to #if 0. + // The intltest Makefile #defines UCHAR_TYPE=char16_t, + // so we only #define it to uint16_t if it is undefined so far. +#elif !defined(UCHAR_TYPE) +# define UCHAR_TYPE uint16_t +#endif + +#if defined(U_COMBINED_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION) || \ + defined(U_I18N_IMPLEMENTATION) || defined(U_IO_IMPLEMENTATION) + // Inside the ICU library code, never configurable. + typedef char16_t UChar; +#elif defined(UCHAR_TYPE) + typedef UCHAR_TYPE UChar; +#elif U_CPLUSPLUS_VERSION != 0 + typedef char16_t UChar; // C++ +#else + typedef uint16_t UChar; // C +#endif + +/** + * \var OldUChar + * Default ICU 58 definition of UChar. + * A base type for UTF-16 code units and pointers. + * Unsigned 16-bit integer. + * + * Define OldUChar to be wchar_t if that is 16 bits wide. + * If wchar_t is not 16 bits wide, then define UChar to be uint16_t. + * + * This makes the definition of OldUChar platform-dependent + * but allows direct string type compatibility with platforms with + * 16-bit wchar_t types. + * + * This is how UChar was defined in ICU 58, for transition convenience. + * Exception: ICU 58 UChar was defined to UCHAR_TYPE if that macro was defined. + * The current UChar responds to UCHAR_TYPE but OldUChar does not. + * + * @stable ICU 59 + */ +#if U_SIZEOF_WCHAR_T==2 + typedef wchar_t OldUChar; +#elif defined(__CHAR16_TYPE__) + typedef __CHAR16_TYPE__ OldUChar; +#else + typedef uint16_t OldUChar; +#endif + +/** + * Define UChar32 as a type for single Unicode code points. + * UChar32 is a signed 32-bit integer (same as int32_t). + * + * The Unicode code point range is 0..0x10ffff. + * All other values (negative or >=0x110000) are illegal as Unicode code points. + * They may be used as sentinel values to indicate "done", "error" + * or similar non-code point conditions. + * + * Before ICU 2.4 (Jitterbug 2146), UChar32 was defined + * to be wchar_t if that is 32 bits wide (wchar_t may be signed or unsigned) + * or else to be uint32_t. + * That is, the definition of UChar32 was platform-dependent. + * + * @see U_SENTINEL + * @stable ICU 2.4 + */ +typedef int32_t UChar32; + +/** + * This value is intended for sentinel values for APIs that + * (take or) return single code points (UChar32). + * It is outside of the Unicode code point range 0..0x10ffff. + * + * For example, a "done" or "error" value in a new API + * could be indicated with U_SENTINEL. + * + * ICU APIs designed before ICU 2.4 usually define service-specific "done" + * values, mostly 0xffff. + * Those may need to be distinguished from + * actual U+ffff text contents by calling functions like + * CharacterIterator::hasNext() or UnicodeString::length(). + * + * @return -1 + * @see UChar32 + * @stable ICU 2.4 + */ +#define U_SENTINEL (-1) + +#include "unicode/urename.h" + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umisc.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umisc.h new file mode 100644 index 0000000000000000000000000000000000000000..4e9dda7450bdc48981ee3f78017e16b2c9a95f47 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umisc.h @@ -0,0 +1,62 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2006, International Business Machines +* Corporation and others. All Rights Reserved. +********************************************************************** +* file name: umisc.h +* encoding: UTF-8 +* tab size: 8 (not used) +* indentation:4 +* +* created on: 1999oct15 +* created by: Markus W. Scherer +*/ + +#ifndef UMISC_H +#define UMISC_H + +#include "unicode/utypes.h" + +/** + * \file + * \brief C API: Miscellaneous definitions + * + * This file contains miscellaneous definitions for the C APIs. + */ + +U_CDECL_BEGIN + +/** A struct representing a range of text containing a specific field + * @stable ICU 2.0 + */ +typedef struct UFieldPosition { + /** + * The field + * @stable ICU 2.0 + */ + int32_t field; + /** + * The start of the text range containing field + * @stable ICU 2.0 + */ + int32_t beginIndex; + /** + * The limit of the text range containing field + * @stable ICU 2.0 + */ + int32_t endIndex; +} UFieldPosition; + +#if !UCONFIG_NO_SERVICE +/** + * Opaque type returned by registerInstance, registerFactory and unregister for service registration. + * @stable ICU 2.6 + */ +typedef const void* URegistryKey; +#endif + +U_CDECL_END + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umsg.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umsg.h new file mode 100644 index 0000000000000000000000000000000000000000..c955dc18ac4d4ab092d9e908f37b696b3120015f --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umsg.h @@ -0,0 +1,628 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/******************************************************************** + * COPYRIGHT: + * Copyright (c) 1997-2011, International Business Machines Corporation and + * others. All Rights Reserved. + * Copyright (C) 2010 , Yahoo! Inc. + ******************************************************************** + * + * file name: umsg.h + * encoding: UTF-8 + * tab size: 8 (not used) + * indentation:4 + * + * Change history: + * + * 08/5/2001 Ram Added C wrappers for C++ API. + ********************************************************************/ + +#ifndef UMSG_H +#define UMSG_H + +#include "unicode/utypes.h" + +#if !UCONFIG_NO_FORMATTING + +#include "unicode/uloc.h" +#include "unicode/parseerr.h" +#include + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C API: MessageFormat + * + *

MessageFormat C API

+ * + *

MessageFormat prepares strings for display to users, + * with optional arguments (variables/placeholders). + * The arguments can occur in any order, which is necessary for translation + * into languages with different grammars. + * + *

The opaque UMessageFormat type is a thin C wrapper around + * a C++ MessageFormat. It is constructed from a pattern string + * with arguments in {curly braces} which will be replaced by formatted values. + * + *

Currently, the C API supports only numbered arguments. + * + *

For details about the pattern syntax and behavior, + * especially about the ASCII apostrophe vs. the + * real apostrophe (single quote) character \htmlonly’\endhtmlonly (U+2019), + * see the C++ MessageFormat class documentation. + * + *

Here are some examples of C API usage: + * Example 1: + *

+ * \code
+ *     UChar *result, *tzID, *str;
+ *     UChar pattern[100];
+ *     int32_t resultLengthOut, resultlength;
+ *     UCalendar *cal;
+ *     UDate d1;
+ *     UDateFormat *def1;
+ *     UErrorCode status = U_ZERO_ERROR;
+ *
+ *     str=(UChar*)malloc(sizeof(UChar) * (strlen("disturbance in force") +1));
+ *     u_uastrcpy(str, "disturbance in force");
+ *     tzID=(UChar*)malloc(sizeof(UChar) * 4);
+ *     u_uastrcpy(tzID, "PST");
+ *     cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status);
+ *     ucal_setDateTime(cal, 1999, UCAL_MARCH, 18, 0, 0, 0, &status);
+ *     d1=ucal_getMillis(cal, &status);
+ *     u_uastrcpy(pattern, "On {0, date, long}, there was a {1} on planet {2,number,integer}");
+ *     resultlength=0;
+ *     resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, d1, str, 7);
+ *     if(status==U_BUFFER_OVERFLOW_ERROR){
+ *         status=U_ZERO_ERROR;
+ *         resultlength=resultLengthOut+1;
+ *         result=(UChar*)realloc(result, sizeof(UChar) * resultlength);
+ *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7);
+ *     }
+ *     printf("%s\n", austrdup(result) );//austrdup( a function used to convert UChar* to char*)
+ *     //output>: "On March 18, 1999, there was a disturbance in force on planet 7
+ * \endcode
+ * 
+ * Typically, the message format will come from resources, and the + * arguments will be dynamically set at runtime. + *

+ * Example 2: + *

+ * \code
+ *     UChar* str;
+ *     UErrorCode status = U_ZERO_ERROR;
+ *     UChar *result;
+ *     UChar pattern[100];
+ *     int32_t resultlength, resultLengthOut, i;
+ *     double testArgs= { 100.0, 1.0, 0.0};
+ *
+ *     str=(UChar*)malloc(sizeof(UChar) * 10);
+ *     u_uastrcpy(str, "MyDisk");
+ *     u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
+ *     for(i=0; i<3; i++){
+ *       resultlength=0; 
+ *       resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str); 
+ *       if(status==U_BUFFER_OVERFLOW_ERROR){
+ *         status=U_ZERO_ERROR;
+ *         resultlength=resultLengthOut+1;
+ *         result=(UChar*)malloc(sizeof(UChar) * resultlength);
+ *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
+ *       }
+ *       printf("%s\n", austrdup(result) );  //austrdup( a function used to convert UChar* to char*)
+ *       free(result);
+ *     }
+ *     // output, with different testArgs:
+ *     // output: The disk "MyDisk" contains 100 files.
+ *     // output: The disk "MyDisk" contains one file.
+ *     // output: The disk "MyDisk" contains no files.
+ * \endcode
+ *  
+ * + * + * Example 3: + *
+ * \code
+ * UChar* str;
+ * UChar* str1;
+ * UErrorCode status = U_ZERO_ERROR;
+ * UChar *result;
+ * UChar pattern[100];
+ * UChar expected[100];
+ * int32_t resultlength,resultLengthOut;
+
+ * str=(UChar*)malloc(sizeof(UChar) * 25);
+ * u_uastrcpy(str, "Kirti");
+ * str1=(UChar*)malloc(sizeof(UChar) * 25);
+ * u_uastrcpy(str1, "female");
+ * log_verbose("Testing message format with Select test #1\n:");
+ * u_uastrcpy(pattern, "{0} est {1, select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris.");
+ * u_uastrcpy(expected, "Kirti est all\\u00E9e \\u00E0 Paris.");
+ * resultlength=0;
+ * resultLengthOut=u_formatMessage( "fr", pattern, u_strlen(pattern), NULL, resultlength, &status, str , str1);
+ * if(status==U_BUFFER_OVERFLOW_ERROR)
+ *  {
+ *      status=U_ZERO_ERROR;
+ *      resultlength=resultLengthOut+1;
+ *      result=(UChar*)malloc(sizeof(UChar) * resultlength);
+ *      u_formatMessage( "fr", pattern, u_strlen(pattern), result, resultlength, &status, str , str1);
+ *      if(u_strcmp(result, expected)==0)
+ *          log_verbose("PASS: MessagFormat successful on Select test#1\n");
+ *      else{
+ *          log_err("FAIL: Error in MessageFormat on Select test#1\n GOT %s EXPECTED %s\n", austrdup(result),
+ *          austrdup(expected) );
+ *      }
+ *      free(result);
+ * }
+ * \endcode
+ *  
+ */ + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param locale The locale for which the message will be formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments specified + * in pattern. + * @return The total buffer size needed; if greater than resultLength, the + * output was truncated. + * @see u_parseMessage + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_formatMessage(const char *locale, + const UChar *pattern, + int32_t patternLength, + UChar *result, + int32_t resultLength, + UErrorCode *status, + ...); + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param locale The locale for which the message will be formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param ap A variable-length argument list containing the arguments specified + * @param status A pointer to an UErrorCode to receive any errors + * in pattern. + * @return The total buffer size needed; if greater than resultLength, the + * output was truncated. + * @see u_parseMessage + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_vformatMessage( const char *locale, + const UChar *pattern, + int32_t patternLength, + UChar *result, + int32_t resultLength, + va_list ap, + UErrorCode *status); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #u_formatMessage }. + * @param locale The locale for which the message is formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments + * specified in pattern. + * @see u_formatMessage + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_parseMessage( const char *locale, + const UChar *pattern, + int32_t patternLength, + const UChar *source, + int32_t sourceLength, + UErrorCode *status, + ...); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #u_formatMessage }. + * @param locale The locale for which the message is formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param ap A variable-length argument list containing the arguments + * @param status A pointer to an UErrorCode to receive any errors + * specified in pattern. + * @see u_formatMessage + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_vparseMessage(const char *locale, + const UChar *pattern, + int32_t patternLength, + const UChar *source, + int32_t sourceLength, + va_list ap, + UErrorCode *status); + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param locale The locale for which the message will be formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments specified + * in pattern. + * @param parseError A pointer to UParseError to receive information about errors + * occurred during parsing. + * @return The total buffer size needed; if greater than resultLength, the + * output was truncated. + * @see u_parseMessage + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_formatMessageWithError( const char *locale, + const UChar *pattern, + int32_t patternLength, + UChar *result, + int32_t resultLength, + UParseError *parseError, + UErrorCode *status, + ...); + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param locale The locale for which the message will be formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param parseError A pointer to UParseError to receive information about errors + * occurred during parsing. + * @param ap A variable-length argument list containing the arguments specified + * @param status A pointer to an UErrorCode to receive any errors + * in pattern. + * @return The total buffer size needed; if greater than resultLength, the + * output was truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +u_vformatMessageWithError( const char *locale, + const UChar *pattern, + int32_t patternLength, + UChar *result, + int32_t resultLength, + UParseError* parseError, + va_list ap, + UErrorCode *status); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #u_formatMessage }. + * @param locale The locale for which the message is formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param parseError A pointer to UParseError to receive information about errors + * occurred during parsing. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments + * specified in pattern. + * @see u_formatMessage + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_parseMessageWithError(const char *locale, + const UChar *pattern, + int32_t patternLength, + const UChar *source, + int32_t sourceLength, + UParseError *parseError, + UErrorCode *status, + ...); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #u_formatMessage }. + * @param locale The locale for which the message is formatted + * @param pattern The pattern specifying the message's format + * @param patternLength The length of pattern + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param ap A variable-length argument list containing the arguments + * @param parseError A pointer to UParseError to receive information about errors + * occurred during parsing. + * @param status A pointer to an UErrorCode to receive any errors + * specified in pattern. + * @see u_formatMessage + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +u_vparseMessageWithError(const char *locale, + const UChar *pattern, + int32_t patternLength, + const UChar *source, + int32_t sourceLength, + va_list ap, + UParseError *parseError, + UErrorCode* status); + +/*----------------------- New experimental API --------------------------- */ +/** + * The message format object + * @stable ICU 2.0 + */ +typedef void* UMessageFormat; + + +/** + * Open a message formatter with given pattern and for the given locale. + * @param pattern A pattern specifying the format to use. + * @param patternLength Length of the pattern to use + * @param locale The locale for which the messages are formatted. + * @param parseError A pointer to UParseError struct to receive any errors + * occurred during parsing. Can be NULL. + * @param status A pointer to an UErrorCode to receive any errors. + * @return A pointer to a UMessageFormat to use for formatting + * messages, or 0 if an error occurred. + * @stable ICU 2.0 + */ +U_CAPI UMessageFormat* U_EXPORT2 +umsg_open( const UChar *pattern, + int32_t patternLength, + const char *locale, + UParseError *parseError, + UErrorCode *status); + +/** + * Close a UMessageFormat. + * Once closed, a UMessageFormat may no longer be used. + * @param format The formatter to close. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +umsg_close(UMessageFormat* format); + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUMessageFormatPointer + * "Smart pointer" class, closes a UMessageFormat via umsg_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 4.4 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUMessageFormatPointer, UMessageFormat, umsg_close); + +U_NAMESPACE_END + +#endif + +/** + * Open a copy of a UMessageFormat. + * This function performs a deep copy. + * @param fmt The formatter to copy + * @param status A pointer to an UErrorCode to receive any errors. + * @return A pointer to a UDateFormat identical to fmt. + * @stable ICU 2.0 + */ +U_CAPI UMessageFormat U_EXPORT2 +umsg_clone(const UMessageFormat *fmt, + UErrorCode *status); + +/** + * Sets the locale. This locale is used for fetching default number or date + * format information. + * @param fmt The formatter to set + * @param locale The locale the formatter should use. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +umsg_setLocale(UMessageFormat *fmt, + const char* locale); + +/** + * Gets the locale. This locale is used for fetching default number or date + * format information. + * @param fmt The formatter to querry + * @return the locale. + * @stable ICU 2.0 + */ +U_CAPI const char* U_EXPORT2 +umsg_getLocale(const UMessageFormat *fmt); + +/** + * Sets the pattern. + * @param fmt The formatter to use + * @param pattern The pattern to be applied. + * @param patternLength Length of the pattern to use + * @param parseError Struct to receive information on position + * of error if an error is encountered.Can be NULL. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +umsg_applyPattern( UMessageFormat *fmt, + const UChar* pattern, + int32_t patternLength, + UParseError* parseError, + UErrorCode* status); + +/** + * Gets the pattern. + * @param fmt The formatter to use + * @param result A pointer to a buffer to receive the pattern. + * @param resultLength The maximum size of result. + * @param status Output param set to success/failure code on + * exit. If the pattern is invalid, this will be + * set to a failure result. + * @return the pattern of the format + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +umsg_toPattern(const UMessageFormat *fmt, + UChar* result, + int32_t resultLength, + UErrorCode* status); + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param fmt The formatter to use + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments + * specified in pattern. + * @return The total buffer size needed; if greater than resultLength, + * the output was truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +umsg_format( const UMessageFormat *fmt, + UChar *result, + int32_t resultLength, + UErrorCode *status, + ...); + +/** + * Format a message for a locale. + * This function may perform re-ordering of the arguments depending on the + * locale. For all numeric arguments, double is assumed unless the type is + * explicitly integer. All choice format arguments must be of type double. + * @param fmt The formatter to use + * @param result A pointer to a buffer to receive the formatted message. + * @param resultLength The maximum size of result. + * @param ap A variable-length argument list containing the arguments + * @param status A pointer to an UErrorCode to receive any errors + * specified in pattern. + * @return The total buffer size needed; if greater than resultLength, + * the output was truncated. + * @stable ICU 2.0 + */ +U_CAPI int32_t U_EXPORT2 +umsg_vformat( const UMessageFormat *fmt, + UChar *result, + int32_t resultLength, + va_list ap, + UErrorCode *status); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #umsg_format }. + * @param fmt The formatter to use + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param count Output param to receive number of elements returned. + * @param status A pointer to an UErrorCode to receive any errors + * @param ... A variable-length argument list containing the arguments + * specified in pattern. + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +umsg_parse( const UMessageFormat *fmt, + const UChar *source, + int32_t sourceLength, + int32_t *count, + UErrorCode *status, + ...); + +/** + * Parse a message. + * For numeric arguments, this function will always use doubles. Integer types + * should not be passed. + * This function is not able to parse all output from {@link #umsg_format }. + * @param fmt The formatter to use + * @param source The text to parse. + * @param sourceLength The length of source, or -1 if null-terminated. + * @param count Output param to receive number of elements returned. + * @param ap A variable-length argument list containing the arguments + * @param status A pointer to an UErrorCode to receive any errors + * specified in pattern. + * @see u_formatMessage + * @stable ICU 2.0 + */ +U_CAPI void U_EXPORT2 +umsg_vparse(const UMessageFormat *fmt, + const UChar *source, + int32_t sourceLength, + int32_t *count, + va_list ap, + UErrorCode *status); + + +/** + * Convert an 'apostrophe-friendly' pattern into a standard + * pattern. Standard patterns treat all apostrophes as + * quotes, which is problematic in some languages, e.g. + * French, where apostrophe is commonly used. This utility + * assumes that only an unpaired apostrophe immediately before + * a brace is a true quote. Other unpaired apostrophes are paired, + * and the resulting standard pattern string is returned. + * + *

Note it is not guaranteed that the returned pattern + * is indeed a valid pattern. The only effect is to convert + * between patterns having different quoting semantics. + * + * @param pattern the 'apostrophe-friendly' patttern to convert + * @param patternLength the length of pattern, or -1 if unknown and pattern is null-terminated + * @param dest the buffer for the result, or NULL if preflight only + * @param destCapacity the length of the buffer, or 0 if preflighting + * @param ec the error code + * @return the length of the resulting text, not including trailing null + * if buffer has room for the trailing null, it is provided, otherwise + * not + * @stable ICU 3.4 + */ +U_CAPI int32_t U_EXPORT2 +umsg_autoQuoteApostrophe(const UChar* pattern, + int32_t patternLength, + UChar* dest, + int32_t destCapacity, + UErrorCode* ec); + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umutablecptrie.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umutablecptrie.h new file mode 100644 index 0000000000000000000000000000000000000000..d60fd618191c480196039ed3a448cf423ba4c8f6 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/umutablecptrie.h @@ -0,0 +1,240 @@ +// © 2017 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html + +// umutablecptrie.h (split out of ucptrie.h) +// created: 2018jan24 Markus W. Scherer + +#ifndef __UMUTABLECPTRIE_H__ +#define __UMUTABLECPTRIE_H__ + +#include "unicode/utypes.h" + +#include "unicode/ucpmap.h" +#include "unicode/ucptrie.h" +#include "unicode/utf8.h" + +#if U_SHOW_CPLUSPLUS_API +#include "unicode/localpointer.h" +#endif // U_SHOW_CPLUSPLUS_API + +U_CDECL_BEGIN + +/** + * \file + * \brief C API: This file defines a mutable Unicode code point trie. + * + * @see UCPTrie + * @see UMutableCPTrie + */ + +/** + * Mutable Unicode code point trie. + * Fast map from Unicode code points (U+0000..U+10FFFF) to 32-bit integer values. + * For details see https://icu.unicode.org/design/struct/utrie + * + * Setting values (especially ranges) and lookup is fast. + * The mutable trie is only somewhat space-efficient. + * It builds a compacted, immutable UCPTrie. + * + * This trie can be modified while iterating over its contents. + * For example, it is possible to merge its values with those from another + * set of ranges (e.g., another mutable or immutable trie): + * Iterate over those source ranges; for each of them iterate over this trie; + * add the source value into the value of each trie range. + * + * @see UCPTrie + * @see umutablecptrie_buildImmutable + * @stable ICU 63 + */ +typedef struct UMutableCPTrie UMutableCPTrie; + +/** + * Creates a mutable trie that initially maps each Unicode code point to the same value. + * It uses 32-bit data values until umutablecptrie_buildImmutable() is called. + * umutablecptrie_buildImmutable() takes a valueWidth parameter which + * determines the number of bits in the data value in the resulting UCPTrie. + * You must umutablecptrie_close() the trie once you are done using it. + * + * @param initialValue the initial value that is set for all code points + * @param errorValue the value for out-of-range code points and ill-formed UTF-8/16 + * @param pErrorCode an in/out ICU UErrorCode + * @return the trie + * @stable ICU 63 + */ +U_CAPI UMutableCPTrie * U_EXPORT2 +umutablecptrie_open(uint32_t initialValue, uint32_t errorValue, UErrorCode *pErrorCode); + +/** + * Clones a mutable trie. + * You must umutablecptrie_close() the clone once you are done using it. + * + * @param other the trie to clone + * @param pErrorCode an in/out ICU UErrorCode + * @return the trie clone + * @stable ICU 63 + */ +U_CAPI UMutableCPTrie * U_EXPORT2 +umutablecptrie_clone(const UMutableCPTrie *other, UErrorCode *pErrorCode); + +/** + * Closes a mutable trie and releases associated memory. + * + * @param trie the trie + * @stable ICU 63 + */ +U_CAPI void U_EXPORT2 +umutablecptrie_close(UMutableCPTrie *trie); + +/** + * Creates a mutable trie with the same contents as the UCPMap. + * You must umutablecptrie_close() the mutable trie once you are done using it. + * + * @param map the source map + * @param pErrorCode an in/out ICU UErrorCode + * @return the mutable trie + * @stable ICU 63 + */ +U_CAPI UMutableCPTrie * U_EXPORT2 +umutablecptrie_fromUCPMap(const UCPMap *map, UErrorCode *pErrorCode); + +/** + * Creates a mutable trie with the same contents as the immutable one. + * You must umutablecptrie_close() the mutable trie once you are done using it. + * + * @param trie the immutable trie + * @param pErrorCode an in/out ICU UErrorCode + * @return the mutable trie + * @stable ICU 63 + */ +U_CAPI UMutableCPTrie * U_EXPORT2 +umutablecptrie_fromUCPTrie(const UCPTrie *trie, UErrorCode *pErrorCode); + +/** + * Returns the value for a code point as stored in the trie. + * + * @param trie the trie + * @param c the code point + * @return the value + * @stable ICU 63 + */ +U_CAPI uint32_t U_EXPORT2 +umutablecptrie_get(const UMutableCPTrie *trie, UChar32 c); + +/** + * Returns the last code point such that all those from start to there have the same value. + * Can be used to efficiently iterate over all same-value ranges in a trie. + * (This is normally faster than iterating over code points and get()ting each value, + * but much slower than a data structure that stores ranges directly.) + * + * The trie can be modified between calls to this function. + * + * If the UCPMapValueFilter function pointer is not NULL, then + * the value to be delivered is passed through that function, and the return value is the end + * of the range where all values are modified to the same actual value. + * The value is unchanged if that function pointer is NULL. + * + * See the same-signature ucptrie_getRange() for a code sample. + * + * @param trie the trie + * @param start range start + * @param option defines whether surrogates are treated normally, + * or as having the surrogateValue; usually UCPMAP_RANGE_NORMAL + * @param surrogateValue value for surrogates; ignored if option==UCPMAP_RANGE_NORMAL + * @param filter a pointer to a function that may modify the trie data value, + * or NULL if the values from the trie are to be used unmodified + * @param context an opaque pointer that is passed on to the filter function + * @param pValue if not NULL, receives the value that every code point start..end has; + * may have been modified by filter(context, trie value) + * if that function pointer is not NULL + * @return the range end code point, or -1 if start is not a valid code point + * @stable ICU 63 + */ +U_CAPI UChar32 U_EXPORT2 +umutablecptrie_getRange(const UMutableCPTrie *trie, UChar32 start, + UCPMapRangeOption option, uint32_t surrogateValue, + UCPMapValueFilter *filter, const void *context, uint32_t *pValue); + +/** + * Sets a value for a code point. + * + * @param trie the trie + * @param c the code point + * @param value the value + * @param pErrorCode an in/out ICU UErrorCode + * @stable ICU 63 + */ +U_CAPI void U_EXPORT2 +umutablecptrie_set(UMutableCPTrie *trie, UChar32 c, uint32_t value, UErrorCode *pErrorCode); + +/** + * Sets a value for each code point [start..end]. + * Faster and more space-efficient than setting the value for each code point separately. + * + * @param trie the trie + * @param start the first code point to get the value + * @param end the last code point to get the value (inclusive) + * @param value the value + * @param pErrorCode an in/out ICU UErrorCode + * @stable ICU 63 + */ +U_CAPI void U_EXPORT2 +umutablecptrie_setRange(UMutableCPTrie *trie, + UChar32 start, UChar32 end, + uint32_t value, UErrorCode *pErrorCode); + +/** + * Compacts the data and builds an immutable UCPTrie according to the parameters. + * After this, the mutable trie will be empty. + * + * The mutable trie stores 32-bit values until buildImmutable() is called. + * If values shorter than 32 bits are to be stored in the immutable trie, + * then the upper bits are discarded. + * For example, when the mutable trie contains values 0x81, -0x7f, and 0xa581, + * and the value width is 8 bits, then each of these is stored as 0x81 + * and the immutable trie will return that as an unsigned value. + * (Some implementations may want to make productive temporary use of the upper bits + * until buildImmutable() discards them.) + * + * Not every possible set of mappings can be built into a UCPTrie, + * because of limitations resulting from speed and space optimizations. + * Every Unicode assigned character can be mapped to a unique value. + * Typical data yields data structures far smaller than the limitations. + * + * It is possible to construct extremely unusual mappings that exceed the data structure limits. + * In such a case this function will fail with a U_INDEX_OUTOFBOUNDS_ERROR. + * + * @param trie the trie trie + * @param type selects the trie type + * @param valueWidth selects the number of bits in a trie data value; if smaller than 32 bits, + * then the values stored in the trie will be truncated first + * @param pErrorCode an in/out ICU UErrorCode + * + * @see umutablecptrie_fromUCPTrie + * @stable ICU 63 + */ +U_CAPI UCPTrie * U_EXPORT2 +umutablecptrie_buildImmutable(UMutableCPTrie *trie, UCPTrieType type, UCPTrieValueWidth valueWidth, + UErrorCode *pErrorCode); + +U_CDECL_END + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +/** + * \class LocalUMutableCPTriePointer + * "Smart pointer" class, closes a UMutableCPTrie via umutablecptrie_close(). + * For most methods see the LocalPointerBase base class. + * + * @see LocalPointerBase + * @see LocalPointer + * @stable ICU 63 + */ +U_DEFINE_LOCAL_OPEN_POINTER(LocalUMutableCPTriePointer, UMutableCPTrie, umutablecptrie_close); + +U_NAMESPACE_END + +#endif + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifilt.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifilt.h new file mode 100644 index 0000000000000000000000000000000000000000..0fcaf4b789c4c290b28a4ca560b431e396a153ed --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifilt.h @@ -0,0 +1,136 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (C) 1999-2010, International Business Machines Corporation and others. +* All Rights Reserved. +********************************************************************** +* Date Name Description +* 11/17/99 aliu Creation. +********************************************************************** +*/ +#ifndef UNIFILT_H +#define UNIFILT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/unifunct.h" +#include "unicode/unimatch.h" + +/** + * \file + * \brief C++ API: Unicode Filter + */ + +U_NAMESPACE_BEGIN + +/** + * U_ETHER is used to represent character values for positions outside + * a range. For example, transliterator uses this to represent + * characters outside the range contextStart..contextLimit-1. This + * allows explicit matching by rules and UnicodeSets of text outside a + * defined range. + * @stable ICU 3.0 + */ +#define U_ETHER ((char16_t)0xFFFF) + +/** + * + * UnicodeFilter defines a protocol for selecting a + * subset of the full range (U+0000 to U+10FFFF) of Unicode characters. + * Currently, filters are used in conjunction with classes like + * {@link Transliterator} to only process selected characters through a + * transformation. + * + *

Note: UnicodeFilter currently stubs out two pure virtual methods + * of its base class, UnicodeMatcher. These methods are toPattern() + * and matchesIndexValue(). This is done so that filter classes that + * are not actually used as matchers -- specifically, those in the + * UnicodeFilterLogic component, and those in tests -- can continue to + * work without defining these methods. As long as a filter is not + * used in an RBT during real transliteration, these methods will not + * be called. However, this breaks the UnicodeMatcher base class + * protocol, and it is not a correct solution. + * + *

In the future we may revisit the UnicodeMatcher / UnicodeFilter + * hierarchy and either redesign it, or simply remove the stubs in + * UnicodeFilter and force subclasses to implement the full + * UnicodeMatcher protocol. + * + * @see UnicodeFilterLogic + * @stable ICU 2.0 + */ +class U_COMMON_API UnicodeFilter : public UnicodeFunctor, public UnicodeMatcher { + +public: + /** + * Destructor + * @stable ICU 2.0 + */ + virtual ~UnicodeFilter(); + + /** + * Clones this object polymorphically. + * The caller owns the result and should delete it when done. + * @return clone, or nullptr if an error occurred + * @stable ICU 2.4 + */ + virtual UnicodeFilter* clone() const override = 0; + + /** + * Returns true for characters that are in the selected + * subset. In other words, if a character is to be + * filtered, then contains() returns + * false. + * @stable ICU 2.0 + */ + virtual UBool contains(UChar32 c) const = 0; + + /** + * UnicodeFunctor API. Cast 'this' to a UnicodeMatcher* pointer + * and return the pointer. + * @stable ICU 2.4 + */ + virtual UnicodeMatcher* toMatcher() const override; + + /** + * Implement UnicodeMatcher API. + * @stable ICU 2.4 + */ + virtual UMatchDegree matches(const Replaceable& text, + int32_t& offset, + int32_t limit, + UBool incremental) override; + + /** + * UnicodeFunctor API. Nothing to do. + * @stable ICU 2.4 + */ + virtual void setData(const TransliterationRuleData*) override; + + /** + * ICU "poor man's RTTI", returns a UClassID for this class. + * + * @stable ICU 2.2 + */ + static UClassID U_EXPORT2 getStaticClassID(); + +protected: + + /* + * Since this class has pure virtual functions, + * a constructor can't be used. + * @stable ICU 2.0 + */ +/* UnicodeFilter();*/ +}; + +/*inline UnicodeFilter::UnicodeFilter() {}*/ + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifunct.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifunct.h new file mode 100644 index 0000000000000000000000000000000000000000..8751302494bcdb346e68801512db10075ebc78c3 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unifunct.h @@ -0,0 +1,132 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2002-2005, International Business Machines Corporation +* and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 01/14/2002 aliu Creation. +********************************************************************** +*/ +#ifndef UNIFUNCT_H +#define UNIFUNCT_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/uobject.h" + +/** + * \file + * \brief C++ API: Unicode Functor + */ + +U_NAMESPACE_BEGIN + +class UnicodeMatcher; +class UnicodeReplacer; +class TransliterationRuleData; + +/** + * UnicodeFunctor is an abstract base class for objects + * that perform match and/or replace operations on Unicode strings. + * @author Alan Liu + * @stable ICU 2.4 + */ +class U_COMMON_API UnicodeFunctor : public UObject { + +public: + + /** + * Destructor + * @stable ICU 2.4 + */ + virtual ~UnicodeFunctor(); + + /** + * Return a copy of this object. All UnicodeFunctor objects + * have to support cloning in order to allow classes using + * UnicodeFunctor to implement cloning. + * @stable ICU 2.4 + */ + virtual UnicodeFunctor* clone() const = 0; + + /** + * Cast 'this' to a UnicodeMatcher* pointer and return the + * pointer, or null if this is not a UnicodeMatcher*. Subclasses + * that mix in UnicodeMatcher as a base class must override this. + * This protocol is required because a pointer to a UnicodeFunctor + * cannot be cast to a pointer to a UnicodeMatcher, since + * UnicodeMatcher is a mixin that does not derive from + * UnicodeFunctor. + * @stable ICU 2.4 + */ + virtual UnicodeMatcher* toMatcher() const; + + /** + * Cast 'this' to a UnicodeReplacer* pointer and return the + * pointer, or null if this is not a UnicodeReplacer*. Subclasses + * that mix in UnicodeReplacer as a base class must override this. + * This protocol is required because a pointer to a UnicodeFunctor + * cannot be cast to a pointer to a UnicodeReplacer, since + * UnicodeReplacer is a mixin that does not derive from + * UnicodeFunctor. + * @stable ICU 2.4 + */ + virtual UnicodeReplacer* toReplacer() const; + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). + * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Returns a unique class ID polymorphically. This method + * is to implement a simple version of RTTI, since not all C++ + * compilers support genuine RTTI. Polymorphic operator==() and + * clone() methods call this method. + * + *

Concrete subclasses of UnicodeFunctor should use the macro + * UOBJECT_DEFINE_RTTI_IMPLEMENTATION from uobject.h to + * provide definitions getStaticClassID and getDynamicClassID. + * + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 2.4 + */ + virtual UClassID getDynamicClassID(void) const override = 0; + + /** + * Set the data object associated with this functor. The data + * object provides context for functor-to-standin mapping. This + * method is required when assigning a functor to a different data + * object. This function MAY GO AWAY later if the architecture is + * changed to pass data object pointers through the API. + * @internal ICU 2.1 + */ + virtual void setData(const TransliterationRuleData*) = 0; + +protected: + + /** + * Since this class has pure virtual functions, + * a constructor can't be used. + * @stable ICU 2.0 + */ + /*UnicodeFunctor();*/ + +}; + +/*inline UnicodeFunctor::UnicodeFunctor() {}*/ + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unimatch.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unimatch.h new file mode 100644 index 0000000000000000000000000000000000000000..302332f4558c3e06abb2e7b1fa3d043695e54cde --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unimatch.h @@ -0,0 +1,168 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +* Copyright (C) 2001-2005, International Business Machines Corporation and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 07/18/01 aliu Creation. +********************************************************************** +*/ +#ifndef UNIMATCH_H +#define UNIMATCH_H + +#include "unicode/utypes.h" + +/** + * \file + * \brief C++ API: Unicode Matcher + */ + +#if U_SHOW_CPLUSPLUS_API + +U_NAMESPACE_BEGIN + +class Replaceable; +class UnicodeString; +class UnicodeSet; + +/** + * Constants returned by UnicodeMatcher::matches() + * indicating the degree of match. + * @stable ICU 2.4 + */ +enum UMatchDegree { + /** + * Constant returned by matches() indicating a + * mismatch between the text and this matcher. The text contains + * a character which does not match, or the text does not contain + * all desired characters for a non-incremental match. + * @stable ICU 2.4 + */ + U_MISMATCH, + + /** + * Constant returned by matches() indicating a + * partial match between the text and this matcher. This value is + * only returned for incremental match operations. All characters + * of the text match, but more characters are required for a + * complete match. Alternatively, for variable-length matchers, + * all characters of the text match, and if more characters were + * supplied at limit, they might also match. + * @stable ICU 2.4 + */ + U_PARTIAL_MATCH, + + /** + * Constant returned by matches() indicating a + * complete match between the text and this matcher. For an + * incremental variable-length match, this value is returned if + * the given text matches, and it is known that additional + * characters would not alter the extent of the match. + * @stable ICU 2.4 + */ + U_MATCH +}; + +/** + * UnicodeMatcher defines a protocol for objects that can + * match a range of characters in a Replaceable string. + * @stable ICU 2.4 + */ +class U_COMMON_API UnicodeMatcher /* not : public UObject because this is an interface/mixin class */ { + +public: + /** + * Destructor. + * @stable ICU 2.4 + */ + virtual ~UnicodeMatcher(); + + /** + * Return a UMatchDegree value indicating the degree of match for + * the given text at the given offset. Zero, one, or more + * characters may be matched. + * + * Matching in the forward direction is indicated by limit > + * offset. Characters from offset forwards to limit-1 will be + * considered for matching. + * + * Matching in the reverse direction is indicated by limit < + * offset. Characters from offset backwards to limit+1 will be + * considered for matching. + * + * If limit == offset then the only match possible is a zero + * character match (which subclasses may implement if desired). + * + * As a side effect, advance the offset parameter to the limit of + * the matched substring. In the forward direction, this will be + * the index of the last matched character plus one. In the + * reverse direction, this will be the index of the last matched + * character minus one. + * + *

Note: This method is not const because some classes may + * modify their state as the result of a match. + * + * @param text the text to be matched + * @param offset on input, the index into text at which to begin + * matching. On output, the limit of the matched text. The + * number of matched characters is the output value of offset + * minus the input value. Offset should always point to the + * HIGH SURROGATE (leading code unit) of a pair of surrogates, + * both on entry and upon return. + * @param limit the limit index of text to be matched. Greater + * than offset for a forward direction match, less than offset for + * a backward direction match. The last character to be + * considered for matching will be text.charAt(limit-1) in the + * forward direction or text.charAt(limit+1) in the backward + * direction. + * @param incremental if true, then assume further characters may + * be inserted at limit and check for partial matching. Otherwise + * assume the text as given is complete. + * @return a match degree value indicating a full match, a partial + * match, or a mismatch. If incremental is false then + * U_PARTIAL_MATCH should never be returned. + * @stable ICU 2.4 + */ + virtual UMatchDegree matches(const Replaceable& text, + int32_t& offset, + int32_t limit, + UBool incremental) = 0; + + /** + * Returns a string representation of this matcher. If the result of + * calling this function is passed to the appropriate parser, it + * will produce another matcher that is equal to this one. + * @param result the string to receive the pattern. Previous + * contents will be deleted. + * @param escapeUnprintable if true then convert unprintable + * character to their hex escape representations, \\uxxxx or + * \\Uxxxxxxxx. Unprintable characters are those other than + * U+000A, U+0020..U+007E. + * @stable ICU 2.4 + */ + virtual UnicodeString& toPattern(UnicodeString& result, + UBool escapeUnprintable = false) const = 0; + + /** + * Returns true if this matcher will match a character c, where c + * & 0xFF == v, at offset, in the forward direction (with limit > + * offset). This is used by RuleBasedTransliterator for + * indexing. + * @stable ICU 2.4 + */ + virtual UBool matchesIndexValue(uint8_t v) const = 0; + + /** + * Union the set of all characters that may be matched by this object + * into the given set. + * @param toUnionTo the set into which to union the source characters + * @stable ICU 2.4 + */ + virtual void addMatchSetTo(UnicodeSet& toUnionTo) const = 0; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unirepl.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unirepl.h new file mode 100644 index 0000000000000000000000000000000000000000..7f6edcf61ad801fdf7e61e9018c686bc94ee5367 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/unirepl.h @@ -0,0 +1,103 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +********************************************************************** +* Copyright (c) 2002-2005, International Business Machines Corporation +* and others. All Rights Reserved. +********************************************************************** +* Date Name Description +* 01/14/2002 aliu Creation. +********************************************************************** +*/ +#ifndef UNIREPL_H +#define UNIREPL_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +/** + * \file + * \brief C++ API: UnicodeReplacer + */ + +U_NAMESPACE_BEGIN + +class Replaceable; +class UnicodeString; +class UnicodeSet; + +/** + * UnicodeReplacer defines a protocol for objects that + * replace a range of characters in a Replaceable string with output + * text. The replacement is done via the Replaceable API so as to + * preserve out-of-band data. + * + *

This is a mixin class. + * @author Alan Liu + * @stable ICU 2.4 + */ +class U_I18N_API UnicodeReplacer /* not : public UObject because this is an interface/mixin class */ { + + public: + + /** + * Destructor. + * @stable ICU 2.4 + */ + virtual ~UnicodeReplacer(); + + /** + * Replace characters in 'text' from 'start' to 'limit' with the + * output text of this object. Update the 'cursor' parameter to + * give the cursor position and return the length of the + * replacement text. + * + * @param text the text to be matched + * @param start inclusive start index of text to be replaced + * @param limit exclusive end index of text to be replaced; + * must be greater than or equal to start + * @param cursor output parameter for the cursor position. + * Not all replacer objects will update this, but in a complete + * tree of replacer objects, representing the entire output side + * of a transliteration rule, at least one must update it. + * @return the number of 16-bit code units in the text replacing + * the characters at offsets start..(limit-1) in text + * @stable ICU 2.4 + */ + virtual int32_t replace(Replaceable& text, + int32_t start, + int32_t limit, + int32_t& cursor) = 0; + + /** + * Returns a string representation of this replacer. If the + * result of calling this function is passed to the appropriate + * parser, typically TransliteratorParser, it will produce another + * replacer that is equal to this one. + * @param result the string to receive the pattern. Previous + * contents will be deleted. + * @param escapeUnprintable if true then convert unprintable + * character to their hex escape representations, \\uxxxx or + * \\Uxxxxxxxx. Unprintable characters are defined by + * Utility.isUnprintable(). + * @return a reference to 'result'. + * @stable ICU 2.4 + */ + virtual UnicodeString& toReplacerPattern(UnicodeString& result, + UBool escapeUnprintable) const = 0; + + /** + * Union the set of all characters that may output by this object + * into the given set. + * @param toUnionTo the set into which to union the output characters + * @stable ICU 2.4 + */ + virtual void addReplacementSetTo(UnicodeSet& toUnionTo) const = 0; +}; + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif diff --git a/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uniset.h b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uniset.h new file mode 100644 index 0000000000000000000000000000000000000000..84774d9f36ecf675bc5d3eaa6713fe4cbd709af7 --- /dev/null +++ b/miniconda3/pkgs/icu-73.1-h6a678d5_0/include/unicode/uniset.h @@ -0,0 +1,1793 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html +/* +*************************************************************************** +* Copyright (C) 1999-2016, International Business Machines Corporation +* and others. All Rights Reserved. +*************************************************************************** +* Date Name Description +* 10/20/99 alan Creation. +*************************************************************************** +*/ + +#ifndef UNICODESET_H +#define UNICODESET_H + +#include "unicode/utypes.h" + +#if U_SHOW_CPLUSPLUS_API + +#include "unicode/ucpmap.h" +#include "unicode/unifilt.h" +#include "unicode/unistr.h" +#include "unicode/uset.h" + +/** + * \file + * \brief C++ API: Unicode Set + */ + +U_NAMESPACE_BEGIN + +// Forward Declarations. +class BMPSet; +class ParsePosition; +class RBBIRuleScanner; +class SymbolTable; +class UnicodeSetStringSpan; +class UVector; +class RuleCharacterIterator; + +/** + * A mutable set of Unicode characters and multicharacter strings. Objects of this class + * represent character classes used in regular expressions. + * A character specifies a subset of Unicode code points. Legal + * code points are U+0000 to U+10FFFF, inclusive. + * + *

The UnicodeSet class is not designed to be subclassed. + * + *

UnicodeSet supports two APIs. The first is the + * operand API that allows the caller to modify the value of + * a UnicodeSet object. It conforms to Java 2's + * java.util.Set interface, although + * UnicodeSet does not actually implement that + * interface. All methods of Set are supported, with the + * modification that they take a character range or single character + * instead of an Object, and they take a + * UnicodeSet instead of a Collection. The + * operand API may be thought of in terms of boolean logic: a boolean + * OR is implemented by add, a boolean AND is implemented + * by retain, a boolean XOR is implemented by + * complement taking an argument, and a boolean NOT is + * implemented by complement with no argument. In terms + * of traditional set theory function names, add is a + * union, retain is an intersection, remove + * is an asymmetric difference, and complement with no + * argument is a set complement with respect to the superset range + * MIN_VALUE-MAX_VALUE + * + *

The second API is the + * applyPattern()/toPattern() API from the + * java.text.Format-derived classes. Unlike the + * methods that add characters, add categories, and control the logic + * of the set, the method applyPattern() sets all + * attributes of a UnicodeSet at once, based on a + * string pattern. + * + *

Pattern syntax

+ * + * Patterns are accepted by the constructors and the + * applyPattern() methods and returned by the + * toPattern() method. These patterns follow a syntax + * similar to that employed by version 8 regular expression character + * classes. Here are some simple examples: + * + * \htmlonly
\endhtmlonly + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
[]No characters
[a]The character 'a'
[ae]The characters 'a' and 'e'
[a-e]The characters 'a' through 'e' inclusive, in Unicode code + * point order
[\\u4E01]The character U+4E01
[a{ab}{ac}]The character 'a' and the multicharacter strings "ab" and + * "ac"
[\\p{Lu}]All characters in the general category Uppercase Letter
+ * \htmlonly
\endhtmlonly + * + * Any character may be preceded by a backslash in order to remove any special + * meaning. White space characters, as defined by UCharacter.isWhitespace(), are + * ignored, unless they are escaped. + * + *

Property patterns specify a set of characters having a certain + * property as defined by the Unicode standard. Both the POSIX-like + * "[:Lu:]" and the Perl-like syntax "\\p{Lu}" are recognized. For a + * complete list of supported property patterns, see the User's Guide + * for UnicodeSet at + * + * https://unicode-org.github.io/icu/userguide/strings/unicodeset. + * Actual determination of property data is defined by the underlying + * Unicode database as implemented by UCharacter. + * + *

Patterns specify individual characters, ranges of characters, and + * Unicode property sets. When elements are concatenated, they + * specify their union. To complement a set, place a '^' immediately + * after the opening '['. Property patterns are inverted by modifying + * their delimiters; "[:^foo]" and "\\P{foo}". In any other location, + * '^' has no special meaning. + * + *

Since ICU 70, "[^...]", "[:^foo]", "\\P{foo}", and "[:binaryProperty=No:]" + * perform a “code point complement” (all code points minus the original set), + * removing all multicharacter strings, + * equivalent to .complement().removeAllStrings(). + * The complement() API function continues to perform a + * symmetric difference with all code points and thus retains all multicharacter strings. + * + *

Ranges are indicated by placing two a '-' between two + * characters, as in "a-z". This specifies the range of all + * characters from the left to the right, in Unicode order. If the + * left character is greater than or equal to the + * right character it is a syntax error. If a '-' occurs as the first + * character after the opening '[' or '[^', or if it occurs as the + * last character before the closing ']', then it is taken as a + * literal. Thus "[a\-b]", "[-ab]", and "[ab-]" all indicate the same + * set of three characters, 'a', 'b', and '-'. + * + *

Sets may be intersected using the '&' operator or the asymmetric + * set difference may be taken using the '-' operator, for example, + * "[[:L:]&[\\u0000-\\u0FFF]]" indicates the set of all Unicode letters + * with values less than 4096. Operators ('&' and '|') have equal + * precedence and bind left-to-right. Thus + * "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to + * "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]". This only really matters for + * difference; intersection is commutative. + * + * + *
[a]The set containing 'a' + *
[a-z]The set containing 'a' + * through 'z' and all letters in between, in Unicode order + *
[^a-z]The set containing + * all characters but 'a' through 'z', + * that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF + *
[[pat1][pat2]] + * The union of sets specified by pat1 and pat2 + *
[[pat1]&[pat2]] + * The intersection of sets specified by pat1 and pat2 + *
[[pat1]-[pat2]] + * The asymmetric difference of sets specified by pat1 and + * pat2 + *
[:Lu:] or \\p{Lu} + * The set of characters having the specified + * Unicode property; in + * this case, Unicode uppercase letters + *
[:^Lu:] or \\P{Lu} + * The set of characters not having the given + * Unicode property + *
+ * + *

Formal syntax

+ * + * \htmlonly
\endhtmlonly + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
pattern :=  ('[' '^'? item* ']') | + * property
item :=  char | (char '-' char) | pattern-expr
+ *
pattern-expr :=  pattern | pattern-expr pattern | + * pattern-expr op pattern
+ *
op :=  '&' | '-'
+ *
special :=  '[' | ']' | '-'
+ *
char :=  any character that is not special
+ * | ('\'
any character)
+ * | ('\\u' hex hex hex hex)
+ *
hex :=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
+ *     'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
property :=  a Unicode property set pattern
+ *
+ * + * + * + * + *
Legend: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
a := b  a may be replaced by b
a?zero or one instance of a
+ *
a*one or more instances of a
+ *
a | beither a or b
+ *
'a'the literal string between the quotes
+ *
+ * \htmlonly
\endhtmlonly + * + *

Note: + * - Most UnicodeSet methods do not take a UErrorCode parameter because + * there are usually very few opportunities for failure other than a shortage + * of memory, error codes in low-level C++ string methods would be inconvenient, + * and the error code as the last parameter (ICU convention) would prevent + * the use of default parameter values. + * Instead, such methods set the UnicodeSet into a "bogus" state + * (see isBogus()) if an error occurs. + * + * @author Alan Liu + * @stable ICU 2.0 + */ +class U_COMMON_API UnicodeSet final : public UnicodeFilter { +private: + /** + * Enough for sets with few ranges. + * For example, White_Space has 10 ranges, list length 21. + */ + static constexpr int32_t INITIAL_CAPACITY = 25; + // fFlags constant + static constexpr uint8_t kIsBogus = 1; // This set is bogus (i.e. not valid) + + UChar32* list = stackList; // MUST be terminated with HIGH + int32_t capacity = INITIAL_CAPACITY; // capacity of list + int32_t len = 1; // length of list used; 1 <= len <= capacity + uint8_t fFlags = 0; // Bit flag (see constants above) + + BMPSet *bmpSet = nullptr; // The set is frozen iff either bmpSet or stringSpan is not nullptr. + UChar32* buffer = nullptr; // internal buffer, may be nullptr + int32_t bufferCapacity = 0; // capacity of buffer + + /** + * The pattern representation of this set. This may not be the + * most economical pattern. It is the pattern supplied to + * applyPattern(), with variables substituted and whitespace + * removed. For sets constructed without applyPattern(), or + * modified using the non-pattern API, this string will be empty, + * indicating that toPattern() must generate a pattern + * representation from the inversion list. + */ + char16_t *pat = nullptr; + int32_t patLen = 0; + + UVector* strings = nullptr; // maintained in sorted order + UnicodeSetStringSpan *stringSpan = nullptr; + + /** + * Initial list array. + * Avoids some heap allocations, and list is never nullptr. + * Increases the object size a bit. + */ + UChar32 stackList[INITIAL_CAPACITY]; + +public: + /** + * Determine if this object contains a valid set. + * A bogus set has no value. It is different from an empty set. + * It can be used to indicate that no set value is available. + * + * @return true if the set is bogus/invalid, false otherwise + * @see setToBogus() + * @stable ICU 4.0 + */ + inline UBool isBogus(void) const; + + /** + * Make this UnicodeSet object invalid. + * The string will test true with isBogus(). + * + * A bogus set has no value. It is different from an empty set. + * It can be used to indicate that no set value is available. + * + * This utility function is used throughout the UnicodeSet + * implementation to indicate that a UnicodeSet operation failed, + * and may be used in other functions, + * especially but not exclusively when such functions do not + * take a UErrorCode for simplicity. + * + * @see isBogus() + * @stable ICU 4.0 + */ + void setToBogus(); + +public: + + enum { + /** + * Minimum value that can be stored in a UnicodeSet. + * @stable ICU 2.4 + */ + MIN_VALUE = 0, + + /** + * Maximum value that can be stored in a UnicodeSet. + * @stable ICU 2.4 + */ + MAX_VALUE = 0x10ffff + }; + + //---------------------------------------------------------------- + // Constructors &c + //---------------------------------------------------------------- + +public: + + /** + * Constructs an empty set. + * @stable ICU 2.0 + */ + UnicodeSet(); + + /** + * Constructs a set containing the given range. If end < + * start then an empty set is created. + * + * @param start first character, inclusive, of range + * @param end last character, inclusive, of range + * @stable ICU 2.4 + */ + UnicodeSet(UChar32 start, UChar32 end); + +#ifndef U_HIDE_INTERNAL_API + /** + * @internal + */ + enum ESerialization { + kSerialized /* result of serialize() */ + }; + + /** + * Constructs a set from the output of serialize(). + * + * @param buffer the 16 bit array + * @param bufferLen the original length returned from serialize() + * @param serialization the value 'kSerialized' + * @param status error code + * + * @internal + */ + UnicodeSet(const uint16_t buffer[], int32_t bufferLen, + ESerialization serialization, UErrorCode &status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Constructs a set from the given pattern. See the class + * description for the syntax of the pattern language. + * @param pattern a string specifying what characters are in the set + * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern + * contains a syntax error. + * @stable ICU 2.0 + */ + UnicodeSet(const UnicodeString& pattern, + UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Constructs a set from the given pattern. See the class + * description for the syntax of the pattern language. + * @param pattern a string specifying what characters are in the set + * @param options bitmask for options to apply to the pattern. + * Valid options are USET_IGNORE_SPACE and + * at most one of USET_CASE_INSENSITIVE, USET_ADD_CASE_MAPPINGS, USET_SIMPLE_CASE_INSENSITIVE. + * These case options are mutually exclusive. + * @param symbols a symbol table mapping variable names to values + * and stand-in characters to UnicodeSets; may be nullptr + * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern + * contains a syntax error. + * @internal + */ + UnicodeSet(const UnicodeString& pattern, + uint32_t options, + const SymbolTable* symbols, + UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Constructs a set from the given pattern. See the class description + * for the syntax of the pattern language. + * @param pattern a string specifying what characters are in the set + * @param pos on input, the position in pattern at which to start parsing. + * On output, the position after the last character parsed. + * @param options bitmask for options to apply to the pattern. + * Valid options are USET_IGNORE_SPACE and + * at most one of USET_CASE_INSENSITIVE, USET_ADD_CASE_MAPPINGS, USET_SIMPLE_CASE_INSENSITIVE. + * These case options are mutually exclusive. + * @param symbols a symbol table mapping variable names to values + * and stand-in characters to UnicodeSets; may be nullptr + * @param status input-output error code + * @stable ICU 2.8 + */ + UnicodeSet(const UnicodeString& pattern, ParsePosition& pos, + uint32_t options, + const SymbolTable* symbols, + UErrorCode& status); + + /** + * Constructs a set that is identical to the given UnicodeSet. + * @stable ICU 2.0 + */ + UnicodeSet(const UnicodeSet& o); + + /** + * Destructs the set. + * @stable ICU 2.0 + */ + virtual ~UnicodeSet(); + + /** + * Assigns this object to be a copy of another. + * A frozen set will not be modified. + * @stable ICU 2.0 + */ + UnicodeSet& operator=(const UnicodeSet& o); + + /** + * Compares the specified object with this set for equality. Returns + * true if the two sets + * have the same size, and every member of the specified set is + * contained in this set (or equivalently, every member of this set is + * contained in the specified set). + * + * @param o set to be compared for equality with this set. + * @return true if the specified set is equal to this set. + * @stable ICU 2.0 + */ + virtual bool operator==(const UnicodeSet& o) const; + + /** + * Compares the specified object with this set for equality. Returns + * true if the specified set is not equal to this set. + * @stable ICU 2.0 + */ + inline bool operator!=(const UnicodeSet& o) const; + + /** + * Returns a copy of this object. All UnicodeFunctor objects have + * to support cloning in order to allow classes using + * UnicodeFunctors, such as Transliterator, to implement cloning. + * If this set is frozen, then the clone will be frozen as well. + * Use cloneAsThawed() for a mutable clone of a frozen set. + * @see cloneAsThawed + * @stable ICU 2.0 + */ + virtual UnicodeSet* clone() const override; + + /** + * Returns the hash code value for this set. + * + * @return the hash code value for this set. + * @see Object#hashCode() + * @stable ICU 2.0 + */ + virtual int32_t hashCode(void) const; + + /** + * Get a UnicodeSet pointer from a USet + * + * @param uset a USet (the ICU plain C type for UnicodeSet) + * @return the corresponding UnicodeSet pointer. + * + * @stable ICU 4.2 + */ + inline static UnicodeSet *fromUSet(USet *uset); + + /** + * Get a UnicodeSet pointer from a const USet + * + * @param uset a const USet (the ICU plain C type for UnicodeSet) + * @return the corresponding UnicodeSet pointer. + * + * @stable ICU 4.2 + */ + inline static const UnicodeSet *fromUSet(const USet *uset); + + /** + * Produce a USet * pointer for this UnicodeSet. + * USet is the plain C type for UnicodeSet + * + * @return a USet pointer for this UnicodeSet + * @stable ICU 4.2 + */ + inline USet *toUSet(); + + + /** + * Produce a const USet * pointer for this UnicodeSet. + * USet is the plain C type for UnicodeSet + * + * @return a const USet pointer for this UnicodeSet + * @stable ICU 4.2 + */ + inline const USet * toUSet() const; + + + //---------------------------------------------------------------- + // Freezable API + //---------------------------------------------------------------- + + /** + * Determines whether the set has been frozen (made immutable) or not. + * See the ICU4J Freezable interface for details. + * @return true/false for whether the set has been frozen + * @see freeze + * @see cloneAsThawed + * @stable ICU 3.8 + */ + inline UBool isFrozen() const; + + /** + * Freeze the set (make it immutable). + * Once frozen, it cannot be unfrozen and is therefore thread-safe + * until it is deleted. + * See the ICU4J Freezable interface for details. + * Freezing the set may also make some operations faster, for example + * contains() and span(). + * A frozen set will not be modified. (It remains frozen.) + * @return this set. + * @see isFrozen + * @see cloneAsThawed + * @stable ICU 3.8 + */ + UnicodeSet *freeze(); + + /** + * Clone the set and make the clone mutable. + * See the ICU4J Freezable interface for details. + * @return the mutable clone + * @see freeze + * @see isFrozen + * @stable ICU 3.8 + */ + UnicodeSet *cloneAsThawed() const; + + //---------------------------------------------------------------- + // Public API + //---------------------------------------------------------------- + + /** + * Make this object represent the range `start - end`. + * If `start > end` then this object is set to an empty range. + * A frozen set will not be modified. + * + * @param start first character in the set, inclusive + * @param end last character in the set, inclusive + * @stable ICU 2.4 + */ + UnicodeSet& set(UChar32 start, UChar32 end); + + /** + * Return true if the given position, in the given pattern, appears + * to be the start of a UnicodeSet pattern. + * @stable ICU 2.4 + */ + static UBool resemblesPattern(const UnicodeString& pattern, + int32_t pos); + + /** + * Modifies this set to represent the set specified by the given + * pattern, ignoring Unicode Pattern_White_Space characters. + * See the class description for the syntax of the pattern language. + * A frozen set will not be modified. + * @param pattern a string specifying what characters are in the set + * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern + * contains a syntax error. + * Empties the set passed before applying the pattern. + * @return a reference to this + * @stable ICU 2.0 + */ + UnicodeSet& applyPattern(const UnicodeString& pattern, + UErrorCode& status); + +#ifndef U_HIDE_INTERNAL_API + /** + * Modifies this set to represent the set specified by the given + * pattern, optionally ignoring Unicode Pattern_White_Space characters. + * See the class description for the syntax of the pattern language. + * A frozen set will not be modified. + * @param pattern a string specifying what characters are in the set + * @param options bitmask for options to apply to the pattern. + * Valid options are USET_IGNORE_SPACE and + * at most one of USET_CASE_INSENSITIVE, USET_ADD_CASE_MAPPINGS, USET_SIMPLE_CASE_INSENSITIVE. + * These case options are mutually exclusive. + * @param symbols a symbol table mapping variable names to + * values and stand-ins to UnicodeSets; may be nullptr + * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern + * contains a syntax error. + * Empties the set passed before applying the pattern. + * @return a reference to this + * @internal + */ + UnicodeSet& applyPattern(const UnicodeString& pattern, + uint32_t options, + const SymbolTable* symbols, + UErrorCode& status); +#endif /* U_HIDE_INTERNAL_API */ + + /** + * Parses the given pattern, starting at the given position. The + * character at pattern.charAt(pos.getIndex()) must be '[', or the + * parse fails. Parsing continues until the corresponding closing + * ']'. If a syntax error is encountered between the opening and + * closing brace, the parse fails. Upon return from a successful + * parse, the ParsePosition is updated to point to the character + * following the closing ']', and a StringBuffer containing a + * pairs list for the parsed pattern is returned. This method calls + * itself recursively to parse embedded subpatterns. + * Empties the set passed before applying the pattern. + * A frozen set will not be modified. + * + * @param pattern the string containing the pattern to be parsed. + * The portion of the string from pos.getIndex(), which must be a + * '[', to the corresponding closing ']', is parsed. + * @param pos upon entry, the position at which to being parsing. + * The character at pattern.charAt(pos.getIndex()) must be a '['. + * Upon return from a successful parse, pos.getIndex() is either + * the character after the closing ']' of the parsed pattern, or + * pattern.length() if the closing ']' is the last character of + * the pattern string. + * @param options bitmask for options to apply to the pattern. + * Valid options are USET_IGNORE_SPACE and + * at most one of USET_CASE_INSENSITIVE, USET_ADD_CASE_MAPPINGS, USET_SIMPLE_CASE_INSENSITIVE. + * These case options are mutually exclusive. + * @param symbols a symbol table mapping variable names to + * values and stand-ins to UnicodeSets; may be nullptr + * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern + * contains a syntax error. + * @return a reference to this + * @stable ICU 2.8 + */ + UnicodeSet& applyPattern(const UnicodeString& pattern, + ParsePosition& pos, + uint32_t options, + const SymbolTable* symbols, + UErrorCode& status); + + /** + * Returns a string representation of this set. If the result of + * calling this function is passed to a UnicodeSet constructor, it + * will produce another set that is equal to this one. + * A frozen set will not be modified. + * @param result the string to receive the rules. Previous + * contents will be deleted. + * @param escapeUnprintable if true then convert unprintable + * character to their hex escape representations, \\uxxxx or + * \\Uxxxxxxxx. Unprintable characters are those other than + * U+000A, U+0020..U+007E. + * @stable ICU 2.0 + */ + virtual UnicodeString& toPattern(UnicodeString& result, + UBool escapeUnprintable = false) const override; + + /** + * Modifies this set to contain those code points which have the given value + * for the given binary or enumerated property, as returned by + * u_getIntPropertyValue. Prior contents of this set are lost. + * A frozen set will not be modified. + * + * @param prop a property in the range UCHAR_BIN_START..UCHAR_BIN_LIMIT-1 + * or UCHAR_INT_START..UCHAR_INT_LIMIT-1 + * or UCHAR_MASK_START..UCHAR_MASK_LIMIT-1. + * + * @param value a value in the range u_getIntPropertyMinValue(prop).. + * u_getIntPropertyMaxValue(prop), with one exception. If prop is + * UCHAR_GENERAL_CATEGORY_MASK, then value should not be a UCharCategory, but + * rather a mask value produced by U_GET_GC_MASK(). This allows grouped + * categories such as [:L:] to be represented. + * + * @param ec error code input/output parameter + * + * @return a reference to this set + * + * @stable ICU 2.4 + */ + UnicodeSet& applyIntPropertyValue(UProperty prop, + int32_t value, + UErrorCode& ec); + + /** + * Modifies this set to contain those code points which have the + * given value for the given property. Prior contents of this + * set are lost. + * A frozen set will not be modified. + * + * @param prop a property alias, either short or long. The name is matched + * loosely. See PropertyAliases.txt for names and a description of loose + * matching. If the value string is empty, then this string is interpreted + * as either a General_Category value alias, a Script value alias, a binary + * property alias, or a special ID. Special IDs are matched loosely and + * correspond to the following sets: + * + * "ANY" = [\\u0000-\\U0010FFFF], + * "ASCII" = [\\u0000-\\u007F], + * "Assigned" = [:^Cn:]. + * + * @param value a value alias, either short or long. The name is matched + * loosely. See PropertyValueAliases.txt for names and a description of + * loose matching. In addition to aliases listed, numeric values and + * canonical combining classes may be expressed numerically, e.g., ("nv", + * "0.5") or ("ccc", "220"). The value string may also be empty. + * + * @param ec error code input/output parameter + * + * @return a reference to this set + * + * @stable ICU 2.4 + */ + UnicodeSet& applyPropertyAlias(const UnicodeString& prop, + const UnicodeString& value, + UErrorCode& ec); + + /** + * Returns the number of elements in this set (its cardinality). + * Note than the elements of a set may include both individual + * codepoints and strings. + * + * This is slower than getRangeCount() because + * it counts the code points of all ranges. + * + * @return the number of elements in this set (its cardinality). + * @stable ICU 2.0 + * @see getRangeCount + */ + virtual int32_t size(void) const; + + /** + * Returns true if this set contains no elements. + * + * @return true if this set contains no elements. + * @stable ICU 2.0 + */ + virtual UBool isEmpty(void) const; + + /** + * @return true if this set contains multi-character strings or the empty string. + * @stable ICU 70 + */ + UBool hasStrings() const; + + /** + * Returns true if this set contains the given character. + * This function works faster with a frozen set. + * @param c character to be checked for containment + * @return true if the test condition is met + * @stable ICU 2.0 + */ + virtual UBool contains(UChar32 c) const override; + + /** + * Returns true if this set contains every character + * of the given range. + * @param start first character, inclusive, of the range + * @param end last character, inclusive, of the range + * @return true if the test condition is met + * @stable ICU 2.0 + */ + virtual UBool contains(UChar32 start, UChar32 end) const; + + /** + * Returns true if this set contains the given + * multicharacter string. + * @param s string to be checked for containment + * @return true if this set contains the specified string + * @stable ICU 2.4 + */ + UBool contains(const UnicodeString& s) const; + + /** + * Returns true if this set contains all the characters and strings + * of the given set. + * @param c set to be checked for containment + * @return true if the test condition is met + * @stable ICU 2.4 + */ + virtual UBool containsAll(const UnicodeSet& c) const; + + /** + * Returns true if this set contains all the characters + * of the given string. + * @param s string containing characters to be checked for containment + * @return true if the test condition is met + * @stable ICU 2.4 + */ + UBool containsAll(const UnicodeString& s) const; + + /** + * Returns true if this set contains none of the characters + * of the given range. + * @param start first character, inclusive, of the range + * @param end last character, inclusive, of the range + * @return true if the test condition is met + * @stable ICU 2.4 + */ + UBool containsNone(UChar32 start, UChar32 end) const; + + /** + * Returns true if this set contains none of the characters and strings + * of the given set. + * @param c set to be checked for containment + * @return true if the test condition is met + * @stable ICU 2.4 + */ + UBool containsNone(const UnicodeSet& c) const; + + /** + * Returns true if this set contains none of the characters + * of the given string. + * @param s string containing characters to be checked for containment + * @return true if the test condition is met + * @stable ICU 2.4 + */ + UBool containsNone(const UnicodeString& s) const; + + /** + * Returns true if this set contains one or more of the characters + * in the given range. + * @param start first character, inclusive, of the range + * @param end last character, inclusive, of the range + * @return true if the condition is met + * @stable ICU 2.4 + */ + inline UBool containsSome(UChar32 start, UChar32 end) const; + + /** + * Returns true if this set contains one or more of the characters + * and strings of the given set. + * @param s The set to be checked for containment + * @return true if the condition is met + * @stable ICU 2.4 + */ + inline UBool containsSome(const UnicodeSet& s) const; + + /** + * Returns true if this set contains one or more of the characters + * of the given string. + * @param s string containing characters to be checked for containment + * @return true if the condition is met + * @stable ICU 2.4 + */ + inline UBool containsSome(const UnicodeString& s) const; + + /** + * Returns the length of the initial substring of the input string which + * consists only of characters and strings that are contained in this set + * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), + * or only of characters and strings that are not contained + * in this set (USET_SPAN_NOT_CONTAINED). + * See USetSpanCondition for details. + * Similar to the strspn() C library function. + * Unpaired surrogates are treated according to contains() of their surrogate code points. + * This function works faster with a frozen set and with a non-negative string length argument. + * @param s start of the string + * @param length of the string; can be -1 for NUL-terminated + * @param spanCondition specifies the containment condition + * @return the length of the initial substring according to the spanCondition; + * 0 if the start of the string does not fit the spanCondition + * @stable ICU 3.8 + * @see USetSpanCondition + */ + int32_t span(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const; + + /** + * Returns the end of the substring of the input string according to the USetSpanCondition. + * Same as start+span(s.getBuffer()+start, s.length()-start, spanCondition) + * after pinning start to 0<=start<=s.length(). + * @param s the string + * @param start the start index in the string for the span operation + * @param spanCondition specifies the containment condition + * @return the exclusive end of the substring according to the spanCondition; + * the substring s.tempSubStringBetween(start, end) fulfills the spanCondition + * @stable ICU 4.4 + * @see USetSpanCondition + */ + inline int32_t span(const UnicodeString &s, int32_t start, USetSpanCondition spanCondition) const; + + /** + * Returns the start of the trailing substring of the input string which + * consists only of characters and strings that are contained in this set + * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), + * or only of characters and strings that are not contained + * in this set (USET_SPAN_NOT_CONTAINED). + * See USetSpanCondition for details. + * Unpaired surrogates are treated according to contains() of their surrogate code points. + * This function works faster with a frozen set and with a non-negative string length argument. + * @param s start of the string + * @param length of the string; can be -1 for NUL-terminated + * @param spanCondition specifies the containment condition + * @return the start of the trailing substring according to the spanCondition; + * the string length if the end of the string does not fit the spanCondition + * @stable ICU 3.8 + * @see USetSpanCondition + */ + int32_t spanBack(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const; + + /** + * Returns the start of the substring of the input string according to the USetSpanCondition. + * Same as spanBack(s.getBuffer(), limit, spanCondition) + * after pinning limit to 0<=end<=s.length(). + * @param s the string + * @param limit the exclusive-end index in the string for the span operation + * (use s.length() or INT32_MAX for spanning back from the end of the string) + * @param spanCondition specifies the containment condition + * @return the start of the substring according to the spanCondition; + * the substring s.tempSubStringBetween(start, limit) fulfills the spanCondition + * @stable ICU 4.4 + * @see USetSpanCondition + */ + inline int32_t spanBack(const UnicodeString &s, int32_t limit, USetSpanCondition spanCondition) const; + + /** + * Returns the length of the initial substring of the input string which + * consists only of characters and strings that are contained in this set + * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), + * or only of characters and strings that are not contained + * in this set (USET_SPAN_NOT_CONTAINED). + * See USetSpanCondition for details. + * Similar to the strspn() C library function. + * Malformed byte sequences are treated according to contains(0xfffd). + * This function works faster with a frozen set and with a non-negative string length argument. + * @param s start of the string (UTF-8) + * @param length of the string; can be -1 for NUL-terminated + * @param spanCondition specifies the containment condition + * @return the length of the initial substring according to the spanCondition; + * 0 if the start of the string does not fit the spanCondition + * @stable ICU 3.8 + * @see USetSpanCondition + */ + int32_t spanUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const; + + /** + * Returns the start of the trailing substring of the input string which + * consists only of characters and strings that are contained in this set + * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), + * or only of characters and strings that are not contained + * in this set (USET_SPAN_NOT_CONTAINED). + * See USetSpanCondition for details. + * Malformed byte sequences are treated according to contains(0xfffd). + * This function works faster with a frozen set and with a non-negative string length argument. + * @param s start of the string (UTF-8) + * @param length of the string; can be -1 for NUL-terminated + * @param spanCondition specifies the containment condition + * @return the start of the trailing substring according to the spanCondition; + * the string length if the end of the string does not fit the spanCondition + * @stable ICU 3.8 + * @see USetSpanCondition + */ + int32_t spanBackUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const; + + /** + * Implement UnicodeMatcher::matches() + * @stable ICU 2.4 + */ + virtual UMatchDegree matches(const Replaceable& text, + int32_t& offset, + int32_t limit, + UBool incremental) override; + +private: + /** + * Returns the longest match for s in text at the given position. + * If limit > start then match forward from start+1 to limit + * matching all characters except s.charAt(0). If limit < start, + * go backward starting from start-1 matching all characters + * except s.charAt(s.length()-1). This method assumes that the + * first character, text.charAt(start), matches s, so it does not + * check it. + * @param text the text to match + * @param start the first character to match. In the forward + * direction, text.charAt(start) is matched against s.charAt(0). + * In the reverse direction, it is matched against + * s.charAt(s.length()-1). + * @param limit the limit offset for matching, either last+1 in + * the forward direction, or last-1 in the reverse direction, + * where last is the index of the last character to match. + * @param s + * @return If part of s matches up to the limit, return |limit - + * start|. If all of s matches before reaching the limit, return + * s.length(). If there is a mismatch between s and text, return + * 0 + */ + static int32_t matchRest(const Replaceable& text, + int32_t start, int32_t limit, + const UnicodeString& s); + + /** + * Returns the smallest value i such that c < list[i]. Caller + * must ensure that c is a legal value or this method will enter + * an infinite loop. This method performs a binary search. + * @param c a character in the range MIN_VALUE..MAX_VALUE + * inclusive + * @return the smallest integer i in the range 0..len-1, + * inclusive, such that c < list[i] + */ + int32_t findCodePoint(UChar32 c) const; + +public: + + /** + * Implementation of UnicodeMatcher API. Union the set of all + * characters that may be matched by this object into the given + * set. + * @param toUnionTo the set into which to union the source characters + * @stable ICU 2.4 + */ + virtual void addMatchSetTo(UnicodeSet& toUnionTo) const override; + + /** + * Returns the index of the given character within this set, where + * the set is ordered by ascending code point. If the character + * is not in this set, return -1. The inverse of this method is + * charAt(). + * @return an index from 0..size()-1, or -1 + * @stable ICU 2.4 + */ + int32_t indexOf(UChar32 c) const; + + /** + * Returns the character at the given index within this set, where + * the set is ordered by ascending code point. If the index is + * out of range for characters, returns (UChar32)-1. + * The inverse of this method is indexOf(). + * + * For iteration, this is slower than UnicodeSetIterator or + * getRangeCount()/getRangeStart()/getRangeEnd(), + * because for each call it skips linearly over index + * characters in the ranges. + * + * @param index an index from 0..size()-1 + * @return the character at the given index, or (UChar32)-1. + * @stable ICU 2.4 + */ + UChar32 charAt(int32_t index) const; + + /** + * Adds the specified range to this set if it is not already + * present. If this set already contains the specified range, + * the call leaves this set unchanged. If start > end + * then an empty range is added, leaving the set unchanged. + * This is equivalent to a boolean logic OR, or a set UNION. + * A frozen set will not be modified. + * + * @param start first character, inclusive, of range to be added + * to this set. + * @param end last character, inclusive, of range to be added + * to this set. + * @stable ICU 2.0 + */ + virtual UnicodeSet& add(UChar32 start, UChar32 end); + + /** + * Adds the specified character to this set if it is not already + * present. If this set already contains the specified character, + * the call leaves this set unchanged. + * A frozen set will not be modified. + * + * @param c the character (code point) + * @return this object, for chaining + * @stable ICU 2.0 + */ + UnicodeSet& add(UChar32 c); + + /** + * Adds the specified multicharacter to this set if it is not already + * present. If this set already contains the multicharacter, + * the call leaves this set unchanged. + * Thus "ch" => {"ch"} + * A frozen set will not be modified. + * + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& add(const UnicodeString& s); + + private: + /** + * @return a code point IF the string consists of a single one. + * otherwise returns -1. + * @param s string to test + */ + static int32_t getSingleCP(const UnicodeString& s); + + void _add(const UnicodeString& s); + + public: + /** + * Adds each of the characters in this string to the set. Note: "ch" => {"c", "h"} + * If this set already contains any particular character, it has no effect on that character. + * A frozen set will not be modified. + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& addAll(const UnicodeString& s); + + /** + * Retains EACH of the characters in this string. Note: "ch" == {"c", "h"} + * A frozen set will not be modified. + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& retainAll(const UnicodeString& s); + + /** + * Complement EACH of the characters in this string. Note: "ch" == {"c", "h"} + * A frozen set will not be modified. + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& complementAll(const UnicodeString& s); + + /** + * Remove EACH of the characters in this string. Note: "ch" == {"c", "h"} + * A frozen set will not be modified. + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& removeAll(const UnicodeString& s); + + /** + * Makes a set from a multicharacter string. Thus "ch" => {"ch"} + * + * @param s the source string + * @return a newly created set containing the given string. + * The caller owns the return object and is responsible for deleting it. + * @stable ICU 2.4 + */ + static UnicodeSet* U_EXPORT2 createFrom(const UnicodeString& s); + + + /** + * Makes a set from each of the characters in the string. Thus "ch" => {"c", "h"} + * @param s the source string + * @return a newly created set containing the given characters + * The caller owns the return object and is responsible for deleting it. + * @stable ICU 2.4 + */ + static UnicodeSet* U_EXPORT2 createFromAll(const UnicodeString& s); + + /** + * Retain only the elements in this set that are contained in the + * specified range. If start > end then an empty range is + * retained, leaving the set empty. This is equivalent to + * a boolean logic AND, or a set INTERSECTION. + * A frozen set will not be modified. + * + * @param start first character, inclusive, of range + * @param end last character, inclusive, of range + * @stable ICU 2.0 + */ + virtual UnicodeSet& retain(UChar32 start, UChar32 end); + + + /** + * Retain the specified character from this set if it is present. + * A frozen set will not be modified. + * + * @param c the character (code point) + * @return this object, for chaining + * @stable ICU 2.0 + */ + UnicodeSet& retain(UChar32 c); + + /** + * Retains only the specified string from this set if it is present. + * Upon return this set will be empty if it did not contain s, or + * will only contain s if it did contain s. + * A frozen set will not be modified. + * + * @param s the source string + * @return this object, for chaining + * @stable ICU 69 + */ + UnicodeSet& retain(const UnicodeString &s); + + /** + * Removes the specified range from this set if it is present. + * The set will not contain the specified range once the call + * returns. If start > end then an empty range is + * removed, leaving the set unchanged. + * A frozen set will not be modified. + * + * @param start first character, inclusive, of range to be removed + * from this set. + * @param end last character, inclusive, of range to be removed + * from this set. + * @stable ICU 2.0 + */ + virtual UnicodeSet& remove(UChar32 start, UChar32 end); + + /** + * Removes the specified character from this set if it is present. + * The set will not contain the specified range once the call + * returns. + * A frozen set will not be modified. + * + * @param c the character (code point) + * @return this object, for chaining + * @stable ICU 2.0 + */ + UnicodeSet& remove(UChar32 c); + + /** + * Removes the specified string from this set if it is present. + * The set will not contain the specified character once the call + * returns. + * A frozen set will not be modified. + * @param s the source string + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& remove(const UnicodeString& s); + + /** + * This is equivalent to + * complement(MIN_VALUE, MAX_VALUE). + * + * Note: This performs a symmetric difference with all code points + * and thus retains all multicharacter strings. + * In order to achieve a “code point complement” (all code points minus this set), + * the easiest is to .complement().removeAllStrings(). + * + * A frozen set will not be modified. + * @stable ICU 2.0 + */ + virtual UnicodeSet& complement(); + + /** + * Complements the specified range in this set. Any character in + * the range will be removed if it is in this set, or will be + * added if it is not in this set. If start > end + * then an empty range is complemented, leaving the set unchanged. + * This is equivalent to a boolean logic XOR. + * A frozen set will not be modified. + * + * @param start first character, inclusive, of range + * @param end last character, inclusive, of range + * @stable ICU 2.0 + */ + virtual UnicodeSet& complement(UChar32 start, UChar32 end); + + /** + * Complements the specified character in this set. The character + * will be removed if it is in this set, or will be added if it is + * not in this set. + * A frozen set will not be modified. + * + * @param c the character (code point) + * @return this object, for chaining + * @stable ICU 2.0 + */ + UnicodeSet& complement(UChar32 c); + + /** + * Complement the specified string in this set. + * The string will be removed if it is in this set, or will be added if it is not in this set. + * A frozen set will not be modified. + * + * @param s the string to complement + * @return this object, for chaining + * @stable ICU 2.4 + */ + UnicodeSet& complement(const UnicodeString& s); + + /** + * Adds all of the elements in the specified set to this set if + * they're not already present. This operation effectively + * modifies this set so that its value is the union of the two + * sets. The behavior of this operation is unspecified if the specified + * collection is modified while the operation is in progress. + * A frozen set will not be modified. + * + * @param c set whose elements are to be added to this set. + * @see #add(UChar32, UChar32) + * @stable ICU 2.0 + */ + virtual UnicodeSet& addAll(const UnicodeSet& c); + + /** + * Retains only the elements in this set that are contained in the + * specified set. In other words, removes from this set all of + * its elements that are not contained in the specified set. This + * operation effectively modifies this set so that its value is + * the intersection of the two sets. + * A frozen set will not be modified. + * + * @param c set that defines which elements this set will retain. + * @stable ICU 2.0 + */ + virtual UnicodeSet& retainAll(const UnicodeSet& c); + + /** + * Removes from this set all of its elements that are contained in the + * specified set. This operation effectively modifies this + * set so that its value is the asymmetric set difference of + * the two sets. + * A frozen set will not be modified. + * + * @param c set that defines which elements will be removed from + * this set. + * @stable ICU 2.0 + */ + virtual UnicodeSet& removeAll(const UnicodeSet& c); + + /** + * Complements in this set all elements contained in the specified + * set. Any character in the other set will be removed if it is + * in this set, or will be added if it is not in this set. + * A frozen set will not be modified. + * + * @param c set that defines which elements will be xor'ed from + * this set. + * @stable ICU 2.4 + */ + virtual UnicodeSet& complementAll(const UnicodeSet& c); + + /** + * Removes all of the elements from this set. This set will be + * empty after this call returns. + * A frozen set will not be modified. + * @stable ICU 2.0 + */ + virtual UnicodeSet& clear(void); + + /** + * Close this set over the given attribute. For the attribute + * USET_CASE_INSENSITIVE, the result is to modify this set so that: + * + * 1. For each character or string 'a' in this set, all strings or + * characters 'b' such that foldCase(a) == foldCase(b) are added + * to this set. + * + * 2. For each string 'e' in the resulting set, if e != + * foldCase(e), 'e' will be removed. + * + * Example: [aq\\u00DF{Bc}{bC}{Fi}] => [aAqQ\\u00DF\\uFB01{ss}{bc}{fi}] + * + * (Here foldCase(x) refers to the operation u_strFoldCase, and a + * == b denotes that the contents are the same, not pointer + * comparison.) + * + * A frozen set will not be modified. + * + * @param attribute bitmask for attributes to close over. + * Valid options: + * At most one of USET_CASE_INSENSITIVE, USET_ADD_CASE_MAPPINGS, USET_SIMPLE_CASE_INSENSITIVE. + * These case options are mutually exclusive. + * Unrelated options bits are ignored. + * @return a reference to this set. + * @stable ICU 4.2 + */ + UnicodeSet& closeOver(int32_t attribute); + + /** + * Remove all strings from this set. + * + * @return a reference to this set. + * @stable ICU 4.2 + */ + virtual UnicodeSet &removeAllStrings(); + + /** + * Iteration method that returns the number of ranges contained in + * this set. + * @see #getRangeStart + * @see #getRangeEnd + * @stable ICU 2.4 + */ + virtual int32_t getRangeCount(void) const; + + /** + * Iteration method that returns the first character in the + * specified range of this set. + * @see #getRangeCount + * @see #getRangeEnd + * @stable ICU 2.4 + */ + virtual UChar32 getRangeStart(int32_t index) const; + + /** + * Iteration method that returns the last character in the + * specified range of this set. + * @see #getRangeStart + * @see #getRangeEnd + * @stable ICU 2.4 + */ + virtual UChar32 getRangeEnd(int32_t index) const; + + /** + * Serializes this set into an array of 16-bit integers. Serialization + * (currently) only records the characters in the set; multicharacter + * strings are ignored. + * + * The array has following format (each line is one 16-bit + * integer): + * + * length = (n+2*m) | (m!=0?0x8000:0) + * bmpLength = n; present if m!=0 + * bmp[0] + * bmp[1] + * ... + * bmp[n-1] + * supp-high[0] + * supp-low[0] + * supp-high[1] + * supp-low[1] + * ... + * supp-high[m-1] + * supp-low[m-1] + * + * The array starts with a header. After the header are n bmp + * code points, then m supplementary code points. Either n or m + * or both may be zero. n+2*m is always <= 0x7FFF. + * + * If there are no supplementary characters (if m==0) then the + * header is one 16-bit integer, 'length', with value n. + * + * If there are supplementary characters (if m!=0) then the header + * is two 16-bit integers. The first, 'length', has value + * (n+2*m)|0x8000. The second, 'bmpLength', has value n. + * + * After the header the code points are stored in ascending order. + * Supplementary code points are stored as most significant 16 + * bits followed by least significant 16 bits. + * + * @param dest pointer to buffer of destCapacity 16-bit integers. + * May be nullptr only if destCapacity is zero. + * @param destCapacity size of dest, or zero. Must not be negative. + * @param ec error code. Will be set to U_INDEX_OUTOFBOUNDS_ERROR + * if n+2*m > 0x7FFF. Will be set to U_BUFFER_OVERFLOW_ERROR if + * n+2*m+(m!=0?2:1) > destCapacity. + * @return the total length of the serialized format, including + * the header, that is, n+2*m+(m!=0?2:1), or 0 on error other + * than U_BUFFER_OVERFLOW_ERROR. + * @stable ICU 2.4 + */ + int32_t serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& ec) const; + + /** + * Reallocate this objects internal structures to take up the least + * possible space, without changing this object's value. + * A frozen set will not be modified. + * @stable ICU 2.4 + */ + virtual UnicodeSet& compact(); + + /** + * Return the class ID for this class. This is useful only for + * comparing to a return value from getDynamicClassID(). For example: + *

+     * .      Base* polymorphic_pointer = createPolymorphicObject();
+     * .      if (polymorphic_pointer->getDynamicClassID() ==
+     * .          Derived::getStaticClassID()) ...
+     * 
+ * @return The class ID for all objects of this class. + * @stable ICU 2.0 + */ + static UClassID U_EXPORT2 getStaticClassID(void); + + /** + * Implement UnicodeFunctor API. + * + * @return The class ID for this object. All objects of a given + * class have the same class ID. Objects of other classes have + * different class IDs. + * @stable ICU 2.4 + */ + virtual UClassID getDynamicClassID(void) const override; + +private: + + // Private API for the USet API + + friend class USetAccess; + + const UnicodeString* getString(int32_t index) const; + + //---------------------------------------------------------------- + // RuleBasedTransliterator support + //---------------------------------------------------------------- + +private: + + /** + * Returns true if this set contains any character whose low byte + * is the given value. This is used by RuleBasedTransliterator for + * indexing. + */ + virtual UBool matchesIndexValue(uint8_t v) const override; + +private: + friend class RBBIRuleScanner; + + //---------------------------------------------------------------- + // Implementation: Clone as thawed (see ICU4J Freezable) + //---------------------------------------------------------------- + + UnicodeSet(const UnicodeSet& o, UBool /* asThawed */); + UnicodeSet& copyFrom(const UnicodeSet& o, UBool asThawed); + + //---------------------------------------------------------------- + // Implementation: Pattern parsing + //---------------------------------------------------------------- + + void applyPatternIgnoreSpace(const UnicodeString& pattern, + ParsePosition& pos, + const SymbolTable* symbols, + UErrorCode& status); + + void applyPattern(RuleCharacterIterator& chars, + const SymbolTable* symbols, + UnicodeString& rebuiltPat, + uint32_t options, + UnicodeSet& (UnicodeSet::*caseClosure)(int32_t attribute), + int32_t depth, + UErrorCode& ec); + + void closeOverCaseInsensitive(bool simple); + void closeOverAddCaseMappings(); + + //---------------------------------------------------------------- + // Implementation: Utility methods + //---------------------------------------------------------------- + + static int32_t nextCapacity(int32_t minCapacity); + + bool ensureCapacity(int32_t newLen); + + bool ensureBufferCapacity(int32_t newLen); + + void swapBuffers(void); + + UBool allocateStrings(UErrorCode &status); + int32_t stringsSize() const; + UBool stringsContains(const UnicodeString &s) const; + + UnicodeString& _toPattern(UnicodeString& result, + UBool escapeUnprintable) const; + + UnicodeString& _generatePattern(UnicodeString& result, + UBool escapeUnprintable) const; + + static void _appendToPat(UnicodeString& buf, const UnicodeString& s, UBool escapeUnprintable); + + static void _appendToPat(UnicodeString& buf, UChar32 c, UBool escapeUnprintable); + + static void _appendToPat(UnicodeString &result, UChar32 start, UChar32 end, + UBool escapeUnprintable); + + //---------------------------------------------------------------- + // Implementation: Fundamental operators + //---------------------------------------------------------------- + + void exclusiveOr(const UChar32* other, int32_t otherLen, int8_t polarity); + + void add(const UChar32* other, int32_t otherLen, int8_t polarity); + + void retain(const UChar32* other, int32_t otherLen, int8_t polarity); + + /** + * Return true if the given position, in the given pattern, appears + * to be the start of a property set pattern [:foo:], \\p{foo}, or + * \\P{foo}, or \\N{name}. + */ + static UBool resemblesPropertyPattern(const UnicodeString& pattern, + int32_t pos); + + static UBool resemblesPropertyPattern(RuleCharacterIterator& chars, + int32_t iterOpts); + + /** + * Parse the given property pattern at the given parse position + * and set this UnicodeSet to the result. + * + * The original design document is out of date, but still useful. + * Ignore the property and value names: + * https://htmlpreview.github.io/?https://github.com/unicode-org/icu-docs/blob/main/design/unicodeset_properties.html + * + * Recognized syntax: + * + * [:foo:] [:^foo:] - white space not allowed within "[:" or ":]" + * \\p{foo} \\P{foo} - white space not allowed within "\\p" or "\\P" + * \\N{name} - white space not allowed within "\\N" + * + * Other than the above restrictions, Unicode Pattern_White_Space characters are ignored. + * Case is ignored except in "\\p" and "\\P" and "\\N". In 'name' leading + * and trailing space is deleted, and internal runs of whitespace + * are collapsed to a single space. + * + * We support binary properties, enumerated properties, and the + * following non-enumerated properties: + * + * Numeric_Value + * Name + * Unicode_1_Name + * + * @param pattern the pattern string + * @param ppos on entry, the position at which to begin parsing. + * This should be one of the locations marked '^': + * + * [:blah:] \\p{blah} \\P{blah} \\N{name} + * ^ % ^ % ^ % ^ % + * + * On return, the position after the last character parsed, that is, + * the locations marked '%'. If the parse fails, ppos is returned + * unchanged. + * @param ec status + * @return a reference to this. + */ + UnicodeSet& applyPropertyPattern(const UnicodeString& pattern, + ParsePosition& ppos, + UErrorCode &ec); + + void applyPropertyPattern(RuleCharacterIterator& chars, + UnicodeString& rebuiltPat, + UErrorCode& ec); + + /** + * A filter that returns true if the given code point should be + * included in the UnicodeSet being constructed. + */ + typedef UBool (*Filter)(UChar32 codePoint, void* context); + + /** + * Given a filter, set this UnicodeSet to the code points + * contained by that filter. The filter MUST be + * property-conformant. That is, if it returns value v for one + * code point, then it must return v for all affiliated code + * points, as defined by the inclusions list. See + * getInclusions(). + * src is a UPropertySource value. + */ + void applyFilter(Filter filter, + void* context, + const UnicodeSet* inclusions, + UErrorCode &status); + + /** + * Set the new pattern to cache. + */ + void setPattern(const UnicodeString& newPat) { + setPattern(newPat.getBuffer(), newPat.length()); + } + void setPattern(const char16_t *newPat, int32_t newPatLen); + /** + * Release existing cached pattern. + */ + void releasePattern(); + + friend class UnicodeSetIterator; +}; + + + +inline bool UnicodeSet::operator!=(const UnicodeSet& o) const { + return !operator==(o); +} + +inline UBool UnicodeSet::isFrozen() const { + return (UBool)(bmpSet!=nullptr || stringSpan!=nullptr); +} + +inline UBool UnicodeSet::containsSome(UChar32 start, UChar32 end) const { + return !containsNone(start, end); +} + +inline UBool UnicodeSet::containsSome(const UnicodeSet& s) const { + return !containsNone(s); +} + +inline UBool UnicodeSet::containsSome(const UnicodeString& s) const { + return !containsNone(s); +} + +inline UBool UnicodeSet::isBogus() const { + return (UBool)(fFlags & kIsBogus); +} + +inline UnicodeSet *UnicodeSet::fromUSet(USet *uset) { + return reinterpret_cast(uset); +} + +inline const UnicodeSet *UnicodeSet::fromUSet(const USet *uset) { + return reinterpret_cast(uset); +} + +inline USet *UnicodeSet::toUSet() { + return reinterpret_cast(this); +} + +inline const USet *UnicodeSet::toUSet() const { + return reinterpret_cast(this); +} + +inline int32_t UnicodeSet::span(const UnicodeString &s, int32_t start, USetSpanCondition spanCondition) const { + int32_t sLength=s.length(); + if(start<0) { + start=0; + } else if(start>sLength) { + start=sLength; + } + return start+span(s.getBuffer()+start, sLength-start, spanCondition); +} + +inline int32_t UnicodeSet::spanBack(const UnicodeString &s, int32_t limit, USetSpanCondition spanCondition) const { + int32_t sLength=s.length(); + if(limit<0) { + limit=0; + } else if(limit>sLength) { + limit=sLength; + } + return spanBack(s.getBuffer(), limit, spanCondition); +} + +U_NAMESPACE_END + +#endif /* U_SHOW_CPLUSPLUS_API */ + +#endif