From 0178a07a26fa7dd827a49048104b4089aa7e2b84 Mon Sep 17 00:00:00 2001 From: Fredrik Roubert Date: Wed, 3 Jul 2024 16:46:57 +0200 Subject: [PATCH] ICU-22793 Clang-Tidy: google-readability-casting https://releases.llvm.org/17.0.1/tools/clang/tools/extra/docs/clang-tidy/checks/google/readability-casting.html --- icu4c/source/common/appendable.cpp | 2 +- icu4c/source/common/bmpset.cpp | 56 +- icu4c/source/common/bmpset.h | 2 +- icu4c/source/common/brkeng.cpp | 18 +- icu4c/source/common/brkiter.cpp | 4 +- icu4c/source/common/bytesinkutil.cpp | 10 +- icu4c/source/common/bytesinkutil.h | 2 +- icu4c/source/common/bytestrie.cpp | 6 +- icu4c/source/common/bytestriebuilder.cpp | 62 +-- icu4c/source/common/bytestrieiterator.cpp | 14 +- icu4c/source/common/caniter.cpp | 22 +- icu4c/source/common/characterproperties.cpp | 10 +- icu4c/source/common/cstring.cpp | 4 +- icu4c/source/common/dictbe.cpp | 96 ++-- icu4c/source/common/dictionarydata.cpp | 10 +- icu4c/source/common/edits.cpp | 22 +- icu4c/source/common/emojiprops.cpp | 6 +- icu4c/source/common/filteredbrk.cpp | 6 +- icu4c/source/common/loadednormalizer2impl.cpp | 12 +- icu4c/source/common/localematcher.cpp | 2 +- icu4c/source/common/locbased.h | 2 +- icu4c/source/common/locdispnames.cpp | 2 +- icu4c/source/common/locdspnm.cpp | 31 +- icu4c/source/common/locid.cpp | 73 +-- icu4c/source/common/loclikely.cpp | 16 +- icu4c/source/common/loclikelysubtags.cpp | 6 +- icu4c/source/common/locmap.cpp | 2 +- icu4c/source/common/locutil.cpp | 4 +- icu4c/source/common/lstmbe.cpp | 10 +- icu4c/source/common/messagepattern.cpp | 16 +- icu4c/source/common/mlbe.cpp | 2 +- icu4c/source/common/norm2allmodes.h | 2 +- icu4c/source/common/normalizer2.cpp | 4 +- icu4c/source/common/normalizer2impl.cpp | 130 ++--- icu4c/source/common/normalizer2impl.h | 38 +- icu4c/source/common/patternprops.cpp | 10 +- icu4c/source/common/propname.cpp | 6 +- icu4c/source/common/propsvec.cpp | 22 +- icu4c/source/common/punycode.cpp | 8 +- icu4c/source/common/putil.cpp | 10 +- icu4c/source/common/putilimp.h | 2 +- icu4c/source/common/rbbi.cpp | 20 +- icu4c/source/common/rbbi_cache.cpp | 4 +- icu4c/source/common/rbbidata.cpp | 6 +- icu4c/source/common/rbbirb.cpp | 14 +- icu4c/source/common/rbbiscan.cpp | 18 +- icu4c/source/common/rbbisetb.cpp | 12 +- icu4c/source/common/rbbistbl.cpp | 12 +- icu4c/source/common/rbbitblb.cpp | 78 +-- icu4c/source/common/resbund_cnv.cpp | 2 +- icu4c/source/common/ruleiter.cpp | 2 +- icu4c/source/common/serv.cpp | 32 +- icu4c/source/common/servlkf.cpp | 2 +- icu4c/source/common/servls.cpp | 6 +- icu4c/source/common/servnotf.cpp | 6 +- icu4c/source/common/servrbf.cpp | 4 +- icu4c/source/common/simpleformatter.cpp | 10 +- icu4c/source/common/stringtriebuilder.cpp | 8 +- icu4c/source/common/ubidi.cpp | 74 +-- icu4c/source/common/ubidi_props.cpp | 2 +- icu4c/source/common/ubiditransform.cpp | 2 +- icu4c/source/common/ucase.cpp | 2 +- icu4c/source/common/ucasemap.cpp | 26 +- .../common/ucasemap_titlecase_brkiter.cpp | 2 +- icu4c/source/common/uchar.cpp | 8 +- icu4c/source/common/ucharstrie.cpp | 4 +- icu4c/source/common/ucharstriebuilder.cpp | 40 +- icu4c/source/common/ucharstrieiterator.cpp | 10 +- icu4c/source/common/uchriter.cpp | 4 +- icu4c/source/common/ucmndata.cpp | 6 +- icu4c/source/common/ucnv.cpp | 32 +- icu4c/source/common/ucnv2022.cpp | 357 ++++++------ icu4c/source/common/ucnv_bld.cpp | 26 +- icu4c/source/common/ucnv_ct.cpp | 2 +- icu4c/source/common/ucnv_ext.cpp | 32 +- icu4c/source/common/ucnv_io.cpp | 25 +- icu4c/source/common/ucnv_lmb.cpp | 2 +- icu4c/source/common/ucnv_u16.cpp | 8 +- icu4c/source/common/ucnv_u8.cpp | 8 +- icu4c/source/common/ucnvbocu.cpp | 180 +++--- icu4c/source/common/ucnvhz.cpp | 4 +- icu4c/source/common/ucnvisci.cpp | 6 +- icu4c/source/common/ucnvlat1.cpp | 2 +- icu4c/source/common/ucnvmbcs.cpp | 384 ++++++------- icu4c/source/common/ucnvscsu.cpp | 36 +- icu4c/source/common/ucnvsel.cpp | 8 +- icu4c/source/common/ucol_swp.cpp | 22 +- icu4c/source/common/ucptrie.cpp | 8 +- icu4c/source/common/ucurr.cpp | 34 +- icu4c/source/common/udata.cpp | 24 +- icu4c/source/common/udataswp.cpp | 24 +- icu4c/source/common/uenum.cpp | 8 +- icu4c/source/common/uhash.cpp | 10 +- icu4c/source/common/uidna.cpp | 30 +- icu4c/source/common/uloc.cpp | 22 +- icu4c/source/common/uloc_keytype.cpp | 12 +- icu4c/source/common/uloc_tag.cpp | 76 +-- icu4c/source/common/ulocbuilder.cpp | 2 +- icu4c/source/common/umutablecptrie.cpp | 48 +- icu4c/source/common/unames.cpp | 158 +++--- icu4c/source/common/unicode/brkiter.h | 2 +- icu4c/source/common/unicode/bytestream.h | 2 +- icu4c/source/common/unicode/bytestrie.h | 4 +- icu4c/source/common/unicode/edits.h | 2 +- icu4c/source/common/unicode/messagepattern.h | 2 +- icu4c/source/common/unicode/simpleformatter.h | 2 +- .../source/common/unicode/stringtriebuilder.h | 4 +- icu4c/source/common/unicode/ucharstrie.h | 4 +- icu4c/source/common/unicode/uniset.h | 4 +- icu4c/source/common/unicode/unistr.h | 24 +- icu4c/source/common/unicode/utypes.h | 4 +- icu4c/source/common/unifiedcache.cpp | 23 +- icu4c/source/common/uniset.cpp | 82 ++- icu4c/source/common/uniset_closure.cpp | 12 +- icu4c/source/common/uniset_props.cpp | 30 +- icu4c/source/common/unisetspan.cpp | 68 +-- icu4c/source/common/unisetspan.h | 4 +- icu4c/source/common/unistr.cpp | 78 +-- icu4c/source/common/unistr_case.cpp | 4 +- icu4c/source/common/unistr_cnv.cpp | 22 +- icu4c/source/common/unormcmp.cpp | 8 +- icu4c/source/common/uprops.cpp | 44 +- icu4c/source/common/uresbund.cpp | 58 +- icu4c/source/common/uresdata.cpp | 72 +-- icu4c/source/common/uscript.cpp | 2 +- icu4c/source/common/usetiter.cpp | 12 +- icu4c/source/common/ushape.cpp | 30 +- icu4c/source/common/usprep.cpp | 28 +- .../source/common/ustr_titlecase_brkiter.cpp | 2 +- icu4c/source/common/ustrcase.cpp | 12 +- icu4c/source/common/ustrenum.cpp | 6 +- icu4c/source/common/ustring.cpp | 4 +- icu4c/source/common/ustrtrns.cpp | 20 +- icu4c/source/common/utext.cpp | 2 +- icu4c/source/common/util.cpp | 8 +- icu4c/source/common/util_props.cpp | 2 +- icu4c/source/common/utrace.cpp | 6 +- icu4c/source/common/utrie.cpp | 4 +- icu4c/source/common/utrie2.cpp | 2 +- icu4c/source/common/utrie2_builder.cpp | 16 +- icu4c/source/common/utrie_swap.cpp | 2 +- icu4c/source/common/uts46.cpp | 10 +- icu4c/source/common/uvector.cpp | 8 +- icu4c/source/common/uvectr32.cpp | 12 +- icu4c/source/common/uvectr64.cpp | 12 +- icu4c/source/extra/uconv/uconv.cpp | 70 +-- icu4c/source/i18n/alphaindex.cpp | 18 +- icu4c/source/i18n/anytrans.cpp | 8 +- icu4c/source/i18n/astro.cpp | 2 +- icu4c/source/i18n/basictz.cpp | 8 +- icu4c/source/i18n/bocsu.cpp | 34 +- icu4c/source/i18n/calendar.cpp | 73 +-- icu4c/source/i18n/chnsecal.cpp | 30 +- icu4c/source/i18n/choicfmt.cpp | 4 +- icu4c/source/i18n/coleitr.cpp | 18 +- icu4c/source/i18n/coll.cpp | 14 +- icu4c/source/i18n/collation.cpp | 40 +- icu4c/source/i18n/collation.h | 20 +- icu4c/source/i18n/collationbuilder.cpp | 24 +- icu4c/source/i18n/collationbuilder.h | 36 +- icu4c/source/i18n/collationcompare.cpp | 44 +- icu4c/source/i18n/collationdata.cpp | 12 +- icu4c/source/i18n/collationdata.h | 2 +- icu4c/source/i18n/collationdatabuilder.cpp | 46 +- icu4c/source/i18n/collationdatawriter.cpp | 10 +- icu4c/source/i18n/collationfastlatin.cpp | 12 +- .../source/i18n/collationfastlatinbuilder.cpp | 72 +-- icu4c/source/i18n/collationfastlatinbuilder.h | 2 +- icu4c/source/i18n/collationfcd.h | 6 +- icu4c/source/i18n/collationiterator.cpp | 10 +- icu4c/source/i18n/collationiterator.h | 6 +- icu4c/source/i18n/collationkeys.cpp | 31 +- icu4c/source/i18n/collationkeys.h | 2 +- icu4c/source/i18n/collationrootelements.cpp | 24 +- icu4c/source/i18n/collationruleparser.cpp | 16 +- icu4c/source/i18n/collationsets.cpp | 22 +- icu4c/source/i18n/collationsettings.cpp | 8 +- icu4c/source/i18n/collationsettings.h | 4 +- icu4c/source/i18n/collationtailoring.cpp | 2 +- icu4c/source/i18n/collationweights.cpp | 26 +- icu4c/source/i18n/collationweights.h | 2 +- icu4c/source/i18n/cpdtrans.cpp | 8 +- icu4c/source/i18n/csdetect.cpp | 8 +- icu4c/source/i18n/csmatch.cpp | 2 +- icu4c/source/i18n/csr2022.cpp | 2 +- icu4c/source/i18n/csrmbcs.cpp | 4 +- icu4c/source/i18n/csrsbcs.cpp | 4 +- icu4c/source/i18n/currpinf.cpp | 10 +- icu4c/source/i18n/dangical.cpp | 6 +- icu4c/source/i18n/datefmt.cpp | 20 +- icu4c/source/i18n/dcfmtsym.cpp | 82 +-- icu4c/source/i18n/decNumber.cpp | 150 ++--- icu4c/source/i18n/decimfmt.cpp | 12 +- .../double-conversion-string-to-double.cpp | 2 +- icu4c/source/i18n/dtfmtsym.cpp | 124 ++--- icu4c/source/i18n/dtitvfmt.cpp | 20 +- icu4c/source/i18n/dtitvinf.cpp | 18 +- icu4c/source/i18n/dtptngen.cpp | 56 +- icu4c/source/i18n/erarules.cpp | 6 +- icu4c/source/i18n/fmtable.cpp | 16 +- .../source/i18n/formatted_string_builder.cpp | 2 +- icu4c/source/i18n/gender.cpp | 4 +- icu4c/source/i18n/gregocal.cpp | 30 +- icu4c/source/i18n/gregoimp.cpp | 6 +- icu4c/source/i18n/gregoimp.h | 4 +- icu4c/source/i18n/hebrwcal.cpp | 12 +- icu4c/source/i18n/indiancal.cpp | 6 +- icu4c/source/i18n/inputext.cpp | 10 +- icu4c/source/i18n/islamcal.cpp | 12 +- icu4c/source/i18n/messageformat2.cpp | 4 +- .../i18n/messageformat2_function_registry.cpp | 2 +- icu4c/source/i18n/messageformat2_parser.cpp | 8 +- .../source/i18n/messageformat2_serializer.cpp | 6 +- icu4c/source/i18n/msgfmt.cpp | 32 +- icu4c/source/i18n/name2uni.cpp | 4 +- icu4c/source/i18n/nfrlist.h | 4 +- icu4c/source/i18n/nfrs.cpp | 20 +- icu4c/source/i18n/nfrule.cpp | 17 +- icu4c/source/i18n/nfrule.h | 4 +- icu4c/source/i18n/nfsubs.cpp | 28 +- icu4c/source/i18n/nortrans.cpp | 4 +- icu4c/source/i18n/number_decimalquantity.cpp | 4 +- icu4c/source/i18n/number_grouping.cpp | 2 +- icu4c/source/i18n/number_usageprefs.cpp | 4 +- icu4c/source/i18n/numfmt.cpp | 18 +- icu4c/source/i18n/numsys.cpp | 4 +- icu4c/source/i18n/olsontz.cpp | 46 +- icu4c/source/i18n/olsontz.h | 2 +- icu4c/source/i18n/plurfmt.cpp | 4 +- icu4c/source/i18n/plurrule.cpp | 18 +- icu4c/source/i18n/plurrule_impl.h | 122 ++--- icu4c/source/i18n/quant.cpp | 12 +- icu4c/source/i18n/quantityformatter.cpp | 2 +- icu4c/source/i18n/rbnf.cpp | 30 +- icu4c/source/i18n/rbt.cpp | 4 +- icu4c/source/i18n/rbt_data.cpp | 6 +- icu4c/source/i18n/rbt_pars.cpp | 58 +- icu4c/source/i18n/rbt_rule.cpp | 14 +- icu4c/source/i18n/rbt_set.cpp | 22 +- icu4c/source/i18n/rbtz.cpp | 58 +- icu4c/source/i18n/regexcmp.cpp | 182 +++---- icu4c/source/i18n/regeximp.cpp | 4 +- icu4c/source/i18n/region.cpp | 48 +- icu4c/source/i18n/reldatefmt.cpp | 3 +- icu4c/source/i18n/reldtfmt.cpp | 18 +- icu4c/source/i18n/rematch.cpp | 458 ++++++++-------- icu4c/source/i18n/repattrn.cpp | 8 +- icu4c/source/i18n/rulebasedcollator.cpp | 34 +- icu4c/source/i18n/scriptset.cpp | 14 +- icu4c/source/i18n/search.cpp | 14 +- icu4c/source/i18n/simpletz.cpp | 48 +- icu4c/source/i18n/smpdtfmt.cpp | 34 +- icu4c/source/i18n/strmatch.cpp | 6 +- icu4c/source/i18n/strrepl.cpp | 14 +- icu4c/source/i18n/stsearch.cpp | 10 +- icu4c/source/i18n/timezone.cpp | 50 +- icu4c/source/i18n/titletrn.cpp | 2 +- icu4c/source/i18n/tmutfmt.cpp | 46 +- icu4c/source/i18n/translit.cpp | 24 +- icu4c/source/i18n/transreg.cpp | 52 +- icu4c/source/i18n/tridpars.cpp | 10 +- icu4c/source/i18n/tzfmt.cpp | 32 +- icu4c/source/i18n/tzgnames.cpp | 34 +- icu4c/source/i18n/tznames.cpp | 22 +- icu4c/source/i18n/tznames_impl.cpp | 68 +-- icu4c/source/i18n/tznames_impl.h | 6 +- icu4c/source/i18n/tzrule.cpp | 4 +- icu4c/source/i18n/ucal.cpp | 2 +- icu4c/source/i18n/ucol_res.cpp | 2 +- icu4c/source/i18n/ucol_sit.cpp | 6 +- icu4c/source/i18n/ucoleitr.cpp | 4 +- icu4c/source/i18n/uitercollationiterator.cpp | 12 +- icu4c/source/i18n/umsg.cpp | 2 +- icu4c/source/i18n/unesctrn.cpp | 4 +- icu4c/source/i18n/uni2name.cpp | 2 +- icu4c/source/i18n/unicode/calendar.h | 4 +- icu4c/source/i18n/unicode/coleitr.h | 2 +- icu4c/source/i18n/unicode/dcfmtsym.h | 2 +- icu4c/source/i18n/unicode/fmtable.h | 2 +- .../i18n/unicode/messageformat2_arguments.h | 2 +- icu4c/source/i18n/unicode/sortkey.h | 2 +- icu4c/source/i18n/unicode/tblcoll.h | 6 +- icu4c/source/i18n/unicode/translit.h | 2 +- icu4c/source/i18n/units_converter.cpp | 11 +- icu4c/source/i18n/unum.cpp | 4 +- icu4c/source/i18n/uregex.cpp | 20 +- icu4c/source/i18n/usearch.cpp | 26 +- icu4c/source/i18n/uspoof_conf.cpp | 10 +- icu4c/source/i18n/uspoof_impl.cpp | 18 +- icu4c/source/i18n/utf16collationiterator.cpp | 18 +- icu4c/source/i18n/utf8collationiterator.cpp | 8 +- icu4c/source/i18n/vtzone.cpp | 52 +- icu4c/source/i18n/zonemeta.cpp | 46 +- icu4c/source/io/sprintf.cpp | 6 +- icu4c/source/io/sscanf.cpp | 2 +- icu4c/source/io/ufile.cpp | 2 +- icu4c/source/io/ufmt_cmn.cpp | 22 +- icu4c/source/io/uprintf.cpp | 4 +- icu4c/source/io/uprntf_p.cpp | 77 +-- icu4c/source/io/uscanf_p.cpp | 116 ++-- icu4c/source/io/ustdio.cpp | 14 +- icu4c/source/io/ustream.cpp | 2 +- icu4c/source/layoutex/ParagraphLayout.cpp | 32 +- icu4c/source/layoutex/RunArrays.cpp | 20 +- icu4c/source/layoutex/plruns.cpp | 6 +- icu4c/source/samples/coll/coll.cpp | 6 +- icu4c/source/samples/strsrch/strsrch.cpp | 6 +- .../samples/translit/answers/unaccent.cpp | 4 +- icu4c/source/samples/translit/unaccent.cpp | 4 +- icu4c/source/samples/ugrep/ugrep.cpp | 4 +- icu4c/source/test/fuzzer/fuzzer_driver.cpp | 2 +- icu4c/source/test/intltest/alphaindextst.cpp | 52 +- icu4c/source/test/intltest/apicoll.cpp | 86 +-- icu4c/source/test/intltest/astrotst.cpp | 41 +- icu4c/source/test/intltest/bidiconf.cpp | 66 +-- icu4c/source/test/intltest/bytestrietest.cpp | 42 +- icu4c/source/test/intltest/calcasts.cpp | 10 +- icu4c/source/test/intltest/callimts.cpp | 50 +- icu4c/source/test/intltest/calregts.cpp | 102 ++-- icu4c/source/test/intltest/caltest.cpp | 140 ++--- icu4c/source/test/intltest/canittst.cpp | 4 +- icu4c/source/test/intltest/citrtest.cpp | 52 +- icu4c/source/test/intltest/collationtest.cpp | 156 +++--- icu4c/source/test/intltest/colldata.cpp | 6 +- .../intltest/compactdecimalformattest.cpp | 18 +- icu4c/source/test/intltest/convtest.cpp | 124 ++--- icu4c/source/test/intltest/cpdtrtst.cpp | 8 +- icu4c/source/test/intltest/dadrcal.cpp | 30 +- icu4c/source/test/intltest/dadrfmt.cpp | 16 +- .../datadrivennumberformattestsuite.cpp | 7 +- icu4c/source/test/intltest/dcfmapts.cpp | 206 +++---- icu4c/source/test/intltest/dtfmapts.cpp | 20 +- icu4c/source/test/intltest/dtfmrgts.cpp | 153 +++--- icu4c/source/test/intltest/dtfmtrtts.cpp | 28 +- icu4c/source/test/intltest/dtfmtrtts.h | 6 +- icu4c/source/test/intltest/dtfmttst.cpp | 266 ++++----- icu4c/source/test/intltest/dtifmtts.cpp | 24 +- icu4c/source/test/intltest/dtptngts.cpp | 20 +- icu4c/source/test/intltest/encoll.cpp | 212 ++++---- icu4c/source/test/intltest/fldset.cpp | 26 +- .../formatted_string_builder_test.cpp | 2 +- .../test/intltest/formattedvaluetest.cpp | 6 +- icu4c/source/test/intltest/icusvtst.cpp | 4 +- icu4c/source/test/intltest/idnaconf.cpp | 6 +- icu4c/source/test/intltest/idnaref.cpp | 24 +- icu4c/source/test/intltest/incaltst.cpp | 50 +- icu4c/source/test/intltest/intltest.cpp | 136 ++--- icu4c/source/test/intltest/intltest.h | 2 +- icu4c/source/test/intltest/itercoll.cpp | 18 +- icu4c/source/test/intltest/itformat.cpp | 28 +- icu4c/source/test/intltest/itrbnf.cpp | 22 +- icu4c/source/test/intltest/itrbnfp.cpp | 12 +- icu4c/source/test/intltest/itrbnfrt.cpp | 4 +- icu4c/source/test/intltest/itspoof.cpp | 6 +- icu4c/source/test/intltest/itutil.cpp | 20 +- icu4c/source/test/intltest/jamotest.cpp | 8 +- .../test/intltest/listformattertest.cpp | 4 +- .../test/intltest/localematchertest.cpp | 10 +- icu4c/source/test/intltest/locnmtst.cpp | 4 +- icu4c/source/test/intltest/loctest.cpp | 56 +- icu4c/source/test/intltest/measfmttest.cpp | 76 +-- .../test/intltest/messageformat2test.cpp | 2 +- .../intltest/messageformat2test_custom.cpp | 14 +- icu4c/source/test/intltest/miscdtfm.cpp | 2 +- icu4c/source/test/intltest/mnkytst.cpp | 14 +- icu4c/source/test/intltest/msfmrgts.cpp | 56 +- icu4c/source/test/intltest/nmfmapts.cpp | 32 +- icu4c/source/test/intltest/nmfmtrt.cpp | 12 +- icu4c/source/test/intltest/nmfmtrt.h | 2 +- icu4c/source/test/intltest/normconf.cpp | 24 +- icu4c/source/test/intltest/nptrans.cpp | 2 +- .../test/intltest/numberformattesttuple.cpp | 14 +- .../intltest/numbertest_decimalquantity.cpp | 2 +- icu4c/source/test/intltest/numfmtst.cpp | 486 ++++++++--------- icu4c/source/test/intltest/numfmtst.h | 2 +- icu4c/source/test/intltest/numrgts.cpp | 78 +-- icu4c/source/test/intltest/pluralmaptest.cpp | 32 +- icu4c/source/test/intltest/plurfmts.cpp | 24 +- icu4c/source/test/intltest/plurults.cpp | 6 +- .../test/intltest/quantityformattertest.cpp | 4 +- icu4c/source/test/intltest/rbbiapts.cpp | 56 +- icu4c/source/test/intltest/rbbimonkeytest.cpp | 18 +- icu4c/source/test/intltest/rbbitst.cpp | 40 +- icu4c/source/test/intltest/regcoll.cpp | 26 +- icu4c/source/test/intltest/regextst.cpp | 80 +-- icu4c/source/test/intltest/regiontst.cpp | 2 +- icu4c/source/test/intltest/reldatefmttest.cpp | 4 +- icu4c/source/test/intltest/reptest.cpp | 2 +- icu4c/source/test/intltest/restest.cpp | 18 +- icu4c/source/test/intltest/restsnew.cpp | 24 +- icu4c/source/test/intltest/sdtfmtts.cpp | 6 +- icu4c/source/test/intltest/sfwdchit.cpp | 2 +- .../test/intltest/simpleformattertest.cpp | 4 +- icu4c/source/test/intltest/srchtest.cpp | 6 +- icu4c/source/test/intltest/ssearch.cpp | 10 +- icu4c/source/test/intltest/strcase.cpp | 46 +- icu4c/source/test/intltest/strtest.cpp | 48 +- icu4c/source/test/intltest/svccoll.cpp | 6 +- icu4c/source/test/intltest/tchcfmt.cpp | 30 +- icu4c/source/test/intltest/testidn.cpp | 10 +- icu4c/source/test/intltest/testidna.cpp | 66 +-- icu4c/source/test/intltest/testutil.cpp | 8 +- icu4c/source/test/intltest/textfile.cpp | 8 +- icu4c/source/test/intltest/tfsmalls.cpp | 18 +- icu4c/source/test/intltest/thcoll.cpp | 16 +- icu4c/source/test/intltest/tmsgfmt.cpp | 152 +++--- icu4c/source/test/intltest/transapi.cpp | 42 +- icu4c/source/test/intltest/transrt.cpp | 30 +- icu4c/source/test/intltest/transtst.cpp | 250 ++++----- icu4c/source/test/intltest/trnserr.cpp | 2 +- icu4c/source/test/intltest/tscoll.cpp | 12 +- icu4c/source/test/intltest/tsdate.cpp | 48 +- icu4c/source/test/intltest/tsdcfmsy.cpp | 32 +- icu4c/source/test/intltest/tsdtfmsy.cpp | 16 +- icu4c/source/test/intltest/tsmthred.cpp | 8 +- icu4c/source/test/intltest/tsnmfmt.cpp | 70 +-- icu4c/source/test/intltest/tsnmfmt.h | 2 +- icu4c/source/test/intltest/tstnorm.cpp | 32 +- icu4c/source/test/intltest/tstnrapi.cpp | 10 +- icu4c/source/test/intltest/tufmtts.cpp | 8 +- icu4c/source/test/intltest/tzbdtest.cpp | 8 +- icu4c/source/test/intltest/tzfmttst.cpp | 86 +-- icu4c/source/test/intltest/tzoffloc.cpp | 24 +- icu4c/source/test/intltest/tzregts.cpp | 52 +- icu4c/source/test/intltest/tzrulets.cpp | 76 +-- icu4c/source/test/intltest/tztest.cpp | 132 ++--- icu4c/source/test/intltest/ucaconf.cpp | 6 +- icu4c/source/test/intltest/ucdtest.cpp | 46 +- icu4c/source/test/intltest/ucharstrietest.cpp | 52 +- icu4c/source/test/intltest/units_test.cpp | 2 +- icu4c/source/test/intltest/uobjtest.cpp | 2 +- icu4c/source/test/intltest/usettest.cpp | 289 +++++----- icu4c/source/test/intltest/ustrtest.cpp | 140 ++--- icu4c/source/test/intltest/uts46test.cpp | 92 ++-- icu4c/source/test/intltest/utxttest.cpp | 56 +- icu4c/source/test/intltest/uvectest.cpp | 8 +- icu4c/source/test/iotest/iotest.cpp | 16 +- icu4c/source/test/letest/FontObject.cpp | 24 +- icu4c/source/test/letest/FontTableCache.cpp | 4 +- .../test/letest/PortableFontInstance.cpp | 28 +- .../source/test/letest/SimpleFontInstance.cpp | 6 +- icu4c/source/test/letest/cmaps.cpp | 12 +- icu4c/source/test/letest/gendata.cpp | 4 +- icu4c/source/test/letest/letest.cpp | 10 +- .../test/perf/DateFmtPerf/DateFmtPerf.h | 10 +- icu4c/source/test/perf/charperf/charperf.cpp | 46 +- .../test/perf/collationperf/collperf.cpp | 88 +-- icu4c/source/test/perf/collperf/collperf.cpp | 7 +- .../source/test/perf/collperf2/collperf2.cpp | 46 +- .../test/perf/dicttrieperf/dicttrieperf.cpp | 34 +- .../perf/howExpensiveIs/howExpensiveIs.cpp | 6 +- .../source/test/perf/howExpensiveIs/sieve.cpp | 8 +- icu4c/source/test/perf/leperf/FontObject.cpp | 22 +- .../test/perf/leperf/FontTableCache.cpp | 4 +- .../test/perf/leperf/PortableFontInstance.cpp | 28 +- .../test/perf/leperf/SimpleFontInstance.cpp | 6 +- icu4c/source/test/perf/leperf/cmaps.cpp | 12 +- icu4c/source/test/perf/leperf/leperf.cpp | 6 +- icu4c/source/test/perf/normperf/dtfmtrtperf.h | 4 +- icu4c/source/test/perf/normperf/normperf.cpp | 4 +- icu4c/source/test/perf/normperf/normperf.h | 2 +- .../test/perf/normperf/simplenormperf.cpp | 2 +- .../test/perf/strsrchperf/strsrchperf.cpp | 2 +- .../test/perf/strsrchperf/strsrchperf.h | 2 +- icu4c/source/test/perf/ubrkperf/ubrkperf.cpp | 2 +- .../test/perf/ucnvavailperf/ucnvavailperf.cpp | 8 +- .../test/perf/unisetperf/draft/bitset.cpp | 38 +- .../test/perf/unisetperf/draft/trieset.cpp | 10 +- .../test/perf/unisetperf/unisetperf.cpp | 54 +- icu4c/source/test/perf/usetperf/bitset.cpp | 4 +- icu4c/source/test/perf/usetperf/usetperf.cpp | 4 +- icu4c/source/test/perf/ustrperf/stringperf.h | 10 +- icu4c/source/test/perf/utfperf/utfperf.cpp | 14 +- .../test/perf/utrie2perf/utrie2perf.cpp | 8 +- icu4c/source/tools/ctestfw/datamap.cpp | 2 +- icu4c/source/tools/ctestfw/uperf.cpp | 34 +- icu4c/source/tools/escapesrc/cptbl.h | 514 +++++++++--------- icu4c/source/tools/escapesrc/escapesrc.cpp | 6 +- icu4c/source/tools/genbrk/genbrk.cpp | 4 +- icu4c/source/tools/gencfu/gencfu.cpp | 2 +- icu4c/source/tools/gendict/gendict.cpp | 24 +- icu4c/source/tools/gennorm2/extradata.cpp | 24 +- icu4c/source/tools/gennorm2/gennorm2.cpp | 12 +- icu4c/source/tools/gennorm2/n2builder.cpp | 80 +-- icu4c/source/tools/gennorm2/norms.cpp | 26 +- icu4c/source/tools/gennorm2/norms.h | 2 +- icu4c/source/tools/genrb/derb.cpp | 24 +- icu4c/source/tools/genrb/genrb.cpp | 36 +- icu4c/source/tools/genrb/parse.cpp | 84 +-- icu4c/source/tools/genrb/reslist.cpp | 132 ++--- icu4c/source/tools/genrb/wrtjava.cpp | 56 +- icu4c/source/tools/genrb/wrtxml.cpp | 88 +-- .../tools/icuexportdata/icuexportdata.cpp | 52 +- icu4c/source/tools/icuinfo/icuinfo.cpp | 2 +- icu4c/source/tools/icupkg/icupkg.cpp | 8 +- icu4c/source/tools/icuswap/icuswap.cpp | 16 +- icu4c/source/tools/makeconv/genmbcs.cpp | 196 +++---- icu4c/source/tools/makeconv/makeconv.cpp | 22 +- icu4c/source/tools/pkgdata/pkgdata.cpp | 34 +- icu4c/source/tools/toolutil/collationinfo.cpp | 36 +- icu4c/source/tools/toolutil/dbgutil.cpp | 4 +- icu4c/source/tools/toolutil/package.cpp | 128 ++--- icu4c/source/tools/toolutil/pkg_genc.cpp | 16 +- icu4c/source/tools/toolutil/pkg_gencmn.cpp | 18 +- icu4c/source/tools/toolutil/pkgitems.cpp | 50 +- icu4c/source/tools/toolutil/ppucd.cpp | 70 +-- icu4c/source/tools/toolutil/swapimpl.cpp | 58 +- icu4c/source/tools/toolutil/toolutil.cpp | 4 +- icu4c/source/tools/toolutil/ucbuf.cpp | 18 +- icu4c/source/tools/toolutil/ucm.cpp | 4 +- icu4c/source/tools/toolutil/ucmstate.cpp | 16 +- icu4c/source/tools/toolutil/udbgutil.cpp | 4 +- icu4c/source/tools/toolutil/xmlparser.cpp | 62 +-- icu4c/source/tools/tzcode/icuzdump.cpp | 8 +- icu4c/source/tools/tzcode/tz2icu.cpp | 34 +- 515 files changed, 7786 insertions(+), 7762 deletions(-) diff --git a/icu4c/source/common/appendable.cpp b/icu4c/source/common/appendable.cpp index c0fbcc6530ad..de18148fe6d6 100644 --- a/icu4c/source/common/appendable.cpp +++ b/icu4c/source/common/appendable.cpp @@ -25,7 +25,7 @@ Appendable::~Appendable() {} UBool Appendable::appendCodePoint(UChar32 c) { if(c<=0xffff) { - return appendCodeUnit((char16_t)c); + return appendCodeUnit(static_cast(c)); } else { return appendCodeUnit(U16_LEAD(c)) && appendCodeUnit(U16_TRAIL(c)); } diff --git a/icu4c/source/common/bmpset.cpp b/icu4c/source/common/bmpset.cpp index 641c675c6706..bab4cff41728 100644 --- a/icu4c/source/common/bmpset.cpp +++ b/icu4c/source/common/bmpset.cpp @@ -75,7 +75,7 @@ static void set32x64Bits(uint32_t table[64], int32_t start, int32_t limit) { int32_t trail=start&0x3f; // Named for UTF-8 2-byte trail byte with lower 6 bits. // Set one bit indicating an all-one block. - uint32_t bits=(uint32_t)1<(1) << lead; if((start+1)==limit) { // Single-character shortcut. table[trail]|=bits; return; @@ -100,9 +100,9 @@ static void set32x64Bits(uint32_t table[64], int32_t start, int32_t limit) { ++lead; } if(lead(1) << lead) - 1); if(limitLead<0x20) { - bits&=((unsigned)1<(1) << limitLead) - 1; } for(trail=0; trail<64; ++trail) { table[trail]|=bits; @@ -111,7 +111,7 @@ static void set32x64Bits(uint32_t table[64], int32_t start, int32_t limit) { // limit<=0x800. If limit==0x800 then limitLead=32 and limitTrail=0. // In that case, bits=1<(1) << ((limitLead == 0x20) ? (limitLead - 1) : limitLead); for(trail=0; trail>6)))!=0); - } else if((uint32_t)c<0xd800 || (c>=0xe000 && c<=0xffff)) { + if (static_cast(c) <= 0xff) { + return latin1Contains[c]; + } else if (static_cast(c) <= 0x7ff) { + return static_cast((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) != 0); + } else if (static_cast(c) < 0xd800 || (c >= 0xe000 && c <= 0xffff)) { int lead=c>>12; uint32_t twoBits=(bmpBlockBits[(c>>6)&0x3f]>>lead)&0x10001; if(twoBits<=1) { // All 64 code points with the same bits 15..6 // are either in the set or not. - return (UBool)twoBits; + return static_cast(twoBits); } else { // Look up the code point in its 4k block of code points. return containsSlow(c, list4kStarts[lead], list4kStarts[lead+1]); } - } else if((uint32_t)c<=0x10ffff) { + } else if (static_cast(c) <= 0x10ffff) { // surrogate or supplementary code point return containsSlow(c, list4kStarts[0xd], list4kStarts[0x11]); } else { @@ -332,7 +332,7 @@ BMPSet::span(const char16_t *s, const char16_t *limit, USetSpanCondition spanCon break; } } else if(c<=0x7ff) { - if((table7FF[c&0x3f]&((uint32_t)1<<(c>>6)))==0) { + if ((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) == 0) { break; } } else if(c<0xd800 || c>=0xe000) { @@ -372,7 +372,7 @@ BMPSet::span(const char16_t *s, const char16_t *limit, USetSpanCondition spanCon break; } } else if(c<=0x7ff) { - if((table7FF[c&0x3f]&((uint32_t)1<<(c>>6)))!=0) { + if ((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) != 0) { break; } } else if(c<0xd800 || c>=0xe000) { @@ -421,7 +421,7 @@ BMPSet::spanBack(const char16_t *s, const char16_t *limit, USetSpanCondition spa break; } } else if(c<=0x7ff) { - if((table7FF[c&0x3f]&((uint32_t)1<<(c>>6)))==0) { + if ((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) == 0) { break; } } else if(c<0xd800 || c>=0xe000) { @@ -464,7 +464,7 @@ BMPSet::spanBack(const char16_t *s, const char16_t *limit, USetSpanCondition spa break; } } else if(c<=0x7ff) { - if((table7FF[c&0x3f]&((uint32_t)1<<(c>>6)))!=0) { + if ((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) != 0) { break; } } else if(c<0xd800 || c>=0xe000) { @@ -527,7 +527,7 @@ BMPSet::spanUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanConditi b=*s; } while(U8_IS_SINGLE(b)); } - length=(int32_t)(limit-s); + length = static_cast(limit - s); } if(spanCondition!=USET_SPAN_NOT_CONTAINED) { @@ -547,7 +547,7 @@ BMPSet::spanUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanConditi * the truncated sequence. */ b=*(limit-1); - if((int8_t)b<0) { + if (static_cast(b) < 0) { // b>=0x80: lead or trail byte if(b<0xc0) { // single trail byte, check for preceding 3- or 4-byte lead byte @@ -602,15 +602,15 @@ BMPSet::spanUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanConditi if(b>=0xe0) { if(b<0xf0) { if( /* handle U+0000..U+FFFF inline */ - (t1=(uint8_t)(s[0]-0x80)) <= 0x3f && - (t2=(uint8_t)(s[1]-0x80)) <= 0x3f + (t1 = static_cast(s[0] - 0x80)) <= 0x3f && + (t2 = static_cast(s[1] - 0x80)) <= 0x3f ) { b&=0xf; uint32_t twoBits=(bmpBlockBits[t1]>>b)&0x10001; if(twoBits<=1) { // All 64 code points with this lead byte and middle trail byte // are either in the set or not. - if(twoBits!=(uint32_t)spanCondition) { + if (twoBits != static_cast(spanCondition)) { return s-1; } } else { @@ -624,12 +624,12 @@ BMPSet::spanUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanConditi continue; } } else if( /* handle U+10000..U+10FFFF inline */ - (t1=(uint8_t)(s[0]-0x80)) <= 0x3f && - (t2=(uint8_t)(s[1]-0x80)) <= 0x3f && - (t3=(uint8_t)(s[2]-0x80)) <= 0x3f + (t1 = static_cast(s[0] - 0x80)) <= 0x3f && + (t2 = static_cast(s[1] - 0x80)) <= 0x3f && + (t3 = static_cast(s[2] - 0x80)) <= 0x3f ) { // Give an illegal sequence the same value as the result of contains(FFFD). - UChar32 c=((UChar32)(b-0xf0)<<18)|((UChar32)t1<<12)|(t2<<6)|t3; + UChar32 c = (static_cast(b - 0xf0) << 18) | (static_cast(t1) << 12) | (t2 << 6) | t3; if( ( (0x10000<=c && c<=0x10ffff) ? containsSlow(c, list4kStarts[0x10], list4kStarts[0x11]) : containsFFFD @@ -643,9 +643,9 @@ BMPSet::spanUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanConditi } else { if( /* handle U+0000..U+07FF inline */ b>=0xc0 && - (t1=(uint8_t)(*s-0x80)) <= 0x3f + (t1 = static_cast(*s - 0x80)) <= 0x3f ) { - if((USetSpanCondition)((table7FF[t1]&((uint32_t)1<<(b&0x1f)))!=0) != spanCondition) { + if (static_cast((table7FF[t1] & (static_cast(1) << (b & 0x1f))) != 0) != spanCondition) { return s-1; } ++s; @@ -711,7 +711,7 @@ BMPSet::spanBackUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanCon c=utf8_prevCharSafeBody(s, 0, &length, b, -3); // c is a valid code point, not ASCII, not a surrogate if(c<=0x7ff) { - if((USetSpanCondition)((table7FF[c&0x3f]&((uint32_t)1<<(c>>6)))!=0) != spanCondition) { + if (static_cast((table7FF[c & 0x3f] & (static_cast(1) << (c >> 6))) != 0) != spanCondition) { return prev+1; } } else if(c<=0xffff) { @@ -720,7 +720,7 @@ BMPSet::spanBackUTF8(const uint8_t *s, int32_t length, USetSpanCondition spanCon if(twoBits<=1) { // All 64 code points with the same bits 15..6 // are either in the set or not. - if(twoBits!=(uint32_t)spanCondition) { + if (twoBits != static_cast(spanCondition)) { return prev+1; } } else { diff --git a/icu4c/source/common/bmpset.h b/icu4c/source/common/bmpset.h index fad0310038ac..440a7a81b087 100644 --- a/icu4c/source/common/bmpset.h +++ b/icu4c/source/common/bmpset.h @@ -156,7 +156,7 @@ class BMPSet : public UMemory { }; inline UBool BMPSet::containsSlow(UChar32 c, int32_t lo, int32_t hi) const { - return (UBool)(findCodePoint(c, lo, hi) & 1); + return static_cast(findCodePoint(c, lo, hi) & 1); } U_NAMESPACE_END diff --git a/icu4c/source/common/brkeng.cpp b/icu4c/source/common/brkeng.cpp index e53a7b2ce4f5..a903357938c2 100644 --- a/icu4c/source/common/brkeng.cpp +++ b/icu4c/source/common/brkeng.cpp @@ -86,7 +86,7 @@ UnhandledEngine::findBreaks( UText *text, if (U_FAILURE(status)) return 0; utext_setNativeIndex(text, startPos); UChar32 c = utext_current32(text); - while((int32_t)utext_getNativeIndex(text) < endPos && fHandled->contains(c)) { + while (static_cast(utext_getNativeIndex(text)) < endPos && fHandled->contains(c)) { utext_next32(text); // TODO: recast loop to work with post-increment operations. c = utext_current32(text); } @@ -146,7 +146,7 @@ ICULanguageBreakFactory::getEngineFor(UChar32 c, const char* locale) { Mutex m(&gBreakEngineMutex); int32_t i = fEngines->size(); while (--i >= 0) { - lbe = (const LanguageBreakEngine *)(fEngines->elementAt(i)); + lbe = static_cast(fEngines->elementAt(i)); if (lbe != nullptr && lbe->handles(c, locale)) { return lbe; } @@ -259,7 +259,7 @@ ICULanguageBreakFactory::loadDictionaryMatcherFor(UScriptCode script) { CharString ext; const char16_t *extStart = u_memrchr(dictfname, 0x002e, dictnlength); // last dot if (extStart != nullptr) { - int32_t len = (int32_t)(extStart - dictfname); + int32_t len = static_cast(extStart - dictfname); ext.appendInvariantChars(UnicodeString(false, extStart + 1, dictnlength - len - 1), status); dictnlength = len; } @@ -269,18 +269,18 @@ ICULanguageBreakFactory::loadDictionaryMatcherFor(UScriptCode script) { UDataMemory *file = udata_open(U_ICUDATA_BRKITR, ext.data(), dictnbuf.data(), &status); if (U_SUCCESS(status)) { // build trie - const uint8_t *data = (const uint8_t *)udata_getMemory(file); - const int32_t *indexes = (const int32_t *)data; + const uint8_t* data = static_cast(udata_getMemory(file)); + const int32_t* indexes = reinterpret_cast(data); const int32_t offset = indexes[DictionaryData::IX_STRING_TRIE_OFFSET]; const int32_t trieType = indexes[DictionaryData::IX_TRIE_TYPE] & DictionaryData::TRIE_TYPE_MASK; DictionaryMatcher *m = nullptr; if (trieType == DictionaryData::TRIE_TYPE_BYTES) { const int32_t transform = indexes[DictionaryData::IX_TRANSFORM]; - const char *characters = (const char *)(data + offset); + const char* characters = reinterpret_cast(data + offset); m = new BytesDictionaryMatcher(characters, transform, file); } else if (trieType == DictionaryData::TRIE_TYPE_UCHARS) { - const char16_t *characters = (const char16_t *)(data + offset); + const char16_t* characters = reinterpret_cast(data + offset); m = new UCharsDictionaryMatcher(characters, file); } if (m == nullptr) { @@ -337,12 +337,12 @@ int32_t BreakEngineWrapper::findBreaks( // extends towards the start or end of the text, depending on 'reverse'. utext_setNativeIndex(text, startPos); - int32_t start = (int32_t)utext_getNativeIndex(text); + int32_t start = static_cast(utext_getNativeIndex(text)); int32_t current; int32_t rangeStart; int32_t rangeEnd; UChar32 c = utext_current32(text); - while((current = (int32_t)utext_getNativeIndex(text)) < endPos && delegate->handles(c)) { + while ((current = static_cast(utext_getNativeIndex(text))) < endPos && delegate->handles(c)) { utext_next32(text); // TODO: recast loop for postincrement c = utext_current32(text); } diff --git a/icu4c/source/common/brkiter.cpp b/icu4c/source/common/brkiter.cpp index 4f2f0f3ace88..4d945cc17e2b 100644 --- a/icu4c/source/common/brkiter.cpp +++ b/icu4c/source/common/brkiter.cpp @@ -85,7 +85,7 @@ BreakIterator::buildInstance(const Locale& loc, const char *type, UErrorCode &st // Get the actual string brkfname = ures_getString(brkName, &size, &status); U_ASSERT((size_t)size=sizeof(fnbuff)) { + if (static_cast(size) >= sizeof(fnbuff)) { size=0; if (U_SUCCESS(status)) { status = U_BUFFER_OVERFLOW_ERROR; @@ -99,7 +99,7 @@ BreakIterator::buildInstance(const Locale& loc, const char *type, UErrorCode &st char16_t* extStart=u_strchr(brkfname, 0x002e); int len = 0; if (extStart != nullptr){ - len = (int)(extStart-brkfname); + len = static_cast(extStart - brkfname); u_UCharsToChars(extStart+1, ext, sizeof(ext)); // nul terminates the buff u_UCharsToChars(brkfname, fnbuff, len); } diff --git a/icu4c/source/common/bytesinkutil.cpp b/icu4c/source/common/bytesinkutil.cpp index a32254a7dbab..e99c10f0838b 100644 --- a/icu4c/source/common/bytesinkutil.cpp +++ b/icu4c/source/common/bytesinkutil.cpp @@ -64,7 +64,7 @@ ByteSinkUtil::appendChange(const uint8_t *s, const uint8_t *limit, errorCode = U_INDEX_OUTOFBOUNDS_ERROR; return false; } - return appendChange((int32_t)(limit - s), s16, s16Length, sink, edits, errorCode); + return appendChange(static_cast(limit - s), s16, s16Length, sink, edits, errorCode); } void @@ -81,15 +81,15 @@ ByteSinkUtil::appendCodePoint(int32_t length, UChar32 c, ByteSink &sink, Edits * namespace { // See unicode/utf8.h U8_APPEND_UNSAFE(). -inline uint8_t getTwoByteLead(UChar32 c) { return (uint8_t)((c >> 6) | 0xc0); } -inline uint8_t getTwoByteTrail(UChar32 c) { return (uint8_t)((c & 0x3f) | 0x80); } +inline uint8_t getTwoByteLead(UChar32 c) { return static_cast((c >> 6) | 0xc0); } +inline uint8_t getTwoByteTrail(UChar32 c) { return static_cast((c & 0x3f) | 0x80); } } // namespace void ByteSinkUtil::appendTwoBytes(UChar32 c, ByteSink &sink) { U_ASSERT(0x80 <= c && c <= 0x7ff); // 2-byte UTF-8 - char s8[2] = { (char)getTwoByteLead(c), (char)getTwoByteTrail(c) }; + char s8[2] = {static_cast(getTwoByteLead(c)), static_cast(getTwoByteTrail(c))}; sink.Append(s8, 2); } @@ -114,7 +114,7 @@ ByteSinkUtil::appendUnchanged(const uint8_t *s, const uint8_t *limit, errorCode = U_INDEX_OUTOFBOUNDS_ERROR; return false; } - int32_t length = (int32_t)(limit - s); + int32_t length = static_cast(limit - s); if (length > 0) { appendNonEmptyUnchanged(s, length, sink, options, edits); } diff --git a/icu4c/source/common/bytesinkutil.h b/icu4c/source/common/bytesinkutil.h index b3bd487be1d6..eb3a622ae957 100644 --- a/icu4c/source/common/bytesinkutil.h +++ b/icu4c/source/common/bytesinkutil.h @@ -73,7 +73,7 @@ class U_COMMON_API ByteSinkUtil { /** The few bytes at [src, nextSrc[ were mapped/changed to valid code point c. */ static inline void appendCodePoint(const uint8_t *src, const uint8_t *nextSrc, UChar32 c, ByteSink &sink, Edits *edits = nullptr) { - appendCodePoint((int32_t)(nextSrc - src), c, sink, edits); + appendCodePoint(static_cast(nextSrc - src), c, sink, edits); } /** Append the two-byte character (U+0080..U+07FF). */ diff --git a/icu4c/source/common/bytestrie.cpp b/icu4c/source/common/bytestrie.cpp index 532ea9e9c0a9..048bbebb01af 100644 --- a/icu4c/source/common/bytestrie.cpp +++ b/icu4c/source/common/bytestrie.cpp @@ -327,7 +327,7 @@ BytesTrie::findUniqueValueFromBranch(const uint8_t *pos, int32_t length, ++pos; // ignore a comparison byte // handle its value int32_t node=*pos++; - UBool isFinal=(UBool)(node&kValueIsFinal); + UBool isFinal = static_cast(node & kValueIsFinal); int32_t value=readValue(pos, node>>1); pos=skipValue(pos, node); if(isFinal) { @@ -366,7 +366,7 @@ BytesTrie::findUniqueValue(const uint8_t *pos, UBool haveUniqueValue, int32_t &u // linear-match node pos+=node-kMinLinearMatch+1; // Ignore the match bytes. } else { - UBool isFinal=(UBool)(node&kValueIsFinal); + UBool isFinal = static_cast(node & kValueIsFinal); int32_t value=readValue(pos, node>>1); if(haveUniqueValue) { if(value!=uniqueValue) { @@ -434,7 +434,7 @@ BytesTrie::getNextBranchBytes(const uint8_t *pos, int32_t length, ByteSink &out) void BytesTrie::append(ByteSink &out, int c) { - char ch=(char)c; + char ch = static_cast(c); out.Append(&ch, 1); } diff --git a/icu4c/source/common/bytestriebuilder.cpp b/icu4c/source/common/bytestriebuilder.cpp index 876e0dfa1609..03bbc28e6577 100644 --- a/icu4c/source/common/bytestriebuilder.cpp +++ b/icu4c/source/common/bytestriebuilder.cpp @@ -43,10 +43,10 @@ class BytesTrieElement : public UMemory { int32_t offset=stringOffset; int32_t length; if(offset>=0) { - length=(uint8_t)strings[offset++]; + length = static_cast(strings[offset++]); } else { offset=~offset; - length=((int32_t)(uint8_t)strings[offset]<<8)|(uint8_t)strings[offset+1]; + length = (static_cast(static_cast(strings[offset])) << 8) | static_cast(strings[offset + 1]); offset+=2; } return StringPiece(strings.data()+offset, length); @@ -54,10 +54,10 @@ class BytesTrieElement : public UMemory { int32_t getStringLength(const CharString &strings) const { int32_t offset=stringOffset; if(offset>=0) { - return (uint8_t)strings[offset]; + return static_cast(strings[offset]); } else { offset=~offset; - return ((int32_t)(uint8_t)strings[offset]<<8)|(uint8_t)strings[offset+1]; + return (static_cast(static_cast(strings[offset])) << 8) | static_cast(strings[offset + 1]); } } @@ -102,9 +102,9 @@ BytesTrieElement::setTo(StringPiece s, int32_t val, int32_t offset=strings.length(); if(length>0xff) { offset=~offset; - strings.append((char)(length>>8), errorCode); + strings.append(static_cast(length >> 8), errorCode); } - strings.append((char)length, errorCode); + strings.append(static_cast(length), errorCode); stringOffset=offset; value=val; strings.append(s, errorCode); @@ -229,7 +229,7 @@ BytesTrieBuilder::buildBytes(UStringTrieBuildOption buildOption, UErrorCode &err errorCode=U_INDEX_OUTOFBOUNDS_ERROR; return; } - uprv_sortArray(elements, elementsLength, (int32_t)sizeof(BytesTrieElement), + uprv_sortArray(elements, elementsLength, static_cast(sizeof(BytesTrieElement)), compareElementStrings, strings, false, // need not be a stable sort &errorCode); @@ -284,7 +284,7 @@ BytesTrieBuilder::getElementStringLength(int32_t i) const { char16_t BytesTrieBuilder::getElementUnit(int32_t i, int32_t byteIndex) const { - return (uint8_t)elements[i].charAt(byteIndex, *strings); + return static_cast(elements[i].charAt(byteIndex, *strings)); } int32_t @@ -330,7 +330,7 @@ BytesTrieBuilder::skipElementsBySomeUnits(int32_t i, int32_t byteIndex, int32_t int32_t BytesTrieBuilder::indexOfElementWithNextUnit(int32_t i, int32_t byteIndex, char16_t byte) const { - char b=(char)byte; + char b = static_cast(byte); while(b==elements[i].charAt(byteIndex, *strings)) { ++i; } @@ -404,7 +404,7 @@ BytesTrieBuilder::write(int32_t byte) { int32_t newLength=bytesLength+1; if(ensureCapacity(newLength)) { bytesLength=newLength; - bytes[bytesCapacity-bytesLength]=(char)byte; + bytes[bytesCapacity - bytesLength] = static_cast(byte); } return bytesLength; } @@ -432,30 +432,30 @@ BytesTrieBuilder::writeValueAndFinal(int32_t i, UBool isFinal) { char intBytes[5]; int32_t length=1; if(i<0 || i>0xffffff) { - intBytes[0]=(char)BytesTrie::kFiveByteValueLead; - intBytes[1]=(char)((uint32_t)i>>24); - intBytes[2]=(char)((uint32_t)i>>16); - intBytes[3]=(char)((uint32_t)i>>8); - intBytes[4]=(char)i; + intBytes[0] = static_cast(BytesTrie::kFiveByteValueLead); + intBytes[1] = static_cast(static_cast(i) >> 24); + intBytes[2] = static_cast(static_cast(i) >> 16); + intBytes[3] = static_cast(static_cast(i) >> 8); + intBytes[4] = static_cast(i); length=5; // } else if(i<=BytesTrie::kMaxOneByteValue) { // intBytes[0]=(char)(BytesTrie::kMinOneByteValueLead+i); } else { if(i<=BytesTrie::kMaxTwoByteValue) { - intBytes[0]=(char)(BytesTrie::kMinTwoByteValueLead+(i>>8)); + intBytes[0] = static_cast(BytesTrie::kMinTwoByteValueLead + (i >> 8)); } else { if(i<=BytesTrie::kMaxThreeByteValue) { - intBytes[0]=(char)(BytesTrie::kMinThreeByteValueLead+(i>>16)); + intBytes[0] = static_cast(BytesTrie::kMinThreeByteValueLead + (i >> 16)); } else { - intBytes[0]=(char)BytesTrie::kFourByteValueLead; - intBytes[1]=(char)(i>>16); + intBytes[0] = static_cast(BytesTrie::kFourByteValueLead); + intBytes[1] = static_cast(i >> 16); length=2; } - intBytes[length++]=(char)(i>>8); + intBytes[length++] = static_cast(i >> 8); } - intBytes[length++]=(char)i; + intBytes[length++] = static_cast(i); } - intBytes[0]=(char)((intBytes[0]<<1)|isFinal); + intBytes[0] = static_cast((intBytes[0] << 1) | isFinal); return write(intBytes, length); } @@ -484,28 +484,28 @@ int32_t BytesTrieBuilder::internalEncodeDelta(int32_t i, char intBytes[]) { U_ASSERT(i>=0); if(i<=BytesTrie::kMaxOneByteDelta) { - intBytes[0]=(char)i; + intBytes[0] = static_cast(i); return 1; } int32_t length=1; if(i<=BytesTrie::kMaxTwoByteDelta) { - intBytes[0]=(char)(BytesTrie::kMinTwoByteDeltaLead+(i>>8)); + intBytes[0] = static_cast(BytesTrie::kMinTwoByteDeltaLead + (i >> 8)); } else { if(i<=BytesTrie::kMaxThreeByteDelta) { - intBytes[0]=(char)(BytesTrie::kMinThreeByteDeltaLead+(i>>16)); + intBytes[0] = static_cast(BytesTrie::kMinThreeByteDeltaLead + (i >> 16)); } else { if(i<=0xffffff) { - intBytes[0]=(char)BytesTrie::kFourByteDeltaLead; + intBytes[0] = static_cast(BytesTrie::kFourByteDeltaLead); } else { - intBytes[0]=(char)BytesTrie::kFiveByteDeltaLead; - intBytes[1]=(char)(i>>24); + intBytes[0] = static_cast(BytesTrie::kFiveByteDeltaLead); + intBytes[1] = static_cast(i >> 24); length=2; } - intBytes[length++]=(char)(i>>16); + intBytes[length++] = static_cast(i >> 16); } - intBytes[length++]=(char)(i>>8); + intBytes[length++] = static_cast(i >> 8); } - intBytes[length++]=(char)i; + intBytes[length++] = static_cast(i); return length; } diff --git a/icu4c/source/common/bytestrieiterator.cpp b/icu4c/source/common/bytestrieiterator.cpp index 65f54be48ae8..b60806f1f357 100644 --- a/icu4c/source/common/bytestrieiterator.cpp +++ b/icu4c/source/common/bytestrieiterator.cpp @@ -115,14 +115,14 @@ BytesTrie::Iterator::next(UErrorCode &errorCode) { pos=bytes_+stack_->elementAti(stackSize-2); stack_->setSize(stackSize-2); str_->truncate(length&0xffff); - length=(int32_t)((uint32_t)length>>16); + length = static_cast(static_cast(length) >> 16); if(length>1) { pos=branchNext(pos, length, errorCode); if(pos==nullptr) { return true; // Reached a final value. } } else { - str_->append((char)*pos++, errorCode); + str_->append(static_cast(*pos++), errorCode); } } if(remainingMatchLength_>=0) { @@ -134,7 +134,7 @@ BytesTrie::Iterator::next(UErrorCode &errorCode) { int32_t node=*pos++; if(node>=kMinValueLead) { // Deliver value for the byte sequence so far. - UBool isFinal=(UBool)(node&kValueIsFinal); + UBool isFinal = static_cast(node & kValueIsFinal); value_=readValue(pos, node>>1); if(isFinal || (maxLength_>0 && str_->length()==maxLength_)) { pos_=nullptr; @@ -186,7 +186,7 @@ BytesTrie::Iterator::branchNext(const uint8_t *pos, int32_t length, UErrorCode & while(length>kMaxBranchLinearSubNodeLength) { ++pos; // ignore the comparison byte // Push state for the greater-or-equal edge. - stack_->addElement((int32_t)(skipDelta(pos)-bytes_), errorCode); + stack_->addElement(static_cast(skipDelta(pos) - bytes_), errorCode); stack_->addElement(((length-(length>>1))<<16)|str_->length(), errorCode); // Follow the less-than edge. length>>=1; @@ -196,12 +196,12 @@ BytesTrie::Iterator::branchNext(const uint8_t *pos, int32_t length, UErrorCode & // Read the first (key, value) pair. uint8_t trieByte=*pos++; int32_t node=*pos++; - UBool isFinal=(UBool)(node&kValueIsFinal); + UBool isFinal = static_cast(node & kValueIsFinal); int32_t value=readValue(pos, node>>1); pos=skipValue(pos, node); - stack_->addElement((int32_t)(pos-bytes_), errorCode); + stack_->addElement(static_cast(pos - bytes_), errorCode); stack_->addElement(((length-1)<<16)|str_->length(), errorCode); - str_->append((char)trieByte, errorCode); + str_->append(static_cast(trieByte), errorCode); if(isFinal) { pos_=nullptr; value_=value; diff --git a/icu4c/source/common/caniter.cpp b/icu4c/source/common/caniter.cpp index cd474134c9f3..1b2bc2ada0c9 100644 --- a/icu4c/source/common/caniter.cpp +++ b/icu4c/source/common/caniter.cpp @@ -183,10 +183,10 @@ void CanonicalIterator::setSource(const UnicodeString &newSource, UErrorCode &st // catch degenerate case if (newSource.length() == 0) { - pieces = (UnicodeString **)uprv_malloc(sizeof(UnicodeString *)); - pieces_lengths = (int32_t*)uprv_malloc(1 * sizeof(int32_t)); + pieces = static_cast(uprv_malloc(sizeof(UnicodeString*))); + pieces_lengths = static_cast(uprv_malloc(1 * sizeof(int32_t))); pieces_length = 1; - current = (int32_t*)uprv_malloc(1 * sizeof(int32_t)); + current = static_cast(uprv_malloc(1 * sizeof(int32_t))); current_length = 1; if (pieces == nullptr || pieces_lengths == nullptr || current == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -229,10 +229,10 @@ void CanonicalIterator::setSource(const UnicodeString &newSource, UErrorCode &st // allocate the arrays, and find the strings that are CE to each segment - pieces = (UnicodeString **)uprv_malloc(list_length * sizeof(UnicodeString *)); + pieces = static_cast(uprv_malloc(list_length * sizeof(UnicodeString*))); pieces_length = list_length; - pieces_lengths = (int32_t*)uprv_malloc(list_length * sizeof(int32_t)); - current = (int32_t*)uprv_malloc(list_length * sizeof(int32_t)); + pieces_lengths = static_cast(uprv_malloc(list_length * sizeof(int32_t))); + current = static_cast(uprv_malloc(list_length * sizeof(int32_t))); current_length = list_length; if (pieces == nullptr || pieces_lengths == nullptr || current == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -330,7 +330,7 @@ void U_EXPORT2 CanonicalIterator::permute(UnicodeString &source, UBool skipZeros // prefix this character to all of them ne = subpermute.nextElement(el); while (ne != nullptr) { - UnicodeString *permRes = (UnicodeString *)(ne->value.pointer); + UnicodeString* permRes = static_cast(ne->value.pointer); UnicodeString *chStr = new UnicodeString(cp); //test for nullptr if (chStr == nullptr) { @@ -378,7 +378,7 @@ UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, i //while (it.hasNext()) while (ne != nullptr) { //String item = (String) it.next(); - UnicodeString item = *((UnicodeString *)(ne->value.pointer)); + UnicodeString item = *static_cast(ne->value.pointer); permutations.removeAll(); permute(item, CANITER_SKIP_ZEROES, &permutations, status); @@ -390,7 +390,7 @@ UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, i while (ne2 != nullptr) { //String possible = (String) it2.next(); //UnicodeString *possible = new UnicodeString(*((UnicodeString *)(ne2->value.pointer))); - UnicodeString possible(*((UnicodeString *)(ne2->value.pointer))); + UnicodeString possible(*static_cast(ne2->value.pointer)); UnicodeString attempt; nfd->normalize(possible, attempt, status); @@ -432,7 +432,7 @@ UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, i el = UHASH_FIRST; ne = result.nextElement(el); while(ne != nullptr) { - finalResult[result_len++] = *((UnicodeString *)(ne->value.pointer)); + finalResult[result_len++] = *static_cast(ne->value.pointer); ne = result.nextElement(el); } @@ -482,7 +482,7 @@ Hashtable *CanonicalIterator::getEquivalents2(Hashtable *fillinResult, const cha int32_t el = UHASH_FIRST; const UHashElement *ne = remainder.nextElement(el); while (ne != nullptr) { - UnicodeString item = *((UnicodeString *)(ne->value.pointer)); + UnicodeString item = *static_cast(ne->value.pointer); UnicodeString *toAdd = new UnicodeString(prefix); /* test for nullptr */ if (toAdd == nullptr) { diff --git a/icu4c/source/common/characterproperties.cpp b/icu4c/source/common/characterproperties.cpp index 98dd72bdb687..a3ed36ac5b8f 100644 --- a/icu4c/source/common/characterproperties.cpp +++ b/icu4c/source/common/characterproperties.cpp @@ -58,17 +58,17 @@ icu::UMutex cpMutex; // Does not use uset.h to reduce code dependencies void U_CALLCONV _set_add(USet *set, UChar32 c) { - ((UnicodeSet *)set)->add(c); + reinterpret_cast(set)->add(c); } void U_CALLCONV _set_addRange(USet *set, UChar32 start, UChar32 end) { - ((UnicodeSet *)set)->add(start, end); + reinterpret_cast(set)->add(start, end); } void U_CALLCONV _set_addString(USet *set, const char16_t *str, int32_t length) { - ((UnicodeSet *)set)->add(icu::UnicodeString((UBool)(length<0), str, length)); + reinterpret_cast(set)->add(icu::UnicodeString(static_cast(length < 0), str, length)); } UBool U_CALLCONV characterproperties_cleanup() { @@ -103,7 +103,7 @@ void U_CALLCONV initInclusion(UPropertySource src, UErrorCode &errorCode) { return; } USetAdder sa = { - (USet *)incl.getAlias(), + reinterpret_cast(incl.getAlias()), _set_add, _set_addRange, _set_addString, @@ -292,7 +292,7 @@ UnicodeSet *makeSet(UProperty property, UErrorCode &errorCode) { const icu::EmojiProps *ep = icu::EmojiProps::getSingleton(errorCode); if (U_FAILURE(errorCode)) { return nullptr; } USetAdder sa = { - (USet *)set.getAlias(), + reinterpret_cast(set.getAlias()), _set_add, _set_addRange, _set_addString, diff --git a/icu4c/source/common/cstring.cpp b/icu4c/source/common/cstring.cpp index e95816c13016..cc3f6deed890 100644 --- a/icu4c/source/common/cstring.cpp +++ b/icu4c/source/common/cstring.cpp @@ -126,7 +126,7 @@ T_CString_toLowerCase(char* str) if (str) { do - *str = (char)uprv_tolower(*str); + *str = uprv_tolower(*str); while (*(str++)); } @@ -140,7 +140,7 @@ T_CString_toUpperCase(char* str) if (str) { do - *str = (char)uprv_toupper(*str); + *str = uprv_toupper(*str); while (*(str++)); } diff --git a/icu4c/source/common/dictbe.cpp b/icu4c/source/common/dictbe.cpp index 3d672c03bfb3..888716c8d891 100644 --- a/icu4c/source/common/dictbe.cpp +++ b/icu4c/source/common/dictbe.cpp @@ -61,12 +61,12 @@ DictionaryBreakEngine::findBreaks( UText *text, // extends towards the start or end of the text, depending on 'reverse'. utext_setNativeIndex(text, startPos); - int32_t start = (int32_t)utext_getNativeIndex(text); + int32_t start = static_cast(utext_getNativeIndex(text)); int32_t current; int32_t rangeStart; int32_t rangeEnd; UChar32 c = utext_current32(text); - while((current = (int32_t)utext_getNativeIndex(text)) < endPos && fSet.contains(c)) { + while ((current = static_cast(utext_getNativeIndex(text))) < endPos && fSet.contains(c)) { utext_next32(text); // TODO: recast loop for postincrement c = utext_current32(text); } @@ -137,7 +137,7 @@ class PossibleWord { int32_t PossibleWord::candidates( UText *text, DictionaryMatcher *dict, int32_t rangeEnd ) { // TODO: If getIndex is too slow, use offset < 0 and add discardAll() - int32_t start = (int32_t)utext_getNativeIndex(text); + int32_t start = static_cast(utext_getNativeIndex(text)); if (start != offset) { offset = start; count = dict->matches(text, rangeEnd-start, UPRV_LENGTHOF(cuLengths), cuLengths, cpLengths, nullptr, &prefix); @@ -253,7 +253,7 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, utext_setNativeIndex(text, rangeStart); - while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) { + while (U_SUCCESS(status) && (current = static_cast(utext_getNativeIndex(text))) < rangeEnd) { cpWordLength = 0; cuWordLength = 0; @@ -269,7 +269,7 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, // If there was more than one, see which one can take us forward the most words else if (candidates > 1) { // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } do { @@ -278,7 +278,7 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, words[wordsFound%THAI_LOOKAHEAD].markCurrent(); // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } @@ -308,7 +308,7 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, // The text iterator should now be positioned at the end of the word we found. UChar32 uc = 0; - if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < THAI_ROOT_COMBINE_THRESHOLD) { + if (static_cast(utext_getNativeIndex(text)) < rangeEnd && cpWordLength < THAI_ROOT_COMBINE_THRESHOLD) { // if it is a dictionary word, do nothing. If it isn't, then if there is // no preceding word, or the non-word shares less than the minimum threshold // of characters with a dictionary word, then scan to resynchronize @@ -320,9 +320,9 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, UChar32 pc; int32_t chars = 0; for (;;) { - int32_t pcIndex = (int32_t)utext_getNativeIndex(text); + int32_t pcIndex = static_cast(utext_getNativeIndex(text)); pc = utext_next32(text); - int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex; + int32_t pcSize = static_cast(utext_getNativeIndex(text)) - pcIndex; chars += pcSize; remaining -= pcSize; if (remaining <= 0) { @@ -356,28 +356,28 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, utext_setNativeIndex(text, current+cuWordLength); } } - + // Never stop before a combining mark. int32_t currPos; - while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) { + while ((currPos = static_cast(utext_getNativeIndex(text))) < rangeEnd && fMarkSet.contains(utext_current32(text))) { utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos; + cuWordLength += static_cast(utext_getNativeIndex(text)) - currPos; } - + // Look ahead for possible suffixes if a dictionary word does not follow. // We do this in code rather than using a rule so that the heuristic // resynch continues to function. For example, one of the suffix characters // could be a typo in the middle of a word. - if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cuWordLength > 0) { + if (static_cast(utext_getNativeIndex(text)) < rangeEnd && cuWordLength > 0) { if (words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0 && fSuffixSet.contains(uc = utext_current32(text))) { if (uc == THAI_PAIYANNOI) { if (!fSuffixSet.contains(utext_previous32(text))) { // Skip over previous end and PAIYANNOI utext_next32(text); - int32_t paiyannoiIndex = (int32_t)utext_getNativeIndex(text); + int32_t paiyannoiIndex = static_cast(utext_getNativeIndex(text)); utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - paiyannoiIndex; // Add PAIYANNOI to word + cuWordLength += static_cast(utext_getNativeIndex(text)) - paiyannoiIndex; // Add PAIYANNOI to word uc = utext_current32(text); // Fetch next character } else { @@ -389,9 +389,9 @@ ThaiBreakEngine::divideUpDictionaryRange( UText *text, if (utext_previous32(text) != THAI_MAIYAMOK) { // Skip over previous end and MAIYAMOK utext_next32(text); - int32_t maiyamokIndex = (int32_t)utext_getNativeIndex(text); + int32_t maiyamokIndex = static_cast(utext_getNativeIndex(text)); utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - maiyamokIndex; // Add MAIYAMOK to word + cuWordLength += static_cast(utext_getNativeIndex(text)) - maiyamokIndex; // Add MAIYAMOK to word } else { // Restore prior position @@ -489,7 +489,7 @@ LaoBreakEngine::divideUpDictionaryRange( UText *text, utext_setNativeIndex(text, rangeStart); - while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) { + while (U_SUCCESS(status) && (current = static_cast(utext_getNativeIndex(text))) < rangeEnd) { cuWordLength = 0; cpWordLength = 0; @@ -514,7 +514,7 @@ LaoBreakEngine::divideUpDictionaryRange( UText *text, words[wordsFound%LAO_LOOKAHEAD].markCurrent(); // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } @@ -541,7 +541,7 @@ LaoBreakEngine::divideUpDictionaryRange( UText *text, // just found (if there is one), but only if the preceding word does not exceed // the threshold. // The text iterator should now be positioned at the end of the word we found. - if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < LAO_ROOT_COMBINE_THRESHOLD) { + if (static_cast(utext_getNativeIndex(text)) < rangeEnd && cpWordLength < LAO_ROOT_COMBINE_THRESHOLD) { // if it is a dictionary word, do nothing. If it isn't, then if there is // no preceding word, or the non-word shares less than the minimum threshold // of characters with a dictionary word, then scan to resynchronize @@ -554,9 +554,9 @@ LaoBreakEngine::divideUpDictionaryRange( UText *text, UChar32 uc; int32_t chars = 0; for (;;) { - int32_t pcIndex = (int32_t)utext_getNativeIndex(text); + int32_t pcIndex = static_cast(utext_getNativeIndex(text)); pc = utext_next32(text); - int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex; + int32_t pcSize = static_cast(utext_getNativeIndex(text)) - pcIndex; chars += pcSize; remaining -= pcSize; if (remaining <= 0) { @@ -590,9 +590,9 @@ LaoBreakEngine::divideUpDictionaryRange( UText *text, // Never stop before a combining mark. int32_t currPos; - while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) { + while ((currPos = static_cast(utext_getNativeIndex(text))) < rangeEnd && fMarkSet.contains(utext_current32(text))) { utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos; + cuWordLength += static_cast(utext_getNativeIndex(text)) - currPos; } // Look ahead for possible suffixes if a dictionary word does not follow. @@ -682,7 +682,7 @@ BurmeseBreakEngine::divideUpDictionaryRange( UText *text, utext_setNativeIndex(text, rangeStart); - while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) { + while (U_SUCCESS(status) && (current = static_cast(utext_getNativeIndex(text))) < rangeEnd) { cuWordLength = 0; cpWordLength = 0; @@ -707,7 +707,7 @@ BurmeseBreakEngine::divideUpDictionaryRange( UText *text, words[wordsFound%BURMESE_LOOKAHEAD].markCurrent(); // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } @@ -734,7 +734,7 @@ BurmeseBreakEngine::divideUpDictionaryRange( UText *text, // just found (if there is one), but only if the preceding word does not exceed // the threshold. // The text iterator should now be positioned at the end of the word we found. - if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < BURMESE_ROOT_COMBINE_THRESHOLD) { + if (static_cast(utext_getNativeIndex(text)) < rangeEnd && cpWordLength < BURMESE_ROOT_COMBINE_THRESHOLD) { // if it is a dictionary word, do nothing. If it isn't, then if there is // no preceding word, or the non-word shares less than the minimum threshold // of characters with a dictionary word, then scan to resynchronize @@ -747,9 +747,9 @@ BurmeseBreakEngine::divideUpDictionaryRange( UText *text, UChar32 uc; int32_t chars = 0; for (;;) { - int32_t pcIndex = (int32_t)utext_getNativeIndex(text); + int32_t pcIndex = static_cast(utext_getNativeIndex(text)); pc = utext_next32(text); - int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex; + int32_t pcSize = static_cast(utext_getNativeIndex(text)) - pcIndex; chars += pcSize; remaining -= pcSize; if (remaining <= 0) { @@ -783,9 +783,9 @@ BurmeseBreakEngine::divideUpDictionaryRange( UText *text, // Never stop before a combining mark. int32_t currPos; - while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) { + while ((currPos = static_cast(utext_getNativeIndex(text))) < rangeEnd && fMarkSet.contains(utext_current32(text))) { utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos; + cuWordLength += static_cast(utext_getNativeIndex(text)) - currPos; } // Look ahead for possible suffixes if a dictionary word does not follow. @@ -888,7 +888,7 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, utext_setNativeIndex(text, rangeStart); - while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) { + while (U_SUCCESS(status) && (current = static_cast(utext_getNativeIndex(text))) < rangeEnd) { cuWordLength = 0; cpWordLength = 0; @@ -905,7 +905,7 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, // If there was more than one, see which one can take us forward the most words else if (candidates > 1) { // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } do { @@ -914,7 +914,7 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, words[wordsFound % KHMER_LOOKAHEAD].markCurrent(); // If we're already at the end of the range, we're done - if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) { + if (static_cast(utext_getNativeIndex(text)) >= rangeEnd) { goto foundBest; } @@ -941,7 +941,7 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, // just found (if there is one), but only if the preceding word does not exceed // the threshold. // The text iterator should now be positioned at the end of the word we found. - if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < KHMER_ROOT_COMBINE_THRESHOLD) { + if (static_cast(utext_getNativeIndex(text)) < rangeEnd && cpWordLength < KHMER_ROOT_COMBINE_THRESHOLD) { // if it is a dictionary word, do nothing. If it isn't, then if there is // no preceding word, or the non-word shares less than the minimum threshold // of characters with a dictionary word, then scan to resynchronize @@ -954,9 +954,9 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, UChar32 uc; int32_t chars = 0; for (;;) { - int32_t pcIndex = (int32_t)utext_getNativeIndex(text); + int32_t pcIndex = static_cast(utext_getNativeIndex(text)); pc = utext_next32(text); - int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex; + int32_t pcSize = static_cast(utext_getNativeIndex(text)) - pcIndex; chars += pcSize; remaining -= pcSize; if (remaining <= 0) { @@ -989,9 +989,9 @@ KhmerBreakEngine::divideUpDictionaryRange( UText *text, // Never stop before a combining mark. int32_t currPos; - while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) { + while ((currPos = static_cast(utext_getNativeIndex(text))) < rangeEnd && fMarkSet.contains(utext_current32(text))) { utext_next32(text); - cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos; + cuWordLength += static_cast(utext_getNativeIndex(text)) - currPos; } // Look ahead for possible suffixes if a dictionary word does not follow. @@ -1120,7 +1120,7 @@ static inline bool isKatakana(UChar32 value) { // Replicates an internal UText function. static inline int32_t utext_i32_flag(int32_t bitIndex) { - return (int32_t)1 << bitIndex; + return static_cast(1) << bitIndex; } /* @@ -1167,14 +1167,14 @@ CjkBreakEngine::divideUpDictionaryRange( UText *inText, int32_t limit = rangeEnd; U_ASSERT(limit <= utext_nativeLength(inText)); if (limit > utext_nativeLength(inText)) { - limit = (int32_t)utext_nativeLength(inText); + limit = static_cast(utext_nativeLength(inText)); } inputMap.adoptInsteadAndCheckErrorCode(new UVector32(status), status); if (U_FAILURE(status)) { return 0; } while (utext_getNativeIndex(inText) < limit) { - int32_t nativePosition = (int32_t)utext_getNativeIndex(inText); + int32_t nativePosition = static_cast(utext_getNativeIndex(inText)); UChar32 c = utext_next32(inText); U_ASSERT(c != U_SENTINEL); inString.append(c); @@ -1304,7 +1304,7 @@ CjkBreakEngine::divideUpDictionaryRange( UText *inText, int32_t ix = 0; bool is_prev_katakana = false; for (int32_t i = 0; i < numCodePts; ++i, ix = inString.moveIndex32(ix, 1)) { - if ((uint32_t)bestSnlp.elementAti(i) == kuint32max) { + if (static_cast(bestSnlp.elementAti(i)) == kuint32max) { continue; } @@ -1327,9 +1327,9 @@ CjkBreakEngine::divideUpDictionaryRange( UText *inText, } for (int32_t j = 0; j < count; j++) { - uint32_t newSnlp = (uint32_t)bestSnlp.elementAti(i) + (uint32_t)values.elementAti(j); + uint32_t newSnlp = static_cast(bestSnlp.elementAti(i)) + static_cast(values.elementAti(j)); int32_t ln_j_i = lengths.elementAti(j) + i; - if (newSnlp < (uint32_t)bestSnlp.elementAti(ln_j_i)) { + if (newSnlp < static_cast(bestSnlp.elementAti(ln_j_i))) { bestSnlp.setElementAt(newSnlp, ln_j_i); prev.setElementAt(i, ln_j_i); } @@ -1353,7 +1353,7 @@ CjkBreakEngine::divideUpDictionaryRange( UText *inText, } if (katakanaRunLength < kMaxKatakanaGroupLength) { uint32_t newSnlp = bestSnlp.elementAti(i) + getKatakanaCost(katakanaRunLength); - if (newSnlp < (uint32_t)bestSnlp.elementAti(i+katakanaRunLength)) { + if (newSnlp < static_cast(bestSnlp.elementAti(i + katakanaRunLength))) { bestSnlp.setElementAt(newSnlp, i+katakanaRunLength); prev.setElementAt(i, i+katakanaRunLength); // prev[j] = i; } @@ -1371,7 +1371,7 @@ CjkBreakEngine::divideUpDictionaryRange( UText *inText, int32_t numBreaks = 0; // No segmentation found, set boundary to end of range - if ((uint32_t)bestSnlp.elementAti(numCodePts) == kuint32max) { + if (static_cast(bestSnlp.elementAti(numCodePts)) == kuint32max) { t_boundary.addElement(numCodePts, status); numBreaks++; } else if (isPhraseBreaking) { diff --git a/icu4c/source/common/dictionarydata.cpp b/icu4c/source/common/dictionarydata.cpp index 80b6d82d56ae..4bae0c6d3358 100644 --- a/icu4c/source/common/dictionarydata.cpp +++ b/icu4c/source/common/dictionarydata.cpp @@ -47,13 +47,13 @@ int32_t UCharsDictionaryMatcher::matches(UText *text, int32_t maxLength, int32_t int32_t *prefix) const { UCharsTrie uct(characters); - int32_t startingTextIndex = (int32_t)utext_getNativeIndex(text); + int32_t startingTextIndex = static_cast(utext_getNativeIndex(text)); int32_t wordCount = 0; int32_t codePointsMatched = 0; for (UChar32 c = utext_next32(text); c >= 0; c=utext_next32(text)) { UStringTrieResult result = (codePointsMatched == 0) ? uct.first(c) : uct.next(c); - int32_t lengthMatched = (int32_t)utext_getNativeIndex(text) - startingTextIndex; + int32_t lengthMatched = static_cast(utext_getNativeIndex(text)) - startingTextIndex; codePointsMatched += 1; if (USTRINGTRIE_HAS_VALUE(result)) { if (wordCount < limit) { @@ -101,7 +101,7 @@ UChar32 BytesDictionaryMatcher::transform(UChar32 c) const { if (delta < 0 || 0xFD < delta) { return U_SENTINEL; } - return (UChar32)delta; + return static_cast(delta); } return c; } @@ -114,13 +114,13 @@ int32_t BytesDictionaryMatcher::matches(UText *text, int32_t maxLength, int32_t int32_t *lengths, int32_t *cpLengths, int32_t *values, int32_t *prefix) const { BytesTrie bt(characters); - int32_t startingTextIndex = (int32_t)utext_getNativeIndex(text); + int32_t startingTextIndex = static_cast(utext_getNativeIndex(text)); int32_t wordCount = 0; int32_t codePointsMatched = 0; for (UChar32 c = utext_next32(text); c >= 0; c=utext_next32(text)) { UStringTrieResult result = (codePointsMatched == 0) ? bt.first(transform(c)) : bt.next(transform(c)); - int32_t lengthMatched = (int32_t)utext_getNativeIndex(text) - startingTextIndex; + int32_t lengthMatched = static_cast(utext_getNativeIndex(text)) - startingTextIndex; codePointsMatched += 1; if (USTRINGTRIE_HAS_VALUE(result)) { if (wordCount < limit) { diff --git a/icu4c/source/common/edits.cpp b/icu4c/source/common/edits.cpp index 3348145d48df..82055e5e543b 100644 --- a/icu4c/source/common/edits.cpp +++ b/icu4c/source/common/edits.cpp @@ -47,7 +47,7 @@ Edits &Edits::copyArray(const Edits &other) { return *this; } if (length > capacity) { - uint16_t *newArray = (uint16_t *)uprv_malloc((size_t)length * 2); + uint16_t* newArray = static_cast(uprv_malloc(static_cast(length) * 2)); if (newArray == nullptr) { length = delta = numChanges = 0; errorCode_ = U_MEMORY_ALLOCATION_ERROR; @@ -186,30 +186,30 @@ void Edits::addReplace(int32_t oldLength, int32_t newLength) { head |= oldLength << 6; } else if(oldLength <= 0x7fff) { head |= LENGTH_IN_1TRAIL << 6; - array[limit++] = (uint16_t)(0x8000 | oldLength); + array[limit++] = static_cast(0x8000 | oldLength); } else { head |= (LENGTH_IN_2TRAIL + (oldLength >> 30)) << 6; - array[limit++] = (uint16_t)(0x8000 | (oldLength >> 15)); - array[limit++] = (uint16_t)(0x8000 | oldLength); + array[limit++] = static_cast(0x8000 | (oldLength >> 15)); + array[limit++] = static_cast(0x8000 | oldLength); } if(newLength < LENGTH_IN_1TRAIL) { head |= newLength; } else if(newLength <= 0x7fff) { head |= LENGTH_IN_1TRAIL; - array[limit++] = (uint16_t)(0x8000 | newLength); + array[limit++] = static_cast(0x8000 | newLength); } else { head |= LENGTH_IN_2TRAIL + (newLength >> 30); - array[limit++] = (uint16_t)(0x8000 | (newLength >> 15)); - array[limit++] = (uint16_t)(0x8000 | newLength); + array[limit++] = static_cast(0x8000 | (newLength >> 15)); + array[limit++] = static_cast(0x8000 | newLength); } - array[length] = (uint16_t)head; + array[length] = static_cast(head); length = limit; } } void Edits::append(int32_t r) { if(length < capacity || growArray()) { - array[length++] = (uint16_t)r; + array[length++] = static_cast(r); } } @@ -232,7 +232,7 @@ UBool Edits::growArray() { errorCode_ = U_INDEX_OUTOFBOUNDS_ERROR; return false; } - uint16_t *newArray = (uint16_t *)uprv_malloc((size_t)newCapacity * 2); + uint16_t* newArray = static_cast(uprv_malloc(static_cast(newCapacity) * 2)); if (newArray == nullptr) { errorCode_ = U_MEMORY_ALLOCATION_ERROR; return false; @@ -415,7 +415,7 @@ int32_t Edits::Iterator::readLength(int32_t head) { U_ASSERT(array[index] >= 0x8000); U_ASSERT(array[index + 1] >= 0x8000); int32_t len = ((head & 1) << 30) | - ((int32_t)(array[index] & 0x7fff) << 15) | + (static_cast(array[index] & 0x7fff) << 15) | (array[index + 1] & 0x7fff); index += 2; return len; diff --git a/icu4c/source/common/emojiprops.cpp b/icu4c/source/common/emojiprops.cpp index f2b3f4762f33..2e4fb0130ce8 100644 --- a/icu4c/source/common/emojiprops.cpp +++ b/icu4c/source/common/emojiprops.cpp @@ -83,8 +83,8 @@ void EmojiProps::load(UErrorCode &errorCode) { memory = udata_openChoice(nullptr, "icu", "uemoji", isAcceptable, this, &errorCode); if (U_FAILURE(errorCode)) { return; } - const uint8_t *inBytes = (const uint8_t *)udata_getMemory(memory); - const int32_t *inIndexes = (const int32_t *)inBytes; + const uint8_t* inBytes = static_cast(udata_getMemory(memory)); + const int32_t* inIndexes = reinterpret_cast(inBytes); int32_t indexesLength = inIndexes[IX_CPTRIE_OFFSET] / 4; if (indexesLength <= IX_RGI_EMOJI_ZWJ_SEQUENCE_TRIE_OFFSET) { errorCode = U_INVALID_FORMAT_ERROR; // Not enough indexes. @@ -104,7 +104,7 @@ EmojiProps::load(UErrorCode &errorCode) { offset = inIndexes[i]; nextOffset = inIndexes[i + 1]; // Set/leave nullptr if there is no UCharsTrie. - const char16_t *p = nextOffset > offset ? (const char16_t *)(inBytes + offset) : nullptr; + const char16_t* p = nextOffset > offset ? reinterpret_cast(inBytes + offset) : nullptr; stringTries[getStringTrieIndex(i)] = p; } } diff --git a/icu4c/source/common/filteredbrk.cpp b/icu4c/source/common/filteredbrk.cpp index a1490b61213f..29b02dd38424 100644 --- a/icu4c/source/common/filteredbrk.cpp +++ b/icu4c/source/common/filteredbrk.cpp @@ -50,8 +50,8 @@ static void _fb_trace(const char *m, const UnicodeString *s, UBool b, int32_t d, * Used with sortedInsert() */ static int32_t U_CALLCONV compareUnicodeString(UElement t1, UElement t2) { - const UnicodeString &a = *(const UnicodeString*)t1.pointer; - const UnicodeString &b = *(const UnicodeString*)t2.pointer; + const UnicodeString& a = *static_cast(t1.pointer); + const UnicodeString& b = *static_cast(t2.pointer); return a.compare(b); } @@ -76,7 +76,7 @@ class UStringSet : public UVector { * Return the ith UnicodeString alias */ inline const UnicodeString* getStringAt(int32_t i) const { - return (const UnicodeString*)elementAt(i); + return static_cast(elementAt(i)); } /** * Adopt the UnicodeString if not already contained. diff --git a/icu4c/source/common/loadednormalizer2impl.cpp b/icu4c/source/common/loadednormalizer2impl.cpp index 2be1d08ebc6d..bb5736137d72 100644 --- a/icu4c/source/common/loadednormalizer2impl.cpp +++ b/icu4c/source/common/loadednormalizer2impl.cpp @@ -82,8 +82,8 @@ LoadedNormalizer2Impl::load(const char *packageName, const char *name, UErrorCod if(U_FAILURE(errorCode)) { return; } - const uint8_t *inBytes=(const uint8_t *)udata_getMemory(memory); - const int32_t *inIndexes=(const int32_t *)inBytes; + const uint8_t* inBytes = static_cast(udata_getMemory(memory)); + const int32_t* inIndexes = reinterpret_cast(inBytes); int32_t indexesLength=inIndexes[IX_NORM_TRIE_OFFSET]/4; if(indexesLength<=IX_MIN_LCCC_CP) { errorCode=U_INVALID_FORMAT_ERROR; // Not enough indexes. @@ -101,7 +101,7 @@ LoadedNormalizer2Impl::load(const char *packageName, const char *name, UErrorCod offset=nextOffset; nextOffset=inIndexes[IX_SMALL_FCD_OFFSET]; - const uint16_t *inExtraData=(const uint16_t *)(inBytes+offset); + const uint16_t* inExtraData = reinterpret_cast(inBytes + offset); // smallFCD: new in formatVersion 2 offset=nextOffset; @@ -311,7 +311,7 @@ Normalizer2::getInstance(const char *packageName, { Mutex lock; if(cache!=nullptr) { - allModes=(Norm2AllModes *)uhash_get(cache, name); + allModes = static_cast(uhash_get(cache, name)); } } if(allModes==nullptr) { @@ -331,7 +331,7 @@ Normalizer2::getInstance(const char *packageName, void *temp=uhash_get(cache, name); if(temp==nullptr) { int32_t keyLength= static_cast(uprv_strlen(name)+1); - char *nameCopy=(char *)uprv_malloc(keyLength); + char* nameCopy = static_cast(uprv_malloc(keyLength)); if(nameCopy==nullptr) { errorCode=U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -341,7 +341,7 @@ Normalizer2::getInstance(const char *packageName, uhash_put(cache, nameCopy, localAllModes.orphan(), &errorCode); } else { // race condition - allModes=(Norm2AllModes *)temp; + allModes = static_cast(temp); } } } diff --git a/icu4c/source/common/localematcher.cpp b/icu4c/source/common/localematcher.cpp index 8aae596bc8d7..1e74dd1f1493 100644 --- a/icu4c/source/common/localematcher.cpp +++ b/icu4c/source/common/localematcher.cpp @@ -780,7 +780,7 @@ int32_t acceptLanguage(UEnumeration &supportedLocales, Locale::Iterator &desired ULOC_ACCEPT_VALID : ULOC_ACCEPT_FALLBACK; } const char *bestStr = result.getSupportedLocale()->getName(); - int32_t bestLength = (int32_t)uprv_strlen(bestStr); + int32_t bestLength = static_cast(uprv_strlen(bestStr)); if (bestLength <= capacity) { uprv_memcpy(dest, bestStr, bestLength); } diff --git a/icu4c/source/common/locbased.h b/icu4c/source/common/locbased.h index 45738863b5ec..2d260b527873 100644 --- a/icu4c/source/common/locbased.h +++ b/icu4c/source/common/locbased.h @@ -99,7 +99,7 @@ inline LocaleBased::LocaleBased(char* validAlias, char* actualAlias) : inline LocaleBased::LocaleBased(const char* validAlias, const char* actualAlias) : // ugh: cast away const - valid((char*)validAlias), actual((char*)actualAlias) { + valid(const_cast(validAlias)), actual(const_cast(actualAlias)) { } U_NAMESPACE_END diff --git a/icu4c/source/common/locdispnames.cpp b/icu4c/source/common/locdispnames.cpp index 0be069357af7..70470a862912 100644 --- a/icu4c/source/common/locdispnames.cpp +++ b/icu4c/source/common/locdispnames.cpp @@ -351,7 +351,7 @@ _getStringOrCopyKey(const char *path, const char *locale, } } else { /* no string from a resource bundle: convert the substitute */ - length=(int32_t)uprv_strlen(substitute); + length = static_cast(uprv_strlen(substitute)); u_charsToUChars(substitute, dest, uprv_min(length, destCapacity)); errorCode = U_USING_DEFAULT_WARNING; } diff --git a/icu4c/source/common/locdspnm.cpp b/icu4c/source/common/locdspnm.cpp index c65a349dbd38..270684341c5c 100644 --- a/icu4c/source/common/locdspnm.cpp +++ b/icu4c/source/common/locdspnm.cpp @@ -336,10 +336,11 @@ LocaleDisplayNamesImpl::LocaleDisplayNamesImpl(const Locale& locale, { while (length-- > 0) { UDisplayContext value = *contexts++; - UDisplayContextType selector = (UDisplayContextType)((uint32_t)value >> 8); + UDisplayContextType selector = + static_cast(static_cast(value) >> 8); switch (selector) { case UDISPCTX_TYPE_DIALECT_HANDLING: - dialectHandling = (UDialectHandling)value; + dialectHandling = static_cast(value); break; case UDISPCTX_TYPE_CAPITALIZATION: capitalizationContext = value; @@ -407,7 +408,7 @@ LocaleDisplayNamesImpl::CapitalizationContextSink::~CapitalizationContextSink() void LocaleDisplayNamesImpl::initialize() { - LocaleDisplayNamesImpl *nonConstThis = (LocaleDisplayNamesImpl *)this; + LocaleDisplayNamesImpl* nonConstThis = this; nonConstThis->locale = langData.getLocale() == Locale::getRoot() ? regionData.getLocale() : langData.getLocale(); @@ -426,16 +427,16 @@ LocaleDisplayNamesImpl::initialize() { pattern = UnicodeString("{0} ({1})", -1, US_INV); } format.applyPatternMinMaxArguments(pattern, 2, 2, status); - if (pattern.indexOf((char16_t)0xFF08) >= 0) { - formatOpenParen.setTo((char16_t)0xFF08); // fullwidth ( - formatReplaceOpenParen.setTo((char16_t)0xFF3B); // fullwidth [ - formatCloseParen.setTo((char16_t)0xFF09); // fullwidth ) - formatReplaceCloseParen.setTo((char16_t)0xFF3D); // fullwidth ] + if (pattern.indexOf(static_cast(0xFF08)) >= 0) { + formatOpenParen.setTo(static_cast(0xFF08)); // fullwidth ( + formatReplaceOpenParen.setTo(static_cast(0xFF3B)); // fullwidth [ + formatCloseParen.setTo(static_cast(0xFF09)); // fullwidth ) + formatReplaceCloseParen.setTo(static_cast(0xFF3D)); // fullwidth ] } else { - formatOpenParen.setTo((char16_t)0x0028); // ( - formatReplaceOpenParen.setTo((char16_t)0x005B); // [ - formatCloseParen.setTo((char16_t)0x0029); // ) - formatReplaceCloseParen.setTo((char16_t)0x005D); // ] + formatOpenParen.setTo(static_cast(0x0028)); // ( + formatReplaceOpenParen.setTo(static_cast(0x005B)); // [ + formatCloseParen.setTo(static_cast(0x0029)); // ) + formatReplaceCloseParen.setTo(static_cast(0x005D)); // ] } UnicodeString ktPattern; @@ -495,7 +496,7 @@ UDisplayContext LocaleDisplayNamesImpl::getContext(UDisplayContextType type) const { switch (type) { case UDISPCTX_TYPE_DIALECT_HANDLING: - return (UDisplayContext)dialectHandling; + return static_cast(dialectHandling); case UDISPCTX_TYPE_CAPITALIZATION: return capitalizationContext; case UDISPCTX_TYPE_DISPLAY_LENGTH: @@ -505,7 +506,7 @@ LocaleDisplayNamesImpl::getContext(UDisplayContextType type) const { default: break; } - return (UDisplayContext)0; + return static_cast(0); } UnicodeString& @@ -652,7 +653,7 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc, appendWithSep(resultRemainder, temp3); } else { appendWithSep(resultRemainder, temp) - .append((char16_t)0x3d /* = */) + .append(static_cast(0x3d) /* = */) .append(temp2); } } diff --git a/icu4c/source/common/locid.cpp b/icu4c/source/common/locid.cpp index 8f05e23e73c3..c0757fc2f2d3 100644 --- a/icu4c/source/common/locid.cpp +++ b/icu4c/source/common/locid.cpp @@ -109,7 +109,7 @@ namespace { // void U_CALLCONV deleteLocale(void *obj) { - delete (icu::Locale *) obj; + delete static_cast(obj); } UBool U_CALLCONV locale_cleanup() @@ -132,7 +132,7 @@ void U_CALLCONV locale_init(UErrorCode &status) { U_NAMESPACE_USE U_ASSERT(gLocaleCache == nullptr); - gLocaleCache = new Locale[(int)eMAX_LOCALES]; + gLocaleCache = new Locale[static_cast(eMAX_LOCALES)]; if (gLocaleCache == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; @@ -194,7 +194,7 @@ Locale *locale_set_default_internal(const char *id, UErrorCode& status) { ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup); } - Locale *newDefault = (Locale *)uhash_get(gDefaultLocalesHashT, localeNameBuf.data()); + Locale* newDefault = static_cast(uhash_get(gDefaultLocalesHashT, localeNameBuf.data())); if (newDefault == nullptr) { newDefault = new Locale(Locale::eBOGUS); if (newDefault == nullptr) { @@ -202,7 +202,7 @@ Locale *locale_set_default_internal(const char *id, UErrorCode& status) { return gDefaultLocale; } newDefault->init(localeNameBuf.data(), false); - uhash_put(gDefaultLocalesHashT, (char*) newDefault->getName(), newDefault, &status); + uhash_put(gDefaultLocalesHashT, const_cast(newDefault->getName()), newDefault, &status); if (U_FAILURE(status)) { return gDefaultLocale; } @@ -296,7 +296,7 @@ Locale::Locale( const char * newLanguage, // Language if ( newLanguage != nullptr ) { - lsize = (int32_t)uprv_strlen(newLanguage); + lsize = static_cast(uprv_strlen(newLanguage)); if ( lsize < 0 || lsize > ULOC_STRING_LIMIT ) { // int32 wrap setToBogus(); return; @@ -308,7 +308,7 @@ Locale::Locale( const char * newLanguage, // _Country if ( newCountry != nullptr ) { - csize = (int32_t)uprv_strlen(newCountry); + csize = static_cast(uprv_strlen(newCountry)); if ( csize < 0 || csize > ULOC_STRING_LIMIT ) { // int32 wrap setToBogus(); return; @@ -325,7 +325,7 @@ Locale::Locale( const char * newLanguage, } // remove trailing _'s - vsize = (int32_t)uprv_strlen(newVariant); + vsize = static_cast(uprv_strlen(newVariant)); if ( vsize < 0 || vsize > ULOC_STRING_LIMIT ) { // int32 wrap setToBogus(); return; @@ -338,7 +338,7 @@ Locale::Locale( const char * newLanguage, if ( newKeywords != nullptr) { - ksize = (int32_t)uprv_strlen(newKeywords); + ksize = static_cast(uprv_strlen(newKeywords)); if ( ksize < 0 || ksize > ULOC_STRING_LIMIT ) { setToBogus(); return; @@ -1200,8 +1200,8 @@ AliasReplacer::parseLanguageReplacement( return; } // We have multiple field so we have to allocate and parse - CharString* str = new CharString( - replacement, (int32_t)uprv_strlen(replacement), status); + CharString* str = + new CharString(replacement, static_cast(uprv_strlen(replacement)), status); LocalPointer lpStr(str, status); toBeFreed.adoptElement(lpStr.orphan(), status); if (U_FAILURE(status)) { @@ -1213,7 +1213,7 @@ AliasReplacer::parseLanguageReplacement( *endOfField = '\0'; // null terminiate it. endOfField++; const char* start = endOfField; - endOfField = (char*) uprv_strchr(start, '_'); + endOfField = const_cast(uprv_strchr(start, '_')); size_t len = 0; if (endOfField == nullptr) { len = uprv_strlen(start); @@ -1228,7 +1228,7 @@ AliasReplacer::parseLanguageReplacement( return; } start = endOfField++; - endOfField = (char*)uprv_strchr(start, '_'); + endOfField = const_cast(uprv_strchr(start, '_')); if (endOfField == nullptr) { len = uprv_strlen(start); } else { @@ -1243,7 +1243,7 @@ AliasReplacer::parseLanguageReplacement( return; } start = endOfField++; - endOfField = (char*)uprv_strchr(start, '_'); + endOfField = const_cast(uprv_strchr(start, '_')); if (endOfField == nullptr) { len = uprv_strlen(start); } else { @@ -1285,7 +1285,7 @@ AliasReplacer::replaceLanguage( variant_index++) { if (checkVariants) { U_ASSERT(variant_index < variant_size); - searchVariant = (const char*)(variants.elementAt(variant_index)); + searchVariant = static_cast(variants.elementAt(variant_index)); } if (searchVariant != nullptr && uprv_strlen(searchVariant) < 4) { @@ -1406,13 +1406,13 @@ AliasReplacer::replaceTerritory(UVector& toBeFreed, UErrorCode& status) U_ASSERT(foundInReplacement[len] == ' ' || foundInReplacement[len] == '\0'); item.adoptInsteadAndCheckErrorCode( - new CharString(foundInReplacement, (int32_t)len, status), status); + new CharString(foundInReplacement, static_cast(len), status), status); } } if (item.isNull() && U_SUCCESS(status)) { item.adoptInsteadAndCheckErrorCode( new CharString(replacement, - (int32_t)(firstSpace - replacement), status), status); + static_cast(firstSpace - replacement), status), status); } if (U_FAILURE(status)) { return false; } replacedRegion = item->data(); @@ -1454,7 +1454,7 @@ AliasReplacer::replaceVariant(UErrorCode& status) } // Since we may have more than one variant, we need to loop through them. for (int32_t i = 0; i < variants.size(); i++) { - const char *variant = (const char*)(variants.elementAt(i)); + const char* variant = static_cast(variants.elementAt(i)); const char *replacement = data->variantMap().get(variant); if (replacement == nullptr) { // Found no replacement data for this variant. @@ -1496,7 +1496,7 @@ AliasReplacer::replaceSubdivision( size_t len = (firstSpace != nullptr) ? (firstSpace - replacement) : uprv_strlen(replacement); if (2 <= len && len <= 8) { - output.append(replacement, (int32_t)len, status); + output.append(replacement, static_cast(len), status); if (2 == len) { // Add 'zzzz' based on changes to UTS #35 for CLDR-14312. output.append("zzzz", 4, status); @@ -1546,7 +1546,7 @@ AliasReplacer::replaceTransformedExtensions( } const char* nextTKey = ultag_getTKeyStart(tvalue); if (nextTKey != nullptr) { - *((char*)(nextTKey-1)) = '\0'; // NUL terminate tvalue + *const_cast(nextTKey - 1) = '\0'; // NUL terminate tvalue } tfields.insertElementAt((void*)tkey, tfields.size(), status); if (U_FAILURE(status)) { @@ -1561,14 +1561,14 @@ AliasReplacer::replaceTransformedExtensions( if (output.length() > 0) { output.append('-', status); } - const char* tfield = (const char*) tfields.elementAt(i); + const char* tfield = static_cast(tfields.elementAt(i)); const char* tvalue = uprv_strchr(tfield, '-'); if (tvalue == nullptr) { status = U_ILLEGAL_ARGUMENT_ERROR; return false; } // Split the "tkey-tvalue" pair string so that we can canonicalize the tvalue. - *((char*)tvalue++) = '\0'; // NUL terminate tkey + *const_cast(tvalue++) = '\0'; // NUL terminate tkey output.append(tfield, status).append('-', status); const char* bcpTValue = ulocimp_toBcpType(tfield, tvalue, nullptr, nullptr); output.append((bcpTValue == nullptr) ? tvalue : bcpTValue, status); @@ -1604,7 +1604,7 @@ AliasReplacer::outputToString( int32_t variantsStart = out.length(); for (int32_t i = 0; i < variants.size(); i++) { out.append(SEP_CHAR, status) - .append((const char*)(variants.elementAt(i)), + .append(static_cast(variants.elementAt(i)), status); } T_CString_toUpperCase(out.data() + variantsStart); @@ -1673,7 +1673,7 @@ AliasReplacer::replace(const Locale& locale, CharString& out, UErrorCode& status int changed = 0; // A UVector to to hold CharString allocated by the replace* method // and freed when out of scope from his function. - UVector stringsToBeFreed([](void *obj){ delete ((CharString*) obj); }, + UVector stringsToBeFreed([](void *obj) { delete static_cast(obj); }, nullptr, 10, status); while (U_SUCCESS(status)) { // Something wrong with the data cause looping here more than 10 times @@ -1866,10 +1866,10 @@ Locale& Locale::init(const char* localeID, UBool canonicalize) uloc_canonicalize(localeID, fullName, sizeof(fullNameBuffer), &err) : uloc_getName(localeID, fullName, sizeof(fullNameBuffer), &err); - if(err == U_BUFFER_OVERFLOW_ERROR || length >= (int32_t)sizeof(fullNameBuffer)) { + if (err == U_BUFFER_OVERFLOW_ERROR || length >= static_cast(sizeof(fullNameBuffer))) { U_ASSERT(baseName == nullptr); /*Go to heap for the fullName if necessary*/ - char* newFullName = (char *)uprv_malloc(sizeof(char)*(length + 1)); + char* newFullName = static_cast(uprv_malloc(sizeof(char) * (length + 1))); if (newFullName == nullptr) { break; // error: out of memory } @@ -1895,7 +1895,7 @@ Locale& Locale::init(const char* localeID, UBool canonicalize) fieldIdx < UPRV_LENGTHOF(field)-1 && (at == nullptr || separator < at)) { field[fieldIdx] = separator + 1; - fieldLen[fieldIdx-1] = (int32_t)(separator - field[fieldIdx-1]); + fieldLen[fieldIdx - 1] = static_cast(separator - field[fieldIdx - 1]); fieldIdx++; } // variant may contain @foo or .foo POSIX cruft; remove it @@ -1905,12 +1905,12 @@ Locale& Locale::init(const char* localeID, UBool canonicalize) if (separator==nullptr || (sep2!=nullptr && separator > sep2)) { separator = sep2; } - fieldLen[fieldIdx-1] = (int32_t)(separator - field[fieldIdx-1]); + fieldLen[fieldIdx - 1] = static_cast(separator - field[fieldIdx - 1]); } else { - fieldLen[fieldIdx-1] = length - (int32_t)(field[fieldIdx-1] - fullName); + fieldLen[fieldIdx - 1] = length - static_cast(field[fieldIdx - 1] - fullName); } - if (fieldLen[0] >= (int32_t)(sizeof(language))) + if (fieldLen[0] >= static_cast(sizeof(language))) { break; // error: the language field is too long } @@ -1941,7 +1941,7 @@ Locale& Locale::init(const char* localeID, UBool canonicalize) if (fieldLen[variantField] > 0) { /* We have a variant */ - variantBegin = (int32_t)(field[variantField] - fullName); + variantBegin = static_cast(field[variantField] - fullName); } err = U_ZERO_ERROR; @@ -1991,8 +1991,8 @@ Locale::initBaseName(UErrorCode &status) { const char *eqPtr = uprv_strchr(fullName, '='); if (atPtr && eqPtr && atPtr < eqPtr) { // Key words exist. - int32_t baseNameLength = (int32_t)(atPtr - fullName); - char* newBaseName = (char *)uprv_malloc(baseNameLength + 1); + int32_t baseNameLength = static_cast(atPtr - fullName); + char* newBaseName = static_cast(uprv_malloc(baseNameLength + 1)); if (newBaseName == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; @@ -2435,7 +2435,7 @@ class KeywordEnumeration : public StringEnumeration { UErrorCode status = U_ZERO_ERROR; return new KeywordEnumeration( keywords.data(), keywords.length(), - (int32_t)(current - keywords.data()), status); + static_cast(current - keywords.data()), status); } virtual int32_t count(UErrorCode& status) const override { @@ -2454,7 +2454,7 @@ class KeywordEnumeration : public StringEnumeration { int32_t len; if(U_SUCCESS(status) && *current != 0) { result = current; - len = (int32_t)uprv_strlen(current); + len = static_cast(uprv_strlen(current)); current += len+1; if(resultLength != nullptr) { *resultLength = len; @@ -2652,14 +2652,15 @@ Locale::setKeywordValue(const char* keywordName, const char* keywordValue, UErro if (status == U_STRING_NOT_TERMINATED_WARNING) { status = U_ZERO_ERROR; } - int32_t bufferLength = uprv_max((int32_t)(uprv_strlen(fullName) + 1), ULOC_FULLNAME_CAPACITY); + int32_t bufferLength = + uprv_max(static_cast(uprv_strlen(fullName) + 1), ULOC_FULLNAME_CAPACITY); int32_t newLength = uloc_setKeywordValue(keywordName, keywordValue, fullName, bufferLength, &status) + 1; U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING); /* Handle the case the current buffer is not enough to hold the new id */ if (status == U_BUFFER_OVERFLOW_ERROR) { U_ASSERT(newLength > bufferLength); - char* newFullName = (char *)uprv_malloc(newLength); + char* newFullName = static_cast(uprv_malloc(newLength)); if (newFullName == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; diff --git a/icu4c/source/common/loclikely.cpp b/icu4c/source/common/loclikely.cpp index 5aa929dc4b15..e7188be3667b 100644 --- a/icu4c/source/common/loclikely.cpp +++ b/icu4c/source/common/loclikely.cpp @@ -170,7 +170,7 @@ _uloc_addLikelySubtags(const char* localeID, return; } - int32_t trailingLength = (int32_t)uprv_strlen(trailing); + int32_t trailingLength = static_cast(uprv_strlen(trailing)); const icu::LikelySubtags* likelySubtags = icu::LikelySubtags::getSingleton(err); if (U_FAILURE(err)) { @@ -193,11 +193,11 @@ _uloc_addLikelySubtags(const char* localeID, } createTagStringWithAlternates( language, - (int32_t)uprv_strlen(language), + static_cast(uprv_strlen(language)), lsr.script, - (int32_t)uprv_strlen(lsr.script), + static_cast(uprv_strlen(lsr.script)), lsr.region, - (int32_t)uprv_strlen(lsr.region), + static_cast(uprv_strlen(lsr.region)), variant.data(), variant.length(), trailing, @@ -235,7 +235,7 @@ _uloc_minimizeSubtags(const char* localeID, return; } - int32_t trailingLength = (int32_t)uprv_strlen(trailing); + int32_t trailingLength = static_cast(uprv_strlen(trailing)); const icu::LikelySubtags* likelySubtags = icu::LikelySubtags::getSingleton(err); if (U_FAILURE(err)) { @@ -256,11 +256,11 @@ _uloc_minimizeSubtags(const char* localeID, } createTagStringWithAlternates( language, - (int32_t)uprv_strlen(language), + static_cast(uprv_strlen(language)), lsr.script, - (int32_t)uprv_strlen(lsr.script), + static_cast(uprv_strlen(lsr.script)), lsr.region, - (int32_t)uprv_strlen(lsr.region), + static_cast(uprv_strlen(lsr.region)), variant.data(), variant.length(), trailing, diff --git a/icu4c/source/common/loclikelysubtags.cpp b/icu4c/source/common/loclikelysubtags.cpp index a750bb7b1a39..7c6131197d89 100644 --- a/icu4c/source/common/loclikelysubtags.cpp +++ b/icu4c/source/common/loclikelysubtags.cpp @@ -609,9 +609,9 @@ LSR LikelySubtags::maximize(const char *language, const char *script, const char bool returnInputIfUnmatch, UErrorCode &errorCode) const { if (U_FAILURE(errorCode)) { return {}; } - return maximize({language, (int32_t)uprv_strlen(language)}, - {script, (int32_t)uprv_strlen(script)}, - {region, (int32_t)uprv_strlen(region)}, + return maximize({language, static_cast(uprv_strlen(language))}, + {script, static_cast(uprv_strlen(script))}, + {region, static_cast(uprv_strlen(region))}, returnInputIfUnmatch, errorCode); } diff --git a/icu4c/source/common/locmap.cpp b/icu4c/source/common/locmap.cpp index b95eb04428b5..da78c7716a75 100644 --- a/icu4c/source/common/locmap.cpp +++ b/icu4c/source/common/locmap.cpp @@ -979,7 +979,7 @@ getHostID(const ILcidPosixMap *this_0, const char* posixID, UErrorCode& status) if (U_FAILURE(status)) { return locmap_root->hostID; } int32_t bestIdx = 0; int32_t bestIdxDiff = 0; - int32_t posixIDlen = (int32_t)uprv_strlen(posixID); + int32_t posixIDlen = static_cast(uprv_strlen(posixID)); uint32_t idx; for (idx = 0; idx < this_0->numRegions; idx++ ) { diff --git a/icu4c/source/common/locutil.cpp b/icu4c/source/common/locutil.cpp index 1abecef1c5b0..a257ec593a80 100644 --- a/icu4c/source/common/locutil.cpp +++ b/icu4c/source/common/locutil.cpp @@ -171,7 +171,7 @@ LocaleUtility::initLocaleFromName(const UnicodeString& id, Locale& result) prev = 0; UErrorCode status = U_ZERO_ERROR; do { - i = id.indexOf((char16_t)0x40, prev); + i = id.indexOf(static_cast(0x40), prev); if(i < 0) { // no @ between prev and the rest of the string buffer.appendInvariantChars(id.tempSubString(prev), status); @@ -224,7 +224,7 @@ LocaleUtility::getAvailableLocaleNames(const UnicodeString& bundleID) Hashtable* htp; umtx_lock(nullptr); - htp = (Hashtable*) cache->get(bundleID); + htp = static_cast(cache->get(bundleID)); umtx_unlock(nullptr); if (htp == nullptr) { diff --git a/icu4c/source/common/lstmbe.cpp b/icu4c/source/common/lstmbe.cpp index fb8eb01761cd..c1a142469c44 100644 --- a/icu4c/source/common/lstmbe.cpp +++ b/icu4c/source/common/lstmbe.cpp @@ -164,7 +164,7 @@ class Array1D : public ReadArray1D { Array1D() : memory_(nullptr), data_(nullptr), d1_(0) {} Array1D(int32_t d1, UErrorCode &status) : memory_(uprv_malloc(d1 * sizeof(float))), - data_((float*)memory_), d1_(d1) { + data_(static_cast(memory_)), d1_(d1) { if (U_SUCCESS(status)) { if (memory_ == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -301,7 +301,7 @@ class Array2D : public ReadArray2D { Array2D() : memory_(nullptr), data_(nullptr), d1_(0), d2_(0) {} Array2D(int32_t d1, int32_t d2, UErrorCode &status) : memory_(uprv_malloc(d1 * d2 * sizeof(float))), - data_((float*)memory_), d1_(d1), d2_(d2) { + data_(static_cast(memory_)), d1_(d1), d2_(d2) { if (U_SUCCESS(status)) { if (memory_ == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -526,11 +526,11 @@ void CodePointsVectorizer::vectorize( int32_t current; char16_t str[2] = {0, 0}; while (U_SUCCESS(status) && - (current = (int32_t)utext_getNativeIndex(text)) < endPos) { + (current = static_cast(utext_getNativeIndex(text))) < endPos) { // Since the LSTMBreakEngine is currently only accept chars in BMP, // we can ignore the possibility of hitting supplementary code // point. - str[0] = (char16_t) utext_next32(text); + str[0] = static_cast(utext_next32(text)); U_ASSERT(!U_IS_SURROGATE(str[0])); offsets.addElement(current, status); indices.addElement(stringToIndex(str), status); @@ -733,7 +733,7 @@ LSTMBreakEngine::divideUpDictionaryRange( UText *text, #endif // LSTM_DEBUG // current = argmax(logp) - LSTMClass current = (LSTMClass)logp.maxIndex(); + LSTMClass current = static_cast(logp.maxIndex()); // BIES logic. if (current == BEGIN || current == SINGLE) { if (i != 0) { diff --git a/icu4c/source/common/messagepattern.cpp b/icu4c/source/common/messagepattern.cpp index 8f15c4ab467d..96555ce8ae33 100644 --- a/icu4c/source/common/messagepattern.cpp +++ b/icu4c/source/common/messagepattern.cpp @@ -351,7 +351,7 @@ MessagePattern::autoQuoteApostropheDeep() const { for(int32_t i=count; i>0;) { const Part &part=getPart(--i); if(part.getType()==UMSGPAT_PART_TYPE_INSERT_CHAR) { - modified.insert(part.index, (char16_t)part.value); + modified.insert(part.index, static_cast(part.value)); } } return modified; @@ -628,7 +628,7 @@ MessagePattern::parseArg(int32_t index, int32_t argStartLength, int32_t nestingL } } // change the ARG_START type from NONE to argType - partsList->a[argStart].value=(int16_t)argType; + partsList->a[argStart].value = static_cast(argType); if(argType==UMSGPAT_ARG_TYPE_SIMPLE) { addPart(UMSGPAT_PART_TYPE_ARG_TYPE, typeIndex, length, 0, errorCode); } @@ -980,13 +980,13 @@ MessagePattern::parseDouble(int32_t start, int32_t limit, UBool allowInfinity, } // Let Double.parseDouble() throw a NumberFormatException. char numberChars[128]; - int32_t capacity=(int32_t)sizeof(numberChars); + int32_t capacity = static_cast(sizeof(numberChars)); int32_t length=limit-start; if(length>=capacity) { break; // number too long } msg.extract(start, length, numberChars, capacity, US_INV); - if((int32_t)uprv_strlen(numberChars)(uprv_strlen(numberChars)) < length) { break; // contains non-invariant character that was turned into NUL } char *end; @@ -1006,7 +1006,7 @@ MessagePattern::skipWhiteSpace(int32_t index) { const char16_t *s=msg.getBuffer(); int32_t msgLength=msg.length(); const char16_t *t=PatternProps::skipWhiteSpace(s+index, msgLength-index); - return (int32_t)(t-s); + return static_cast(t - s); } int32_t @@ -1014,7 +1014,7 @@ MessagePattern::skipIdentifier(int32_t index) { const char16_t *s=msg.getBuffer(); int32_t msgLength=msg.length(); const char16_t *t=PatternProps::skipIdentifier(s+index, msgLength-index); - return (int32_t)(t-s); + return static_cast(t - s); } int32_t @@ -1105,8 +1105,8 @@ MessagePattern::addPart(UMessagePatternPartType type, int32_t index, int32_t len Part &part=partsList->a[partsLength++]; part.type=type; part.index=index; - part.length=(uint16_t)length; - part.value=(int16_t)value; + part.length = static_cast(length); + part.value = static_cast(value); part.limitPartIndex=0; } } diff --git a/icu4c/source/common/mlbe.cpp b/icu4c/source/common/mlbe.cpp index 7e734f2c8adf..178c0239d265 100644 --- a/icu4c/source/common/mlbe.cpp +++ b/icu4c/source/common/mlbe.cpp @@ -57,7 +57,7 @@ int32_t MlBreakEngine::divideUpRange(UText *inText, int32_t rangeStart, int32_t // moving forward, finally the last six values in the indexList are // [length-4, length-3, length-2, length-1, -1, -1]. The "+4" here means four extra "-1". int32_t indexSize = codePointLength + 4; - int32_t *indexList = (int32_t *)uprv_malloc(indexSize * sizeof(int32_t)); + int32_t* indexList = static_cast(uprv_malloc(indexSize * sizeof(int32_t))); if (indexList == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return 0; diff --git a/icu4c/source/common/norm2allmodes.h b/icu4c/source/common/norm2allmodes.h index a2cfc89c1a81..4b30d787e87c 100644 --- a/icu4c/source/common/norm2allmodes.h +++ b/icu4c/source/common/norm2allmodes.h @@ -174,7 +174,7 @@ class Normalizer2WithImpl : public Normalizer2 { errorCode=U_ILLEGAL_ARGUMENT_ERROR; return 0; } - return (int32_t)(spanQuickCheckYes(sArray, sArray+s.length(), errorCode)-sArray); + return static_cast(spanQuickCheckYes(sArray, sArray + s.length(), errorCode) - sArray); } virtual const char16_t * spanQuickCheckYes(const char16_t *src, const char16_t *limit, UErrorCode &errorCode) const = 0; diff --git a/icu4c/source/common/normalizer2.cpp b/icu4c/source/common/normalizer2.cpp index 6856736b888a..dad3df4edee2 100644 --- a/icu4c/source/common/normalizer2.cpp +++ b/icu4c/source/common/normalizer2.cpp @@ -380,8 +380,8 @@ normalizeSecondAndAppend(const UNormalizer2 *norm2, firstLength=firstString.length(); // In case it was -1. // secondLength==0: Nothing to do, and n2wi->normalizeAndAppend(nullptr, nullptr, buffer, ...) would crash. if(secondLength!=0) { - const Normalizer2 *n2=(const Normalizer2 *)norm2; - const Normalizer2WithImpl *n2wi=dynamic_cast(n2); + const Normalizer2* n2 = reinterpret_cast(norm2); + const Normalizer2WithImpl* n2wi = dynamic_cast(n2); if(n2wi!=nullptr) { // Avoid duplicate argument checking and support NUL-terminated src. UnicodeString safeMiddle; diff --git a/icu4c/source/common/normalizer2impl.cpp b/icu4c/source/common/normalizer2impl.cpp index 2f120138d066..758a84c11069 100644 --- a/icu4c/source/common/normalizer2impl.cpp +++ b/icu4c/source/common/normalizer2impl.cpp @@ -53,9 +53,9 @@ namespace { */ inline uint8_t leadByteForCP(UChar32 c) { if (c <= 0x7f) { - return (uint8_t)c; + return static_cast(c); } else if (c <= 0x7ff) { - return (uint8_t)(0xc0+(c>>6)); + return static_cast(0xc0 + (c >> 6)); } else { // Should not occur because ccc(U+0300)!=0. return 0xe0; @@ -82,7 +82,7 @@ UChar32 codePointFromValidUTF8(const uint8_t *cpStart, const uint8_t *cpLimit) { return ((c&0x1f)<<6) | (cpStart[1]&0x3f); case 3: // no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (char16_t) - return (char16_t)((c<<12) | ((cpStart[1]&0x3f)<<6) | (cpStart[2]&0x3f)); + return static_cast((c << 12) | ((cpStart[1] & 0x3f) << 6) | (cpStart[2] & 0x3f)); case 4: return ((c&7)<<18) | ((cpStart[1]&0x3f)<<12) | ((cpStart[2]&0x3f)<<6) | (cpStart[3]&0x3f); default: @@ -100,8 +100,8 @@ UChar32 previousHangulOrJamo(const uint8_t *start, const uint8_t *p) { uint8_t l = *p; uint8_t t1, t2; if (0xe1 <= l && l <= 0xed && - (t1 = (uint8_t)(p[1] - 0x80)) <= 0x3f && - (t2 = (uint8_t)(p[2] - 0x80)) <= 0x3f && + (t1 = static_cast(p[1] - 0x80)) <= 0x3f && + (t2 = static_cast(p[2] - 0x80)) <= 0x3f && (l < 0xed || t1 <= 0x1f)) { return ((l & 0xf) << 12) | (t1 << 6) | t2; } @@ -125,7 +125,7 @@ int32_t getJamoTMinusBase(const uint8_t *src, const uint8_t *limit) { } } else if (src[1] == 0x87) { uint8_t t = src[2]; - if ((int8_t)t <= (int8_t)0x82u) { + if (static_cast(t) <= static_cast(0x82u)) { return t - (0xa7 - 0x40); } } @@ -138,10 +138,10 @@ appendCodePointDelta(const uint8_t *cpStart, const uint8_t *cpLimit, int32_t del ByteSink &sink, Edits *edits) { char buffer[U8_MAX_LENGTH]; int32_t length; - int32_t cpLength = (int32_t)(cpLimit - cpStart); + int32_t cpLength = static_cast(cpLimit - cpStart); if (cpLength == 1) { // The builder makes ASCII map to ASCII. - buffer[0] = (uint8_t)(*cpStart + delta); + buffer[0] = static_cast(*cpStart + delta); length = 1; } else { int32_t trail = *(cpLimit-1) + delta; @@ -150,7 +150,7 @@ appendCodePointDelta(const uint8_t *cpStart, const uint8_t *cpLimit, int32_t del --cpLimit; length = 0; do { buffer[length++] = *cpStart++; } while (cpStart < cpLimit); - buffer[length++] = (uint8_t)trail; + buffer[length++] = static_cast(trail); } else { // Decode the code point, add the delta, re-encode. UChar32 c = codePointFromValidUTF8(cpStart, cpLimit) + delta; @@ -205,16 +205,16 @@ UBool ReorderingBuffer::init(int32_t destCapacity, UErrorCode &errorCode) { } UBool ReorderingBuffer::equals(const char16_t *otherStart, const char16_t *otherLimit) const { - int32_t length=(int32_t)(limit-start); + int32_t length = static_cast(limit - start); return - length==(int32_t)(otherLimit-otherStart) && + length == static_cast(otherLimit - otherStart) && 0==u_memcmp(start, otherStart, length); } UBool ReorderingBuffer::equals(const uint8_t *otherStart, const uint8_t *otherLimit) const { U_ASSERT((otherLimit - otherStart) <= INT32_MAX); // ensured by caller - int32_t length = (int32_t)(limit - start); - int32_t otherLength = (int32_t)(otherLimit - otherStart); + int32_t length = static_cast(limit - start); + int32_t otherLength = static_cast(otherLimit - otherStart); // For equal strings, UTF-8 is at least as long as UTF-16, and at most three times as long. if (otherLength < length || (otherLength / 3) > length) { return false; @@ -304,7 +304,7 @@ UBool ReorderingBuffer::appendZeroCC(UChar32 c, UErrorCode &errorCode) { } remainingCapacity-=cpLength; if(cpLength==1) { - *limit++=(char16_t)c; + *limit++ = static_cast(c); } else { limit[0]=U16_LEAD(c); limit[1]=U16_TRAIL(c); @@ -319,7 +319,7 @@ UBool ReorderingBuffer::appendZeroCC(const char16_t *s, const char16_t *sLimit, if(s==sLimit) { return true; } - int32_t length=(int32_t)(sLimit-s); + int32_t length = static_cast(sLimit - s); if(remainingCapacity(reorderStart - start); + int32_t length = static_cast(limit - start); str.releaseBuffer(length); int32_t newCapacity=length+appendLength; int32_t doubleCapacity=2*str.getCapacity(); @@ -485,7 +485,7 @@ Normalizer2Impl::addPropertyStarts(const USetAdder *sa, UErrorCode & /*errorCode while ((end = ucptrie_getRange(normTrie, start, UCPMAP_RANGE_FIXED_LEAD_SURROGATES, INERT, nullptr, nullptr, &value)) >= 0) { sa->add(sa->set, start); - if (start != end && isAlgorithmicNoNo((uint16_t)value) && + if (start != end && isAlgorithmicNoNo(static_cast(value)) && (value & Normalizer2Impl::DELTA_TCCC_MASK) > Normalizer2Impl::DELTA_TCCC_1) { // Range of code points with same-norm16-value algorithmic decompositions. // They might have different non-zero FCD16 values. @@ -569,7 +569,7 @@ Normalizer2Impl::decompose(const char16_t *src, const char16_t *limit, int32_t destLengthEstimate, UErrorCode &errorCode) const { if(destLengthEstimate<0 && limit!=nullptr) { - destLengthEstimate=(int32_t)(limit-src); + destLengthEstimate = static_cast(limit - src); } dest.remove(); ReorderingBuffer buffer(*this, dest); @@ -722,13 +722,13 @@ UBool Normalizer2Impl::decompose(UChar32 c, uint16_t norm16, uint16_t firstUnit=*mapping; int32_t length=firstUnit&MAPPING_LENGTH_MASK; uint8_t leadCC, trailCC; - trailCC=(uint8_t)(firstUnit>>8); + trailCC = static_cast(firstUnit >> 8); if(firstUnit&MAPPING_HAS_CCC_LCCC_WORD) { - leadCC=(uint8_t)(*(mapping-1)>>8); + leadCC = static_cast(*(mapping - 1) >> 8); } else { leadCC=0; } - return buffer.append((const char16_t *)mapping+1, length, true, leadCC, trailCC, errorCode); + return buffer.append(reinterpret_cast(mapping) + 1, length, true, leadCC, trailCC, errorCode); } // Dual functionality: @@ -922,17 +922,17 @@ Normalizer2Impl::decomposeShort(const uint8_t *src, const uint8_t *limit, const uint16_t *mapping = getData(norm16); uint16_t firstUnit = *mapping; int32_t length = firstUnit & MAPPING_LENGTH_MASK; - uint8_t trailCC = (uint8_t)(firstUnit >> 8); + uint8_t trailCC = static_cast(firstUnit >> 8); uint8_t leadCC; if (firstUnit & MAPPING_HAS_CCC_LCCC_WORD) { - leadCC = (uint8_t)(*(mapping-1) >> 8); + leadCC = static_cast(*(mapping - 1) >> 8); } else { leadCC = 0; } if (leadCC == 0 && stopAt == STOP_AT_DECOMP_BOUNDARY) { return prevSrc; } - if (!buffer.append((const char16_t *)mapping+1, length, true, leadCC, trailCC, errorCode)) { + if (!buffer.append(reinterpret_cast(mapping) + 1, length, true, leadCC, trailCC, errorCode)) { return nullptr; } } @@ -971,7 +971,7 @@ Normalizer2Impl::getDecomposition(UChar32 c, char16_t buffer[4], int32_t &length // c decomposes, get everything from the variable-length extra data const uint16_t *mapping=getData(norm16); length=*mapping&MAPPING_LENGTH_MASK; - return (const char16_t *)mapping+1; + return reinterpret_cast(mapping) + 1; } // The capacity of the buffer must be 30=MAPPING_LENGTH_MASK-1 @@ -1006,17 +1006,17 @@ Normalizer2Impl::getRawDecomposition(UChar32 c, char16_t buffer[30], int32_t &le uint16_t rm0=*rawMapping; if(rm0<=MAPPING_LENGTH_MASK) { length=rm0; - return (const char16_t *)rawMapping-rm0; + return reinterpret_cast(rawMapping) - rm0; } else { // Copy the normal mapping and replace its first two code units with rm0. - buffer[0]=(char16_t)rm0; - u_memcpy(buffer+1, (const char16_t *)mapping+1+2, mLength-2); + buffer[0] = static_cast(rm0); + u_memcpy(buffer + 1, reinterpret_cast(mapping) + 1 + 2, mLength - 2); length=mLength-1; return buffer; } } else { length=mLength; - return (const char16_t *)mapping+1; + return reinterpret_cast(mapping) + 1; } } @@ -1053,7 +1053,7 @@ void Normalizer2Impl::decomposeAndAppend(const char16_t *src, const char16_t *li limit=u_strchr(p, 0); } - if (buffer.append(src, (int32_t)(p - src), false, firstCC, prevCC, errorCode)) { + if (buffer.append(src, static_cast(p - src), false, firstCC, prevCC, errorCode)) { buffer.appendZeroCC(p, limit, errorCode); } } @@ -1142,13 +1142,13 @@ int32_t Normalizer2Impl::combine(const uint16_t *list, UChar32 trail) { if(trail(trail << 1); while(key1>(firstUnit=*list)) { list+=2+(firstUnit&COMP_1_TRIPLE); } if(key1==(firstUnit&COMP_1_TRAIL_MASK)) { if(firstUnit&COMP_1_TRIPLE) { - return ((int32_t)list[1]<<16)|list[2]; + return (static_cast(list[1]) << 16) | list[2]; } else { return list[1]; } @@ -1156,10 +1156,10 @@ int32_t Normalizer2Impl::combine(const uint16_t *list, UChar32 trail) { } else { // trail character is 3400..10FFFF // result entry has 3 units - key1=(uint16_t)(COMP_1_TRAIL_LIMIT+ + key1 = static_cast(COMP_1_TRAIL_LIMIT + (((trail>>COMP_1_TRAIL_SHIFT))& ~COMP_1_TRIPLE)); - uint16_t key2=(uint16_t)(trail<(trail << COMP_2_TRAIL_SHIFT); uint16_t secondUnit; for(;;) { if(key1>(firstUnit=*list)) { @@ -1172,7 +1172,7 @@ int32_t Normalizer2Impl::combine(const uint16_t *list, UChar32 trail) { list+=3; } } else if(key2==(secondUnit&COMP_2_TRAIL_MASK)) { - return ((int32_t)(secondUnit&~COMP_2_TRAIL_MASK)<<16)|list[2]; + return (static_cast(secondUnit & ~COMP_2_TRAIL_MASK) << 16) | list[2]; } else { break; } @@ -1197,7 +1197,7 @@ void Normalizer2Impl::addComposites(const uint16_t *list, UnicodeSet &set) const compositeAndFwd=list[1]; list+=2; } else { - compositeAndFwd=(((int32_t)list[1]&~COMP_2_TRAIL_MASK)<<16)|list[2]; + compositeAndFwd = ((static_cast(list[1]) & ~COMP_2_TRAIL_MASK) << 16) | list[2]; list+=3; } UChar32 composite=compositeAndFwd>>1; @@ -1254,15 +1254,15 @@ void Normalizer2Impl::recompose(ReorderingBuffer &buffer, int32_t recomposeStart // c is a Jamo V/T, see if we can compose it with the previous character. if(c(*starter - Hangul::JAMO_L_BASE); if(prev( + Hangul::HANGUL_BASE + (prev*Hangul::JAMO_V_COUNT+(c-Hangul::JAMO_V_BASE))* Hangul::JAMO_T_COUNT); char16_t t; - if(p!=limit && (t=(char16_t)(*p-Hangul::JAMO_T_BASE))(*p - Hangul::JAMO_T_BASE)) < Hangul::JAMO_T_COUNT) { ++p; syllable+=t; // The next character was a Jamo T. } @@ -1300,7 +1300,7 @@ void Normalizer2Impl::recompose(ReorderingBuffer &buffer, int32_t recomposeStart starter[0]=U16_LEAD(composite); starter[1]=U16_TRAIL(composite); } else { - *starter=(char16_t)composite; + *starter = static_cast(composite); // The composite is shorter than the starter, // move the intermediate characters forward one. starterIsSupplementary=false; @@ -1325,7 +1325,7 @@ void Normalizer2Impl::recompose(ReorderingBuffer &buffer, int32_t recomposeStart *--starter=U16_LEAD(composite); // undo the temporary increment } else { // both are on the BMP - *starter=(char16_t)composite; + *starter = static_cast(composite); } /* remove the combining mark by moving the following text over it */ @@ -1569,14 +1569,14 @@ Normalizer2Impl::compose(const char16_t *src, const char16_t *limit, if(c(prev - Hangul::JAMO_L_BASE); if(l(*src) - Hangul::JAMO_T_BASE)) && t < Hangul::JAMO_T_COUNT) { // The next character is a Jamo T. ++src; @@ -1594,7 +1594,7 @@ Normalizer2Impl::compose(const char16_t *src, const char16_t *limit, if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) { break; } - if(!buffer.appendBMP((char16_t)syllable, 0, errorCode)) { + if (!buffer.appendBMP(static_cast(syllable), 0, errorCode)) { break; } prevBoundary = src; @@ -1619,7 +1619,7 @@ Normalizer2Impl::compose(const char16_t *src, const char16_t *limit, if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) { break; } - if(!buffer.appendBMP((char16_t)syllable, 0, errorCode)) { + if (!buffer.appendBMP(static_cast(syllable), 0, errorCode)) { break; } prevBoundary = src; @@ -1854,11 +1854,11 @@ void Normalizer2Impl::composeAndAppend(const char16_t *src, const char16_t *limi if(src!=firstStarterInSrc) { const char16_t *lastStarterInDest=findPreviousCompBoundary(buffer.getStart(), buffer.getLimit(), onlyContiguous); - int32_t destSuffixLength=(int32_t)(buffer.getLimit()-lastStarterInDest); + int32_t destSuffixLength = static_cast(buffer.getLimit() - lastStarterInDest); UnicodeString middle(lastStarterInDest, destSuffixLength); buffer.removeSuffix(destSuffixLength); safeMiddle=middle; - middle.append(src, (int32_t)(firstStarterInSrc-src)); + middle.append(src, static_cast(firstStarterInSrc - src)); const char16_t *middleStart=middle.getBuffer(); compose(middleStart, middleStart+middle.length(), onlyContiguous, true, buffer, errorCode); @@ -1948,7 +1948,7 @@ Normalizer2Impl::composeUTF8(uint32_t options, UBool onlyContiguous, } const uint16_t *mapping = getDataForYesOrNo(norm16); int32_t length = *mapping++ & MAPPING_LENGTH_MASK; - if (!ByteSinkUtil::appendChange(prevSrc, src, (const char16_t *)mapping, length, + if (!ByteSinkUtil::appendChange(prevSrc, src, reinterpret_cast(mapping), length, *sink, edits, errorCode)) { break; } @@ -1967,7 +1967,7 @@ Normalizer2Impl::composeUTF8(uint32_t options, UBool onlyContiguous, break; } if (edits != nullptr) { - edits->addReplace((int32_t)(src - prevSrc), 0); + edits->addReplace(static_cast(src - prevSrc), 0); } prevBoundary = src; continue; @@ -1985,7 +1985,7 @@ Normalizer2Impl::composeUTF8(uint32_t options, UBool onlyContiguous, // The current character is a Jamo Vowel, // compose with previous Jamo L and following Jamo T. UChar32 l = prev - Hangul::JAMO_L_BASE; - if ((uint32_t)l < Hangul::JAMO_L_COUNT) { + if (static_cast(l) < Hangul::JAMO_L_COUNT) { if (sink == nullptr) { return false; } @@ -2213,20 +2213,20 @@ uint8_t Normalizer2Impl::getPreviousTrailCC(const char16_t *start, const char16_ if (start == p) { return 0; } - int32_t i = (int32_t)(p - start); + int32_t i = static_cast(p - start); UChar32 c; U16_PREV(start, 0, i, c); - return (uint8_t)getFCD16(c); + return static_cast(getFCD16(c)); } uint8_t Normalizer2Impl::getPreviousTrailCC(const uint8_t *start, const uint8_t *p) const { if (start == p) { return 0; } - int32_t i = (int32_t)(p - start); + int32_t i = static_cast(p - start); UChar32 c; U8_PREV(start, 0, i, c); - return (uint8_t)getFCD16(c); + return static_cast(getFCD16(c)); } // Note: normalizer2impl.cpp r30982 (2011-nov-27) @@ -2421,7 +2421,7 @@ Normalizer2Impl::makeFCD(const char16_t *src, const char16_t *limit, * already but is now going to be decomposed. * prevSrc is set to after what was copied/appended. */ - buffer->removeSuffix((int32_t)(prevSrc-prevBoundary)); + buffer->removeSuffix(static_cast(prevSrc - prevBoundary)); /* * Find the part of the source that needs to be decomposed, * up to the next safe boundary. @@ -2452,11 +2452,11 @@ void Normalizer2Impl::makeFCDAndAppend(const char16_t *src, const char16_t *limi if(src!=firstBoundaryInSrc) { const char16_t *lastBoundaryInDest=findPreviousFCDBoundary(buffer.getStart(), buffer.getLimit()); - int32_t destSuffixLength=(int32_t)(buffer.getLimit()-lastBoundaryInDest); + int32_t destSuffixLength = static_cast(buffer.getLimit() - lastBoundaryInDest); UnicodeString middle(lastBoundaryInDest, destSuffixLength); buffer.removeSuffix(destSuffixLength); safeMiddle=middle; - middle.append(src, (int32_t)(firstBoundaryInSrc-src)); + middle.append(src, static_cast(firstBoundaryInSrc - src)); const char16_t *middleStart=middle.getBuffer(); makeFCD(middleStart, middleStart+middle.length(), &buffer, errorCode); if(U_FAILURE(errorCode)) { @@ -2533,8 +2533,8 @@ void CanonIterData::addToStartSet(UChar32 origin, UChar32 decompLead, UErrorCode if(U_FAILURE(errorCode)) { return; } - UChar32 firstOrigin=(UChar32)(canonValue&CANON_VALUE_MASK); - canonValue=(canonValue&~CANON_VALUE_MASK)|CANON_HAS_SET|(uint32_t)canonStartSets.size(); + UChar32 firstOrigin = static_cast(canonValue & CANON_VALUE_MASK); + canonValue = (canonValue & ~CANON_VALUE_MASK) | CANON_HAS_SET | static_cast(canonStartSets.size()); umutablecptrie_set(mutableTrie, decompLead, canonValue, &errorCode); canonStartSets.adoptElement(lpSet.orphan(), errorCode); if (U_FAILURE(errorCode)) { @@ -2544,7 +2544,7 @@ void CanonIterData::addToStartSet(UChar32 origin, UChar32 decompLead, UErrorCode set->add(firstOrigin); } } else { - set=(UnicodeSet *)canonStartSets[(int32_t)(canonValue&CANON_VALUE_MASK)]; + set = static_cast(canonStartSets[static_cast(canonValue & CANON_VALUE_MASK)]); } set->add(origin); } @@ -2685,11 +2685,11 @@ UBool Normalizer2Impl::ensureCanonIterData(UErrorCode &errorCode) const { } int32_t Normalizer2Impl::getCanonValue(UChar32 c) const { - return (int32_t)ucptrie_get(fCanonIterData->trie, c); + return static_cast(ucptrie_get(fCanonIterData->trie, c)); } const UnicodeSet &Normalizer2Impl::getCanonStartSet(int32_t n) const { - return *(const UnicodeSet *)fCanonIterData->canonStartSets[n]; + return *static_cast(fCanonIterData->canonStartSets[n]); } UBool Normalizer2Impl::isCanonSegmentStarter(UChar32 c) const { @@ -2712,7 +2712,7 @@ UBool Normalizer2Impl::getCanonStartSet(UChar32 c, UnicodeSet &set) const { uint16_t norm16=getRawNorm16(c); if(norm16==JAMO_L) { UChar32 syllable= - (UChar32)(Hangul::HANGUL_BASE+(c-Hangul::JAMO_L_BASE)*Hangul::JAMO_VT_COUNT); + static_cast(Hangul::HANGUL_BASE + (c - Hangul::JAMO_L_BASE) * Hangul::JAMO_VT_COUNT); set.add(syllable, syllable+Hangul::JAMO_VT_COUNT-1); } else { addComposites(getCompositionsList(norm16), set); diff --git a/icu4c/source/common/normalizer2impl.h b/icu4c/source/common/normalizer2impl.h index c0ab9d1348bf..7bd733dee92e 100644 --- a/icu4c/source/common/normalizer2impl.h +++ b/icu4c/source/common/normalizer2impl.h @@ -81,10 +81,10 @@ class U_COMMON_API Hangul { return 0<=c && c(c - JAMO_L_BASE) < JAMO_L_COUNT; } static inline UBool isJamoV(UChar32 c) { - return (uint32_t)(c-JAMO_V_BASE)(c - JAMO_V_BASE) < JAMO_V_COUNT; } static inline UBool isJamoT(UChar32 c) { int32_t t=c-JAMO_T_BASE; @@ -103,12 +103,12 @@ class U_COMMON_API Hangul { c-=HANGUL_BASE; UChar32 c2=c%JAMO_T_COUNT; c/=JAMO_T_COUNT; - buffer[0]=(char16_t)(JAMO_L_BASE+c/JAMO_V_COUNT); - buffer[1]=(char16_t)(JAMO_V_BASE+c%JAMO_V_COUNT); + buffer[0] = static_cast(JAMO_L_BASE + c / JAMO_V_COUNT); + buffer[1] = static_cast(JAMO_V_BASE + c % JAMO_V_COUNT); if(c2==0) { return 2; } else { - buffer[2]=(char16_t)(JAMO_T_BASE+c2); + buffer[2] = static_cast(JAMO_T_BASE + c2); return 3; } } @@ -123,11 +123,11 @@ class U_COMMON_API Hangul { UChar32 c2=c%JAMO_T_COUNT; if(c2==0) { c/=JAMO_T_COUNT; - buffer[0]=(char16_t)(JAMO_L_BASE+c/JAMO_V_COUNT); - buffer[1]=(char16_t)(JAMO_V_BASE+c%JAMO_V_COUNT); + buffer[0] = static_cast(JAMO_L_BASE + c / JAMO_V_COUNT); + buffer[1] = static_cast(JAMO_V_BASE + c % JAMO_V_COUNT); } else { - buffer[0]=(char16_t)(orig-c2); // LV syllable - buffer[1]=(char16_t)(JAMO_T_BASE+c2); + buffer[0] = static_cast(orig - c2); // LV syllable + buffer[1] = static_cast(JAMO_T_BASE + c2); } } private: @@ -147,13 +147,13 @@ class U_COMMON_API ReorderingBuffer : public UMemory { ReorderingBuffer(const Normalizer2Impl &ni, UnicodeString &dest, UErrorCode &errorCode); ~ReorderingBuffer() { if (start != nullptr) { - str.releaseBuffer((int32_t)(limit-start)); + str.releaseBuffer(static_cast(limit - start)); } } UBool init(int32_t destCapacity, UErrorCode &errorCode); UBool isEmpty() const { return start==limit; } - int32_t length() const { return (int32_t)(limit-start); } + int32_t length() const { return static_cast(limit - start); } char16_t *getStart() { return start; } char16_t *getLimit() { return limit; } uint8_t getLastCC() const { return lastCC; } @@ -163,7 +163,7 @@ class U_COMMON_API ReorderingBuffer : public UMemory { UBool append(UChar32 c, uint8_t cc, UErrorCode &errorCode) { return (c<=0xffff) ? - appendBMP((char16_t)c, cc, errorCode) : + appendBMP(static_cast(c), cc, errorCode) : appendSupplementary(c, cc, errorCode); } UBool append(const char16_t *s, int32_t length, UBool isNFD, @@ -190,12 +190,12 @@ class U_COMMON_API ReorderingBuffer : public UMemory { void remove(); void removeSuffix(int32_t suffixLength); void setReorderingLimit(char16_t *newLimit) { - remainingCapacity+=(int32_t)(limit-newLimit); + remainingCapacity += static_cast(limit - newLimit); reorderStart=limit=newLimit; lastCC=0; } void copyReorderableSuffixTo(UnicodeString &s) const { - s.setTo(ConstChar16Ptr(reorderStart), (int32_t)(limit-reorderStart)); + s.setTo(ConstChar16Ptr(reorderStart), static_cast(limit - reorderStart)); } private: /* @@ -215,7 +215,7 @@ class U_COMMON_API ReorderingBuffer : public UMemory { void insert(UChar32 c, uint8_t cc); static void writeCodePoint(char16_t *p, UChar32 c) { if(c<=0xffff) { - *p=(char16_t)c; + *p = static_cast(c); } else { p[0]=U16_LEAD(c); p[1]=U16_TRAIL(c); @@ -291,7 +291,7 @@ class U_COMMON_API Normalizer2Impl : public UObject { return getCCFromNoNo(norm16); } static uint8_t getCCFromNormalYesOrMaybe(uint16_t norm16) { - return (uint8_t)(norm16 >> OFFSET_SHIFT); + return static_cast(norm16 >> OFFSET_SHIFT); } static uint8_t getCCFromYesOrMaybeYes(uint16_t norm16) { return norm16>=MIN_NORMAL_MAYBE_YES ? getCCFromNormalYesOrMaybe(norm16) : 0; @@ -364,7 +364,7 @@ class U_COMMON_API Normalizer2Impl : public UObject { // 0<=lead<=0xffff uint8_t bits=smallFCD[lead>>8]; if(bits==0) { return false; } - return (UBool)((bits>>((lead>>5)&7))&1); + return static_cast((bits >> ((lead >> 5) & 7)) & 1); } /** Returns the FCD value from the regular normalization data. */ uint16_t getFCD16FromNormData(UChar32 c) const; @@ -603,7 +603,7 @@ class U_COMMON_API Normalizer2Impl : public UObject { uint8_t getCCFromNoNo(uint16_t norm16) const { const uint16_t *mapping=getDataForYesOrNo(norm16); if(*mapping&MAPPING_HAS_CCC_LCCC_WORD) { - return (uint8_t)*(mapping-1); + return static_cast(*(mapping - 1)); } else { return 0; } @@ -614,7 +614,7 @@ class U_COMMON_API Normalizer2Impl : public UObject { return 0; // yesYes and Hangul LV have ccc=tccc=0 } else { // For Hangul LVT we harmlessly fetch a firstUnit with tccc=0 here. - return (uint8_t)(*getDataForYesOrNo(norm16)>>8); // tccc from yesNo + return static_cast(*getDataForYesOrNo(norm16) >> 8); // tccc from yesNo } } uint8_t getPreviousTrailCC(const char16_t *start, const char16_t *p) const; diff --git a/icu4c/source/common/patternprops.cpp b/icu4c/source/common/patternprops.cpp index 9922683cda57..19998574cc55 100644 --- a/icu4c/source/common/patternprops.cpp +++ b/icu4c/source/common/patternprops.cpp @@ -120,12 +120,12 @@ PatternProps::isSyntax(UChar32 c) { if(c<0) { return false; } else if(c<=0xff) { - return (UBool)(latin1[c]>>1)&1; + return static_cast(latin1[c] >> 1) & 1; } else if(c<0x2010) { return false; } else if(c<=0x3030) { uint32_t bits=syntax2000[index2000[(c-0x2000)>>5]]; - return (UBool)((bits>>(c&0x1f))&1); + return static_cast((bits >> (c & 0x1f)) & 1); } else if(0xfd3e<=c && c<=0xfe46) { return c<=0xfd3f || 0xfe45<=c; } else { @@ -138,12 +138,12 @@ PatternProps::isSyntaxOrWhiteSpace(UChar32 c) { if(c<0) { return false; } else if(c<=0xff) { - return (UBool)(latin1[c]&1); + return static_cast(latin1[c] & 1); } else if(c<0x200e) { return false; } else if(c<=0x3030) { uint32_t bits=syntaxOrWhiteSpace2000[index2000[(c-0x2000)>>5]]; - return (UBool)((bits>>(c&0x1f))&1); + return static_cast((bits >> (c & 0x1f)) & 1); } else if(0xfd3e<=c && c<=0xfe46) { return c<=0xfd3f || 0xfe45<=c; } else { @@ -156,7 +156,7 @@ PatternProps::isWhiteSpace(UChar32 c) { if(c<0) { return false; } else if(c<=0xff) { - return (UBool)(latin1[c]>>2)&1; + return static_cast(latin1[c] >> 2) & 1; } else if(0x200e<=c && c<=0x2029) { return c<=0x200f || 0x2028<=c; } else { diff --git a/icu4c/source/common/propname.cpp b/icu4c/source/common/propname.cpp index 45062bfbd931..640578c5ee37 100644 --- a/icu4c/source/common/propname.cpp +++ b/icu4c/source/common/propname.cpp @@ -43,7 +43,7 @@ getASCIIPropertyNameChar(const char *name) { ) {} if(c!=0) { - return (i<<8)|(uint8_t)uprv_asciitolower((char)c); + return (i << 8) | static_cast(uprv_asciitolower(c)); } else { return i<<8; } @@ -66,7 +66,7 @@ getEBCDICPropertyNameChar(const char *name) { ) {} if(c!=0) { - return (i<<8)|(uint8_t)uprv_ebcdictolower((char)c); + return (i << 8) | static_cast(uprv_ebcdictolower(c)); } else { return i<<8; } @@ -231,7 +231,7 @@ UBool PropNameData::containsName(BytesTrie &trie, const char *name) { if(!USTRINGTRIE_HAS_NEXT(result)) { return false; } - result=trie.next((uint8_t)c); + result = trie.next(static_cast(c)); } return USTRINGTRIE_HAS_VALUE(result); } diff --git a/icu4c/source/common/propsvec.cpp b/icu4c/source/common/propsvec.cpp index 18cc3e8cd8e8..11ef8df575b6 100644 --- a/icu4c/source/common/propsvec.cpp +++ b/icu4c/source/common/propsvec.cpp @@ -102,29 +102,29 @@ _findRow(UPropsVectors *pv, UChar32 rangeStart) { /* check the vicinity of the last-seen row (start searching with an unrolled loop) */ row=pv->v+prevRow*columns; - if(rangeStart>=(UChar32)row[0]) { - if(rangeStart<(UChar32)row[1]) { + if (rangeStart >= static_cast(row[0])) { + if (rangeStart < static_cast(row[1])) { /* same row as last seen */ return row; - } else if(rangeStart<(UChar32)(row+=columns)[1]) { + } else if (rangeStart < static_cast((row += columns)[1])) { /* next row after the last one */ pv->prevRow=prevRow+1; return row; - } else if(rangeStart<(UChar32)(row+=columns)[1]) { + } else if (rangeStart < static_cast((row += columns)[1])) { /* second row after the last one */ pv->prevRow=prevRow+2; return row; - } else if((rangeStart-(UChar32)row[1])<10) { + } else if ((rangeStart - static_cast(row[1])) < 10) { /* we are close, continue looping */ prevRow+=2; do { ++prevRow; row+=columns; - } while(rangeStart>=(UChar32)row[1]); + } while (rangeStart >= static_cast(row[1])); pv->prevRow=prevRow; return row; } - } else if(rangeStart<(UChar32)pv->v[1]) { + } else if (rangeStart < static_cast(pv->v[1])) { /* the very first row */ pv->prevRow=0; return pv->v; @@ -135,9 +135,9 @@ _findRow(UPropsVectors *pv, UChar32 rangeStart) { while(startv+i*columns; - if(rangeStart<(UChar32)row[0]) { + if (rangeStart < static_cast(row[0])) { limit=i; - } else if(rangeStart<(UChar32)row[1]) { + } else if (rangeStart < static_cast(row[1])) { pv->prevRow=i; return row; } else { @@ -312,8 +312,8 @@ upvec_getRow(const UPropsVectors *pv, int32_t rowIndex, static int32_t U_CALLCONV upvec_compareRows(const void *context, const void *l, const void *r) { - const uint32_t *left=(const uint32_t *)l, *right=(const uint32_t *)r; - const UPropsVectors *pv=(const UPropsVectors *)context; + const uint32_t* left = static_cast(l), *right = static_cast(r); + const UPropsVectors* pv = static_cast(context); int32_t i, count, columns; count=columns=pv->columns; /* includes start/limit columns */ diff --git a/icu4c/source/common/punycode.cpp b/icu4c/source/common/punycode.cpp index 7ebdebc1888a..742d48de18b1 100644 --- a/icu4c/source/common/punycode.cpp +++ b/icu4c/source/common/punycode.cpp @@ -97,12 +97,12 @@ digitToBasic(int32_t digit, UBool uppercase) { /* 26..35 map to ASCII 0..9 */ if(digit<26) { if(uppercase) { - return (char)(_CAPITAL_A+digit); + return static_cast(_CAPITAL_A + digit); } else { - return (char)(_SMALL_A+digit); + return static_cast(_SMALL_A + digit); } } else { - return (char)((_ZERO_-26)+digit); + return static_cast((_ZERO_ - 26) + digit); } } @@ -421,7 +421,7 @@ u_strFromPunycode(const char16_t *src, int32_t srcLength, } if(j(INT64_C(0x7FF8000000000000))}; +static const BitPatternConversion gInf = {static_cast(INT64_C(0x7FF0000000000000))}; /*--------------------------------------------------------------------------- Platform utilities @@ -225,7 +225,7 @@ u_signBit(double d) { #if U_IS_BIG_ENDIAN hiByte = *(uint8_t *)&d; #else - hiByte = *(((uint8_t *)&d) + sizeof(double) - 1); + hiByte = *(reinterpret_cast(&d) + sizeof(double) - 1); #endif return (hiByte & 0x80) != 0; } @@ -744,7 +744,7 @@ static UBool isValidOlsonID(const char *id) { The timezone is sometimes set to "CST-7CDT", "CST6CDT5,J129,J131/19:30", "GRNLNDST3GRNLNDDT" or similar, so we cannot use it. The rest of the time it could be an Olson ID. George */ - return (UBool)(id[idx] == 0 + return static_cast(id[idx] == 0 || uprv_strcmp(id, "PST8PDT") == 0 || uprv_strcmp(id, "MST7MDT") == 0 || uprv_strcmp(id, "CST6CDT") == 0 @@ -927,7 +927,7 @@ static UBool compareBinaryFiles(const char* defaultTZFileName, const char* TZFil */ if (tzInfo->defaultTZBuffer == nullptr) { rewind(tzInfo->defaultTZFilePtr); - tzInfo->defaultTZBuffer = (char*)uprv_malloc(sizeof(char) * tzInfo->defaultTZFileSize); + tzInfo->defaultTZBuffer = static_cast(uprv_malloc(sizeof(char) * tzInfo->defaultTZFileSize)); sizeFileRead = fread(tzInfo->defaultTZBuffer, 1, tzInfo->defaultTZFileSize, tzInfo->defaultTZFilePtr); } rewind(file); diff --git a/icu4c/source/common/putilimp.h b/icu4c/source/common/putilimp.h index 5b95a68418c4..6fe02ff8d289 100644 --- a/icu4c/source/common/putilimp.h +++ b/icu4c/source/common/putilimp.h @@ -553,7 +553,7 @@ inline int32_t pinCapacity(T *dest, int32_t capacity) { if (maxInt < destInt) { // Less than 2GB to the end of the address space. // Pin to that to prevent address overflow. - maxInt = (uintptr_t)-1; + maxInt = static_cast(-1); } # endif diff --git a/icu4c/source/common/rbbi.cpp b/icu4c/source/common/rbbi.cpp index 9c4141022c35..069af2153711 100644 --- a/icu4c/source/common/rbbi.cpp +++ b/icu4c/source/common/rbbi.cpp @@ -110,7 +110,7 @@ RuleBasedBreakIterator::RuleBasedBreakIterator(const uint8_t *compiledRules, status = U_ILLEGAL_ARGUMENT_ERROR; return; } - const RBBIDataHeader *data = (const RBBIDataHeader *)compiledRules; + const RBBIDataHeader* data = reinterpret_cast(compiledRules); if (data->fLength > ruleLength) { status = U_ILLEGAL_ARGUMENT_ERROR; return; @@ -553,7 +553,7 @@ int32_t RuleBasedBreakIterator::first() { * @return The text's past-the-end offset. */ int32_t RuleBasedBreakIterator::last() { - int32_t endPos = (int32_t)utext_nativeLength(&fText); + int32_t endPos = static_cast(utext_nativeLength(&fText)); UBool endShouldBeBoundary = isBoundary(endPos); // Has side effect of setting iterator position. (void)endShouldBeBoundary; U_ASSERT(endShouldBeBoundary); @@ -625,7 +625,7 @@ int32_t RuleBasedBreakIterator::following(int32_t startPos) { // Move requested offset to a code point start. It might be on a trail surrogate, // or on a trail byte if the input is UTF-8. Or it may be beyond the end of the text. utext_setNativeIndex(&fText, startPos); - startPos = (int32_t)utext_getNativeIndex(&fText); + startPos = static_cast(utext_getNativeIndex(&fText)); UErrorCode status = U_ZERO_ERROR; fBreakCache->following(startPos, status); @@ -881,7 +881,7 @@ int32_t RuleBasedBreakIterator::handleNext() { if (accepting == ACCEPTING_UNCONDITIONAL) { // Match found, common case. if (mode != RBBI_START) { - result = (int32_t)UTEXT_GETNATIVEINDEX(&fText); + result = static_cast(UTEXT_GETNATIVEINDEX(&fText)); } fRuleStatusIndex = row->fTagsIdx; // Remember the break status (tag) values. } else if (accepting > ACCEPTING_UNCONDITIONAL) { @@ -905,7 +905,7 @@ int32_t RuleBasedBreakIterator::handleNext() { U_ASSERT(rule == 0 || rule > ACCEPTING_UNCONDITIONAL); U_ASSERT(rule == 0 || rule < fData->fForwardTable->fLookAheadResultsSize); if (rule > ACCEPTING_UNCONDITIONAL) { - int32_t pos = (int32_t)UTEXT_GETNATIVEINDEX(&fText); + int32_t pos = static_cast(UTEXT_GETNATIVEINDEX(&fText)); fLookAheadMatches[rule] = pos; } @@ -937,7 +937,7 @@ int32_t RuleBasedBreakIterator::handleNext() { if (result == initialPosition) { utext_setNativeIndex(&fText, initialPosition); utext_next32(&fText); - result = (int32_t)utext_getNativeIndex(&fText); + result = static_cast(utext_getNativeIndex(&fText)); fRuleStatusIndex = 0; } @@ -1027,7 +1027,7 @@ int32_t RuleBasedBreakIterator::handleSafePrevious(int32_t fromPosition) { } // The state machine is done. Check whether it found a match... - result = (int32_t)UTEXT_GETNATIVEINDEX(&fText); + result = static_cast(UTEXT_GETNATIVEINDEX(&fText)); #ifdef RBBI_DEBUG if (gTrace) { RBBIDebugPrintf("result = %d\n\n", result); @@ -1091,7 +1091,7 @@ const uint8_t *RuleBasedBreakIterator::getBinaryRules(uint32_t &length) { length = 0; if (fData != nullptr) { - retPtr = (const uint8_t *)fData->fHeader; + retPtr = reinterpret_cast(fData->fHeader); length = fData->fHeader->fLength; } return retPtr; @@ -1187,7 +1187,7 @@ getLanguageBreakEngineFromFactory(UChar32 c, const char* locale) int32_t i = gLanguageBreakFactories->size(); const LanguageBreakEngine *lbe = nullptr; while (--i >= 0) { - LanguageBreakFactory *factory = (LanguageBreakFactory *)(gLanguageBreakFactories->elementAt(i)); + LanguageBreakFactory* factory = static_cast(gLanguageBreakFactories->elementAt(i)); lbe = factory->getEngineFor(c, locale); if (lbe != nullptr) { break; @@ -1219,7 +1219,7 @@ RuleBasedBreakIterator::getLanguageBreakEngine(UChar32 c, const char* locale) { int32_t i = fLanguageBreakEngines->size(); while (--i >= 0) { - lbe = (const LanguageBreakEngine *)(fLanguageBreakEngines->elementAt(i)); + lbe = static_cast(fLanguageBreakEngines->elementAt(i)); if (lbe->handles(c, locale)) { return lbe; } diff --git a/icu4c/source/common/rbbi_cache.cpp b/icu4c/source/common/rbbi_cache.cpp index 239345998bc4..3ef030cb9195 100644 --- a/icu4c/source/common/rbbi_cache.cpp +++ b/icu4c/source/common/rbbi_cache.cpp @@ -146,7 +146,7 @@ void RuleBasedBreakIterator::DictionaryCache::populateDictionary(int32_t startPo uint32_t dictStart = fBI->fData->fForwardTable->fDictCategoriesStart; while(U_SUCCESS(status)) { - while((current = (int32_t)UTEXT_GETNATIVEINDEX(text)) < rangeEnd + while ((current = static_cast(UTEXT_GETNATIVEINDEX(text))) < rangeEnd && (category < dictStart)) { utext_next32(text); // TODO: cleaner loop structure. c = utext_current32(text); @@ -221,7 +221,7 @@ void RuleBasedBreakIterator::BreakCache::reset(int32_t pos, int32_t ruleStatus) fTextIdx = pos; fBufIdx = 0; fBoundaries[0] = pos; - fStatuses[0] = (uint16_t)ruleStatus; + fStatuses[0] = static_cast(ruleStatus); } diff --git a/icu4c/source/common/rbbidata.cpp b/icu4c/source/common/rbbidata.cpp index 49603b619345..edfa1bf0d85e 100644 --- a/icu4c/source/common/rbbidata.cpp +++ b/icu4c/source/common/rbbidata.cpp @@ -104,10 +104,10 @@ void RBBIDataWrapper::init(const RBBIDataHeader *data, UErrorCode &status) { fDontFreeData = false; if (data->fFTableLen != 0) { - fForwardTable = (RBBIStateTable *)((char *)data + fHeader->fFTable); + fForwardTable = reinterpret_cast(reinterpret_cast(data) + fHeader->fFTable); } if (data->fRTableLen != 0) { - fReverseTable = (RBBIStateTable *)((char *)data + fHeader->fRTable); + fReverseTable = reinterpret_cast(reinterpret_cast(data) + fHeader->fRTable); } fTrie = ucptrie_openFromBinary(UCPTRIE_TYPE_FAST, @@ -130,7 +130,7 @@ void RBBIDataWrapper::init(const RBBIDataHeader *data, UErrorCode &status) { fRuleString = UnicodeString::fromUTF8(StringPiece(fRuleSource, fHeader->fRuleSourceLen)); U_ASSERT(data->fRuleSourceLen > 0); - fRuleStatusTable = (int32_t *)((char *)data + fHeader->fStatusTable); + fRuleStatusTable = reinterpret_cast(reinterpret_cast(data) + fHeader->fStatusTable); fStatusMaxIdx = data->fStatusTableLen / sizeof(int32_t); fRefCount = 1; diff --git a/icu4c/source/common/rbbirb.cpp b/icu4c/source/common/rbbirb.cpp index 1b2ee67187b5..5e015c9b271e 100644 --- a/icu4c/source/common/rbbirb.cpp +++ b/icu4c/source/common/rbbirb.cpp @@ -103,7 +103,7 @@ RBBIRuleBuilder::~RBBIRuleBuilder() { int i; for (i=0; ; i++) { - RBBINode *n = (RBBINode *)fUSetNodes->elementAt(i); + RBBINode* n = static_cast(fUSetNodes->elementAt(i)); if (n==nullptr) { break; } @@ -182,7 +182,7 @@ RBBIDataHeader *RBBIRuleBuilder::flattenData() { } #endif - RBBIDataHeader *data = (RBBIDataHeader *)uprv_malloc(totalSize); + RBBIDataHeader* data = static_cast(uprv_malloc(totalSize)); if (data == nullptr) { *fStatus = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -213,16 +213,16 @@ RBBIDataHeader *RBBIRuleBuilder::flattenData() { uprv_memset(data->fReserved, 0, sizeof(data->fReserved)); - fForwardTable->exportTable((uint8_t *)data + data->fFTable); - fForwardTable->exportSafeTable((uint8_t *)data + data->fRTable); - fSetBuilder->serializeTrie ((uint8_t *)data + data->fTrie); + fForwardTable->exportTable(reinterpret_cast(data) + data->fFTable); + fForwardTable->exportSafeTable(reinterpret_cast(data) + data->fRTable); + fSetBuilder->serializeTrie(reinterpret_cast(data) + data->fTrie); - int32_t *ruleStatusTable = (int32_t *)((uint8_t *)data + data->fStatusTable); + int32_t* ruleStatusTable = reinterpret_cast(reinterpret_cast(data) + data->fStatusTable); for (i=0; isize(); i++) { ruleStatusTable[i] = fRuleStatusVals->elementAti(i); } - u_strToUTF8WithSub((char *)data+data->fRuleSource, rulesSize, &rulesLengthInUTF8, + u_strToUTF8WithSub(reinterpret_cast(data) + data->fRuleSource, rulesSize, &rulesLengthInUTF8, fStrippedRules.getBuffer(), fStrippedRules.length(), 0xfffd, nullptr, fStatus); if (U_FAILURE(*fStatus)) { diff --git a/icu4c/source/common/rbbiscan.cpp b/icu4c/source/common/rbbiscan.cpp index f5fdba076f02..cf2d63cd807b 100644 --- a/icu4c/source/common/rbbiscan.cpp +++ b/icu4c/source/common/rbbiscan.cpp @@ -748,7 +748,7 @@ void RBBIRuleScanner::findSetFor(const UnicodeString &s, RBBINode *node, Unicode // First check whether we've already cached a set for this string. // If so, just use the cached set in the new node. // delete any set provided by the caller, since we own it. - el = (RBBISetTableEl *)uhash_get(fSetTable, &s); + el = static_cast(uhash_get(fSetTable, &s)); if (el != nullptr) { delete setToAdopt; node->fLeftChild = el->val; @@ -794,7 +794,7 @@ void RBBIRuleScanner::findSetFor(const UnicodeString &s, RBBINode *node, Unicode // // Add the new set to the set hash table. // - el = (RBBISetTableEl *)uprv_malloc(sizeof(RBBISetTableEl)); + el = static_cast(uprv_malloc(sizeof(RBBISetTableEl))); UnicodeString *tkey = new UnicodeString(s); if (tkey == nullptr || el == nullptr || setToAdopt == nullptr) { // Delete to avoid memory leak @@ -864,7 +864,7 @@ UChar32 RBBIRuleScanner::nextCharLL() { UChar32 ch; if (fNextIndex >= fRB->fRules.length()) { - return (UChar32)-1; + return static_cast(-1); } ch = fRB->fRules.char32At(fNextIndex); if (U_IS_SURROGATE(ch)) { @@ -939,7 +939,7 @@ void RBBIRuleScanner::nextChar(RBBIRuleChar &c) { } } - if (c.fChar == (UChar32)-1) { + if (c.fChar == static_cast(-1)) { return; } if (fQuoteMode) { @@ -958,7 +958,7 @@ void RBBIRuleScanner::nextChar(RBBIRuleChar &c) { int32_t commentStart = fScanIndex; for (;;) { c.fChar = nextCharLL(); - if (c.fChar == (UChar32)-1 || // EOF + if (c.fChar == static_cast(-1) || // EOF c.fChar == chCR || c.fChar == chLF || c.fChar == chNEL || @@ -968,7 +968,7 @@ void RBBIRuleScanner::nextChar(RBBIRuleChar &c) { fRB->fStrippedRules.setCharAt(i, u' '); } } - if (c.fChar == (UChar32)-1) { + if (c.fChar == static_cast(-1)) { return; } @@ -1065,14 +1065,14 @@ void RBBIRuleScanner::parse() { // Table row specified "escaped P" and the char is either 'p' or 'P'. break; } - if (tableEl->fCharClass == 252 && fC.fChar == (UChar32)-1) { + if (tableEl->fCharClass == 252 && fC.fChar == static_cast(-1)) { // Table row specified eof and we hit eof on the input. break; } if (tableEl->fCharClass >= 128 && tableEl->fCharClass < 240 && // Table specs a char class && fC.fEscaped == false && // char is not escaped && - fC.fChar != (UChar32)-1) { // char is not EOF + fC.fChar != static_cast(-1)) { // char is not EOF U_ASSERT((tableEl->fCharClass-128) < UPRV_LENGTHOF(fRuleSets)); if (fRuleSets[tableEl->fCharClass-128].contains(fC.fChar)) { // Table row specified a character class, or set of characters, @@ -1090,7 +1090,7 @@ void RBBIRuleScanner::parse() { // We've found the row of the state table that matches the current input // character from the rules string. // Perform any action specified by this row in the state table. - if (doParseActions((int32_t)tableEl->fAction) == false) { + if (doParseActions(static_cast(tableEl->fAction)) == false) { // Break out of the state machine loop if the // the action signalled some kind of error, or // the action was to exit, occurs on normal end-of-rules-input. diff --git a/icu4c/source/common/rbbisetb.cpp b/icu4c/source/common/rbbisetb.cpp index e6c72954bc3b..6c22cf470f8b 100644 --- a/icu4c/source/common/rbbisetb.cpp +++ b/icu4c/source/common/rbbisetb.cpp @@ -120,7 +120,7 @@ void RBBISetBuilder::buildRanges() { // int ni; for (ni=0; ; ni++) { // Loop over each of the UnicodeSets encountered in the input rules - usetNode = (RBBINode *)this->fRB->fUSetNodes->elementAt(ni); + usetNode = static_cast(this->fRB->fUSetNodes->elementAt(ni)); if (usetNode==nullptr) { break; } @@ -251,7 +251,7 @@ void RBBISetBuilder::buildRanges() { UnicodeString eofString(u"eof"); UnicodeString bofString(u"bof"); for (ni=0; ; ni++) { // Loop over each of the UnicodeSets encountered in the input rules - usetNode = (RBBINode *)this->fRB->fUSetNodes->elementAt(ni); + usetNode = static_cast(this->fRB->fUSetNodes->elementAt(ni)); if (usetNode==nullptr) { break; } @@ -369,7 +369,7 @@ void RBBISetBuilder::addValToSets(UVector *sets, uint32_t val) { int32_t ix; for (ix=0; ixsize(); ix++) { - RBBINode *usetNode = (RBBINode *)sets->elementAt(ix); + RBBINode* usetNode = static_cast(sets->elementAt(ix)); addValToSet(usetNode, val); } } @@ -380,7 +380,7 @@ void RBBISetBuilder::addValToSet(RBBINode *usetNode, uint32_t val) { *fStatus = U_MEMORY_ALLOCATION_ERROR; return; } - leafNode->fVal = (unsigned short)val; + leafNode->fVal = static_cast(val); if (usetNode->fLeftChild == nullptr) { usetNode->fLeftChild = leafNode; leafNode->fParent = usetNode; @@ -441,7 +441,7 @@ UBool RBBISetBuilder::sawBOF() const { //------------------------------------------------------------------------ UChar32 RBBISetBuilder::getFirstChar(int32_t category) const { RangeDescriptor *rlRange; - UChar32 retVal = (UChar32)-1; + UChar32 retVal = static_cast(-1); for (rlRange = fRangeList; rlRange!=nullptr; rlRange=rlRange->fNext) { if (rlRange->fNum == category) { retVal = rlRange->fStartChar; @@ -674,7 +674,7 @@ void RangeDescriptor::split(UChar32 where, UErrorCode &status) { bool RangeDescriptor::isDictionaryRange() { static const char16_t *dictionary = u"dictionary"; for (int32_t i=0; isize(); i++) { - RBBINode *usetNode = (RBBINode *)fIncludesSets->elementAt(i); + RBBINode* usetNode = static_cast(fIncludesSets->elementAt(i)); RBBINode *setRef = usetNode->fParent; if (setRef != nullptr) { RBBINode *varRef = setRef->fParent; diff --git a/icu4c/source/common/rbbistbl.cpp b/icu4c/source/common/rbbistbl.cpp index bfaacf64254f..27f31a9d552c 100644 --- a/icu4c/source/common/rbbistbl.cpp +++ b/icu4c/source/common/rbbistbl.cpp @@ -41,7 +41,7 @@ U_CDECL_END U_NAMESPACE_BEGIN RBBISymbolTable::RBBISymbolTable(RBBIRuleScanner *rs, const UnicodeString &rules, UErrorCode &status) - :fRules(rules), fRuleScanner(rs), ffffString(char16_t(0xffff)) + : fRules(rules), fRuleScanner(rs), ffffString(static_cast(0xffff)) { fHashTable = nullptr; fCachedSetLookup = nullptr; @@ -76,9 +76,9 @@ const UnicodeString *RBBISymbolTable::lookup(const UnicodeString& s) const RBBINode *exprNode; RBBINode *usetNode; const UnicodeString *retString; - RBBISymbolTable *This = (RBBISymbolTable *)this; // cast off const + RBBISymbolTable *This = const_cast(this); // cast off const - el = (RBBISymbolTableEntry *)uhash_get(fHashTable, &s); + el = static_cast(uhash_get(fHashTable, &s)); if (el == nullptr) { return nullptr; } @@ -119,7 +119,7 @@ const UnicodeString *RBBISymbolTable::lookup(const UnicodeString& s) const const UnicodeFunctor *RBBISymbolTable::lookupMatcher(UChar32 ch) const { UnicodeSet *retVal = nullptr; - RBBISymbolTable *This = (RBBISymbolTable *)this; // cast off const + RBBISymbolTable *This = const_cast(this); // cast off const if (ch == 0xffff) { retVal = fCachedSetLookup; This->fCachedSetLookup = nullptr; @@ -170,7 +170,7 @@ RBBINode *RBBISymbolTable::lookupNode(const UnicodeString &key) const{ RBBINode *retNode = nullptr; RBBISymbolTableEntry *el; - el = (RBBISymbolTableEntry *)uhash_get(fHashTable, &key); + el = static_cast(uhash_get(fHashTable, &key)); if (el != nullptr) { retNode = el->val; } @@ -190,7 +190,7 @@ void RBBISymbolTable::addEntry (const UnicodeString &key, RBBINode * if (U_FAILURE(err)) { return; } - e = (RBBISymbolTableEntry *)uhash_get(fHashTable, &key); + e = static_cast(uhash_get(fHashTable, &key)); if (e != nullptr) { err = U_BRK_VARIABLE_REDFINITION; return; diff --git a/icu4c/source/common/rbbitblb.cpp b/icu4c/source/common/rbbitblb.cpp index 96a0b0338ded..4d95137601ef 100644 --- a/icu4c/source/common/rbbitblb.cpp +++ b/icu4c/source/common/rbbitblb.cpp @@ -51,7 +51,7 @@ RBBITableBuilder::RBBITableBuilder(RBBIRuleBuilder *rb, RBBINode **rootNode, UEr RBBITableBuilder::~RBBITableBuilder() { int i; for (i=0; isize(); i++) { - delete (RBBIStateDescriptor *)fDStates->elementAt(i); + delete static_cast(fDStates->elementAt(i)); } delete fDStates; delete fSafeTable; @@ -361,8 +361,8 @@ void RBBITableBuilder::calcFollowPos(RBBINode *n) { UVector *LastPosOfLeftChild = n->fLeftChild->fLastPosSet; - for (ix=0; ix<(uint32_t)LastPosOfLeftChild->size(); ix++) { - i = (RBBINode *)LastPosOfLeftChild->elementAt(ix); + for (ix = 0; ix < static_cast(LastPosOfLeftChild->size()); ix++) { + i = static_cast(LastPosOfLeftChild->elementAt(ix)); setAdd(i->fFollowPos, n->fRightChild->fFirstPosSet); } } @@ -373,8 +373,8 @@ void RBBITableBuilder::calcFollowPos(RBBINode *n) { RBBINode *i; // again, n and i are the names from Aho's description. uint32_t ix; - for (ix=0; ix<(uint32_t)n->fLastPosSet->size(); ix++) { - i = (RBBINode *)n->fLastPosSet->elementAt(ix); + for (ix = 0; ix < static_cast(n->fLastPosSet->size()); ix++) { + i = static_cast(n->fLastPosSet->elementAt(ix)); setAdd(i->fFollowPos, n->fFirstPosSet); } } @@ -445,7 +445,7 @@ void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree, RBBINode *endMarkNod int32_t startNodeIx; for (endNodeIx=0; endNodeIx(leafNodes.elementAt(endNodeIx)); // Identify leaf nodes that correspond to overall rule match positions. // These include the endMarkNode in their followPos sets. @@ -465,7 +465,7 @@ void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree, RBBINode *endMarkNod // with the same char class as our ending node. RBBINode *startNode; for (startNodeIx = 0; startNodeIx(matchStartNodes.elementAt(startNodeIx)); if (startNode->fType != RBBINode::leafChar) { continue; } @@ -525,7 +525,7 @@ void RBBITableBuilder::bofFixup() { RBBINode *startNode; int startNodeIx; for (startNodeIx = 0; startNodeIxsize(); startNodeIx++) { - startNode = (RBBINode *)matchStartNodes->elementAt(startNodeIx); + startNode = static_cast(matchStartNodes->elementAt(startNodeIx)); if (startNode->fType != RBBINode::leafChar) { continue; } @@ -605,7 +605,7 @@ void RBBITableBuilder::buildStateTable() { int32_t tx; for (tx=1; txsize(); tx++) { RBBIStateDescriptor *temp; - temp = (RBBIStateDescriptor *)fDStates->elementAt(tx); + temp = static_cast(fDStates->elementAt(tx)); if (temp->fMarked == false) { T = temp; break; @@ -628,7 +628,7 @@ void RBBITableBuilder::buildStateTable() { RBBINode *p; int32_t px; for (px=0; pxfPositions->size(); px++) { - p = (RBBINode *)T->fPositions->elementAt(px); + p = static_cast(T->fPositions->elementAt(px)); if ((p->fType == RBBINode::leafChar) && (p->fVal == a)) { if (U == nullptr) { U = new UVector(*fStatus); @@ -649,7 +649,7 @@ void RBBITableBuilder::buildStateTable() { int ix; for (ix=0; ixsize(); ix++) { RBBIStateDescriptor *temp2; - temp2 = (RBBIStateDescriptor *)fDStates->elementAt(ix); + temp2 = static_cast(fDStates->elementAt(ix)); if (setEquals(U, temp2->fPositions)) { delete U; U = temp2->fPositions; @@ -705,7 +705,7 @@ void RBBITableBuilder::mapLookAheadRules() { fLookAheadRuleMap->setSize(fRB->fScanner->numRules() + 1); for (int32_t n=0; nsize(); n++) { - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(n)); int32_t laSlotForState = 0; // Establish the look-ahead slot for this state, if the state covers @@ -789,9 +789,9 @@ void RBBITableBuilder::flagAcceptingStates() { } for (i=0; i(endMarkerNodes.elementAt(i)); for (n=0; nsize(); n++) { - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(n)); if (sd->fPositions->indexOf(endMarker) >= 0) { // Any non-zero value for fAccepting means this is an accepting node. // The value is what will be returned to the user as the break status. @@ -837,11 +837,11 @@ void RBBITableBuilder::flagLookAheadStates() { return; } for (i=0; i(lookAheadNodes.elementAt(i)); U_ASSERT(lookAheadNode->fType == RBBINode::NodeType::lookAhead); for (n=0; nsize(); n++) { - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(n)); int32_t positionsIdx = sd->fPositions->indexOf(lookAheadNode); if (positionsIdx >= 0) { U_ASSERT(lookAheadNode == sd->fPositions->elementAt(positionsIdx)); @@ -882,10 +882,10 @@ void RBBITableBuilder::flagTaggedStates() { return; } for (i=0; i(tagNodes.elementAt(i)); for (n=0; nsize(); n++) { // For each state s (row in the state table) - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(n)); if (sd->fPositions->indexOf(tagNode) >= 0) { // if s include the tag node t sortedAdd(&sd->fTagVals, tagNode->fVal); } @@ -923,12 +923,12 @@ void RBBITableBuilder::mergeRuleStatusVals() { // We will need this as a default, for rule sets with no explicit tagging. if (fRB->fRuleStatusVals->size() == 0) { fRB->fRuleStatusVals->addElement(1, *fStatus); // Num of statuses in group - fRB->fRuleStatusVals->addElement((int32_t)0, *fStatus); // and our single status of zero + fRB->fRuleStatusVals->addElement(static_cast(0), *fStatus); // and our single status of zero } // For each state for (n=0; nsize(); n++) { - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(n)); UVector *thisStatesTagValues = sd->fTagVals; if (thisStatesTagValues == nullptr) { // No tag values are explicitly associated with this state. @@ -1154,9 +1154,9 @@ bool RBBITableBuilder::findDuplCharClassFrom(IntPair *categories) { uint16_t table_base = 0; uint16_t table_dupl = 1; for (int32_t state=0; stateelementAt(state); - table_base = (uint16_t)sd->fDtran->elementAti(categories->first); - table_dupl = (uint16_t)sd->fDtran->elementAti(categories->second); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(state)); + table_base = static_cast(sd->fDtran->elementAti(categories->first)); + table_dupl = static_cast(sd->fDtran->elementAti(categories->second)); if (table_base != table_dupl) { break; } @@ -1176,7 +1176,7 @@ bool RBBITableBuilder::findDuplCharClassFrom(IntPair *categories) { void RBBITableBuilder::removeColumn(int32_t column) { int32_t numStates = fDStates->size(); for (int32_t state=0; stateelementAt(state); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(state)); U_ASSERT(column < sd->fDtran->size()); sd->fDtran->removeElementAt(column); } @@ -1190,9 +1190,9 @@ bool RBBITableBuilder::findDuplicateState(IntPair *states) { int32_t numCols = fRB->fSetBuilder->getNumCharCategories(); for (; states->firstfirst++) { - RBBIStateDescriptor *firstSD = (RBBIStateDescriptor *)fDStates->elementAt(states->first); + RBBIStateDescriptor* firstSD = static_cast(fDStates->elementAt(states->first)); for (states->second=states->first+1; states->secondsecond++) { - RBBIStateDescriptor *duplSD = (RBBIStateDescriptor *)fDStates->elementAt(states->second); + RBBIStateDescriptor* duplSD = static_cast(fDStates->elementAt(states->second)); if (firstSD->fAccepting != duplSD->fAccepting || firstSD->fLookAhead != duplSD->fLookAhead || firstSD->fTagsIdx != duplSD->fTagsIdx) { @@ -1252,14 +1252,14 @@ void RBBITableBuilder::removeState(IntPair duplStates) { U_ASSERT(keepState < duplState); U_ASSERT(duplState < fDStates->size()); - RBBIStateDescriptor *duplSD = (RBBIStateDescriptor *)fDStates->elementAt(duplState); + RBBIStateDescriptor* duplSD = static_cast(fDStates->elementAt(duplState)); fDStates->removeElementAt(duplState); delete duplSD; int32_t numStates = fDStates->size(); int32_t numCols = fRB->fSetBuilder->getNumCharCategories(); for (int32_t state=0; stateelementAt(state); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(state)); for (int32_t col=0; colfDtran->elementAti(col); int32_t newVal = existingVal; @@ -1283,7 +1283,7 @@ void RBBITableBuilder::removeSafeState(IntPair duplStates) { // and will auto-delete the removed element. int32_t numStates = fSafeTable->size(); for (int32_t state=0; stateelementAt(state); + UnicodeString* sd = static_cast(fSafeTable->elementAt(state)); int32_t numCols = sd->length(); for (int32_t col=0; colcharAt(col); @@ -1357,7 +1357,7 @@ bool RBBITableBuilder::use8BitsForTable() const { // //----------------------------------------------------------------------------- void RBBITableBuilder::exportTable(void *where) { - RBBIStateTable *table = (RBBIStateTable *)where; + RBBIStateTable* table = static_cast(where); uint32_t state; int col; @@ -1390,13 +1390,13 @@ void RBBITableBuilder::exportTable(void *where) { } for (state=0; statefNumStates; state++) { - RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(state); - RBBIStateTableRow *row = (RBBIStateTableRow *)(table->fTableData + state*table->fRowLen); + RBBIStateDescriptor* sd = static_cast(fDStates->elementAt(state)); + RBBIStateTableRow* row = reinterpret_cast(table->fTableData + state * table->fRowLen); if (use8BitsForTable()) { U_ASSERT (sd->fAccepting <= 255); U_ASSERT (sd->fLookAhead <= 255); U_ASSERT (0 <= sd->fTagsIdx && sd->fTagsIdx <= 255); - RBBIStateTableRow8 *r8 = (RBBIStateTableRow8*)row; + RBBIStateTableRow8* r8 = reinterpret_cast(row); r8->fAccepting = sd->fAccepting; r8->fLookAhead = sd->fLookAhead; r8->fTagsIdx = sd->fTagsIdx; @@ -1472,8 +1472,8 @@ void RBBITableBuilder::buildSafeReverseTable(UErrorCode &status) { } } if (wantedEndState == endState) { - safePairs.append((char16_t)c1); - safePairs.append((char16_t)c2); + safePairs.append(static_cast(c1)); + safePairs.append(static_cast(c2)); // printf("(%d, %d) ", c1, c2); } } @@ -1579,7 +1579,7 @@ bool RBBITableBuilder::use8BitsForSafeTable() const { // //----------------------------------------------------------------------------- void RBBITableBuilder::exportSafeTable(void *where) { - RBBIStateTable *table = (RBBIStateTable *)where; + RBBIStateTable* table = static_cast(where); uint32_t state; int col; @@ -1604,10 +1604,10 @@ void RBBITableBuilder::exportSafeTable(void *where) { } for (state=0; statefNumStates; state++) { - UnicodeString *rowString = (UnicodeString *)fSafeTable->elementAt(state); - RBBIStateTableRow *row = (RBBIStateTableRow *)(table->fTableData + state*table->fRowLen); + UnicodeString* rowString = static_cast(fSafeTable->elementAt(state)); + RBBIStateTableRow* row = reinterpret_cast(table->fTableData + state * table->fRowLen); if (use8BitsForSafeTable()) { - RBBIStateTableRow8 *r8 = (RBBIStateTableRow8*)row; + RBBIStateTableRow8* r8 = reinterpret_cast(row); r8->fAccepting = 0; r8->fLookAhead = 0; r8->fTagsIdx = 0; diff --git a/icu4c/source/common/resbund_cnv.cpp b/icu4c/source/common/resbund_cnv.cpp index 7f83f06f0e0c..a10960918941 100644 --- a/icu4c/source/common/resbund_cnv.cpp +++ b/icu4c/source/common/resbund_cnv.cpp @@ -49,7 +49,7 @@ ResourceBundle::constructForLocale(const UnicodeString& path, } else { UnicodeString nullTerminatedPath(path); - nullTerminatedPath.append((char16_t)0); + nullTerminatedPath.append(static_cast(0)); fResource = ures_openU(nullTerminatedPath.getBuffer(), locale.getName(), &error); } } diff --git a/icu4c/source/common/ruleiter.cpp b/icu4c/source/common/ruleiter.cpp index 0e665435a785..39bea52e78b7 100644 --- a/icu4c/source/common/ruleiter.cpp +++ b/icu4c/source/common/ruleiter.cpp @@ -139,7 +139,7 @@ UChar32 RuleCharacterIterator::_current() const { return buf->char32At(bufPos); } else { int i = pos.getIndex(); - return (i < text.length()) ? text.char32At(i) : (UChar32)DONE; + return (i < text.length()) ? text.char32At(i) : static_cast(DONE); } } diff --git a/icu4c/source/common/serv.cpp b/icu4c/source/common/serv.cpp index 5248f7c192b8..3a4aee5797f2 100644 --- a/icu4c/source/common/serv.cpp +++ b/icu4c/source/common/serv.cpp @@ -424,7 +424,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer return handleDefault(key, actualReturn, status); } - ICUService* ncthis = (ICUService*)this; // cast away semantic const + ICUService* ncthis = const_cast(this); // cast away semantic const CacheEntry* result = nullptr; { @@ -462,7 +462,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer if (factory != nullptr) { for (int32_t i = 0; i < limit; ++i) { - if (factory == (const ICUServiceFactory*)factories->elementAt(i)) { + if (factory == static_cast(factories->elementAt(i))) { startIndex = i + 1; break; } @@ -478,7 +478,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer do { currentDescriptor.remove(); key.currentDescriptor(currentDescriptor); - result = (CacheEntry*)serviceCache->get(currentDescriptor); + result = static_cast(serviceCache->get(currentDescriptor)); if (result != nullptr) { break; } @@ -490,7 +490,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer int32_t index = startIndex; while (index < limit) { - ICUServiceFactory* f = (ICUServiceFactory*)factories->elementAt(index++); + ICUServiceFactory* f = static_cast(factories->elementAt(index++)); LocalPointer service(f->create(key, this, status)); if (U_FAILURE(status)) { return nullptr; @@ -543,7 +543,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer if (cacheDescriptorList.isValid()) { for (int32_t i = cacheDescriptorList->size(); --i >= 0;) { - UnicodeString* desc = (UnicodeString*)cacheDescriptorList->elementAt(i); + UnicodeString* desc = static_cast(cacheDescriptorList->elementAt(i)); serviceCache->put(*desc, result, status); if (U_FAILURE(status)) { @@ -558,7 +558,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer if (actualReturn != nullptr) { // strip null prefix - if (result->actualDescriptor.indexOf((char16_t)0x2f) == 0) { // U+002f=slash (/) + if (result->actualDescriptor.indexOf(static_cast(0x2f)) == 0) { // U+002f=slash (/) actualReturn->remove(); actualReturn->append(result->actualDescriptor, 1, @@ -618,7 +618,7 @@ ICUService::getVisibleIDs(UVector& result, const UnicodeString* matchID, UErrorC break; } - const UnicodeString* id = (const UnicodeString*)e->key.pointer; + const UnicodeString* id = static_cast(e->key.pointer); if (fallbackKey != nullptr) { if (!fallbackKey->isFallbackOf(*id)) { continue; @@ -644,14 +644,14 @@ ICUService::getVisibleIDMap(UErrorCode& status) const { // must only be called when lock is already held - ICUService* ncthis = (ICUService*)this; // cast away semantic const + ICUService* ncthis = const_cast(this); // cast away semantic const if (idCache == nullptr) { ncthis->idCache = new Hashtable(status); if (idCache == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else if (factories != nullptr) { for (int32_t pos = factories->size(); --pos >= 0;) { - ICUServiceFactory* f = (ICUServiceFactory*)factories->elementAt(pos); + ICUServiceFactory* f = static_cast(factories->elementAt(pos)); f->updateVisibleIDs(*idCache, status); } if (U_FAILURE(status)) { @@ -679,7 +679,7 @@ ICUService::getDisplayName(const UnicodeString& id, UnicodeString& result, const Mutex mutex(&lock); const Hashtable* map = getVisibleIDMap(status); if (map != nullptr) { - ICUServiceFactory* f = (ICUServiceFactory*)map->get(id); + ICUServiceFactory* f = static_cast(map->get(id)); if (f != nullptr) { f->getDisplayName(id, locale, result); return result; @@ -691,7 +691,7 @@ ICUService::getDisplayName(const UnicodeString& id, UnicodeString& result, const while (fallbackKey != nullptr && fallbackKey->fallback()) { UnicodeString us; fallbackKey->currentID(us); - f = (ICUServiceFactory*)map->get(us); + f = static_cast(map->get(us)); if (f != nullptr) { f->getDisplayName(id, locale, result); delete fallbackKey; @@ -727,7 +727,7 @@ ICUService::getDisplayNames(UVector& result, result.removeAllElements(); result.setDeleter(userv_deleteStringPair); if (U_SUCCESS(status)) { - ICUService* ncthis = (ICUService*)this; // cast away semantic const + ICUService* ncthis = const_cast(this); // cast away semantic const Mutex mutex(&lock); if (dnCache != nullptr && dnCache->locale != locale) { @@ -749,8 +749,8 @@ ICUService::getDisplayNames(UVector& result, int32_t pos = UHASH_FIRST; const UHashElement* entry = nullptr; while ((entry = m->nextElement(pos)) != nullptr) { - const UnicodeString* id = (const UnicodeString*)entry->key.pointer; - ICUServiceFactory* f = (ICUServiceFactory*)entry->value.pointer; + const UnicodeString* id = static_cast(entry->key.pointer); + ICUServiceFactory* f = static_cast(entry->value.pointer); UnicodeString dname; f->getDisplayName(*id, locale, dname); if (dname.isBogus()) { @@ -776,11 +776,11 @@ ICUService::getDisplayNames(UVector& result, int32_t pos = UHASH_FIRST; const UHashElement *entry = nullptr; while ((entry = dnCache->cache.nextElement(pos)) != nullptr) { - const UnicodeString* id = (const UnicodeString*)entry->value.pointer; + const UnicodeString* id = static_cast(entry->value.pointer); if (matchKey != nullptr && !matchKey->isFallbackOf(*id)) { continue; } - const UnicodeString* dn = (const UnicodeString*)entry->key.pointer; + const UnicodeString* dn = static_cast(entry->key.pointer); StringPair* sp = StringPair::create(*id, *dn, status); result.adoptElement(sp, status); if (U_FAILURE(status)) { diff --git a/icu4c/source/common/servlkf.cpp b/icu4c/source/common/servlkf.cpp index f5bb0418c4e9..7ca5e7adc94b 100644 --- a/icu4c/source/common/servlkf.cpp +++ b/icu4c/source/common/servlkf.cpp @@ -76,7 +76,7 @@ LocaleKeyFactory::updateVisibleIDs(Hashtable& result, UErrorCode& status) const const UHashElement* elem = nullptr; int32_t pos = UHASH_FIRST; while ((elem = supported->nextElement(pos)) != nullptr) { - const UnicodeString& id = *((const UnicodeString*)elem->key.pointer); + const UnicodeString& id = *static_cast(elem->key.pointer); if (!visible) { result.remove(id); } else { diff --git a/icu4c/source/common/servls.cpp b/icu4c/source/common/servls.cpp index 978a956df7c3..33a113896233 100644 --- a/icu4c/source/common/servls.cpp +++ b/icu4c/source/common/servls.cpp @@ -179,7 +179,7 @@ class ServiceEnumeration : public StringEnumeration { length = other._ids.size(); for(i = 0; i < length; ++i) { - LocalPointer clonedId(((UnicodeString *)other._ids.elementAt(i))->clone(), status); + LocalPointer clonedId(static_cast(other._ids.elementAt(i))->clone(), status); _ids.adoptElement(clonedId.orphan(), status); } @@ -228,7 +228,7 @@ class ServiceEnumeration : public StringEnumeration { virtual const UnicodeString* snext(UErrorCode& status) override { if (upToDate(status) && (_pos < _ids.size())) { - return (const UnicodeString*)_ids[_pos++]; + return static_cast(_ids[_pos++]); } return nullptr; } @@ -263,7 +263,7 @@ const UnicodeString& ICULocaleService::validateFallbackLocale() const { const Locale& loc = Locale::getDefault(); - ICULocaleService* ncThis = (ICULocaleService*)this; + ICULocaleService* ncThis = const_cast(this); static UMutex llock; { Mutex mutex(&llock); diff --git a/icu4c/source/common/servnotf.cpp b/icu4c/source/common/servnotf.cpp index b2ad663a488a..3106152467ff 100644 --- a/icu4c/source/common/servnotf.cpp +++ b/icu4c/source/common/servnotf.cpp @@ -56,7 +56,7 @@ ICUNotifier::addListener(const EventListener* l, UErrorCode& status) listeners = lpListeners.orphan(); } else { for (int i = 0, e = listeners->size(); i < e; ++i) { - const EventListener* el = (const EventListener*)(listeners->elementAt(i)); + const EventListener* el = static_cast(listeners->elementAt(i)); if (l == el) { return; } @@ -88,7 +88,7 @@ ICUNotifier::removeListener(const EventListener *l, UErrorCode& status) if (listeners != nullptr) { // identity equality check for (int i = 0, e = listeners->size(); i < e; ++i) { - const EventListener* el = (const EventListener*)listeners->elementAt(i); + const EventListener* el = static_cast(listeners->elementAt(i)); if (l == el) { listeners->removeElementAt(i); if (listeners->size() == 0) { @@ -109,7 +109,7 @@ ICUNotifier::notifyChanged() Mutex lmx(¬ifyLock); if (listeners != nullptr) { for (int i = 0, e = listeners->size(); i < e; ++i) { - EventListener* el = (EventListener*)listeners->elementAt(i); + EventListener* el = static_cast(listeners->elementAt(i)); notifyListener(*el); } } diff --git a/icu4c/source/common/servrbf.cpp b/icu4c/source/common/servrbf.cpp index a4feca2c3b00..7f130d55aa50 100644 --- a/icu4c/source/common/servrbf.cpp +++ b/icu4c/source/common/servrbf.cpp @@ -61,8 +61,8 @@ ICUResourceBundleFactory::handleCreate(const Locale& loc, int32_t /* kind */, co // who made this change? -- dlf char pkg[20]; int32_t length; - length=_bundleName.extract(0, INT32_MAX, pkg, (int32_t)sizeof(pkg), US_INV); - if(length>=(int32_t)sizeof(pkg)) { + length = _bundleName.extract(0, INT32_MAX, pkg, static_cast(sizeof(pkg)), US_INV); + if (length >= static_cast(sizeof(pkg))) { return nullptr; } return new ResourceBundle(pkg, loc, status); diff --git a/icu4c/source/common/simpleformatter.cpp b/icu4c/source/common/simpleformatter.cpp index 16256270727e..66074938943e 100644 --- a/icu4c/source/common/simpleformatter.cpp +++ b/icu4c/source/common/simpleformatter.cpp @@ -73,7 +73,7 @@ UBool SimpleFormatter::applyPatternMinMaxArguments( const char16_t *patternBuffer = pattern.getBuffer(); int32_t patternLength = pattern.length(); // Reserve the first char for the number of arguments. - compiledPattern.setTo((char16_t)0); + compiledPattern.setTo(static_cast(0)); int32_t textLength = 0; int32_t maxArg = -1; UBool inQuote = false; @@ -98,7 +98,7 @@ UBool SimpleFormatter::applyPatternMinMaxArguments( } else if (!inQuote && c == OPEN_BRACE) { if (textLength > 0) { compiledPattern.setCharAt(compiledPattern.length() - textLength - 1, - (char16_t)(ARG_NUM_LIMIT + textLength)); + static_cast(ARG_NUM_LIMIT + textLength)); textLength = 0; } int32_t argNumber; @@ -129,7 +129,7 @@ UBool SimpleFormatter::applyPatternMinMaxArguments( if (argNumber > maxArg) { maxArg = argNumber; } - compiledPattern.append((char16_t)argNumber); + compiledPattern.append(static_cast(argNumber)); continue; } // else: c is part of literal text // Append c and track the literal-text segment length. @@ -144,14 +144,14 @@ UBool SimpleFormatter::applyPatternMinMaxArguments( } if (textLength > 0) { compiledPattern.setCharAt(compiledPattern.length() - textLength - 1, - (char16_t)(ARG_NUM_LIMIT + textLength)); + static_cast(ARG_NUM_LIMIT + textLength)); } int32_t argCount = maxArg + 1; if (argCount < min || max < argCount) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return false; } - compiledPattern.setCharAt(0, (char16_t)argCount); + compiledPattern.setCharAt(0, static_cast(argCount)); return true; } diff --git a/icu4c/source/common/stringtriebuilder.cpp b/icu4c/source/common/stringtriebuilder.cpp index 2a40dc88fd87..686703906289 100644 --- a/icu4c/source/common/stringtriebuilder.cpp +++ b/icu4c/source/common/stringtriebuilder.cpp @@ -328,7 +328,7 @@ StringTrieBuilder::registerNode(Node *newNode, UErrorCode &errorCode) { const UHashElement *old=uhash_find(nodes, newNode); if(old!=nullptr) { delete newNode; - return (Node *)old->key.pointer; + return static_cast(old->key.pointer); } // If uhash_puti() returns a non-zero value from an equivalent, previously // registered node, then uhash_find() failed to find that and we will leak newNode. @@ -352,7 +352,7 @@ StringTrieBuilder::registerFinalValue(int32_t value, UErrorCode &errorCode) { FinalValueNode key(value); const UHashElement *old=uhash_find(nodes, &key); if(old!=nullptr) { - return (Node *)old->key.pointer; + return static_cast(old->key.pointer); } Node *newNode=new FinalValueNode(value); if(newNode==nullptr) { @@ -375,12 +375,12 @@ StringTrieBuilder::registerFinalValue(int32_t value, UErrorCode &errorCode) { int32_t StringTrieBuilder::hashNode(const void *node) { - return ((const Node *)node)->hashCode(); + return static_cast(node)->hashCode(); } UBool StringTrieBuilder::equalNodes(const void *left, const void *right) { - return *(const Node *)left==*(const Node *)right; + return *static_cast(left) == *static_cast(right); } bool diff --git a/icu4c/source/common/ubidi.cpp b/icu4c/source/common/ubidi.cpp index fcf82fa97a8c..bcf4d2e36507 100644 --- a/icu4c/source/common/ubidi.cpp +++ b/icu4c/source/common/ubidi.cpp @@ -381,7 +381,7 @@ firstL_R_AL(UBiDi *pBiDi) { for(i=0; i(ubidi_getCustomizedClass(pBiDi, uchar)); if(result==ON) { if(dirProp==L || dirProp==R || dirProp==AL) { result=dirProp; @@ -436,13 +436,13 @@ getDirProps(UBiDi *pBiDi) { UBool isDefaultLevel=IS_DEFAULT_LEVEL(pBiDi->paraLevel); /* for inverse BiDi, the default para level is set to RTL if there is a strong R or AL character at either end of the text */ - UBool isDefaultLevelInverse=isDefaultLevel && (UBool) - (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT || - pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL); + UBool isDefaultLevelInverse = isDefaultLevel && static_cast( + pBiDi->reorderingMode == UBIDI_REORDER_INVERSE_LIKE_DIRECT || + pBiDi->reorderingMode == UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL); int32_t lastArabicPos=-1; int32_t controlCount=0; - UBool removeBiDiControls = (UBool)(pBiDi->reorderingOptions & - UBIDI_OPTION_REMOVE_CONTROLS); + UBool removeBiDiControls = + static_cast(pBiDi->reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS); enum State { NOT_SEEKING_STRONG, /* 0: not contextual paraLevel, not after FSI */ @@ -676,7 +676,7 @@ bracketInit(UBiDi *pBiDi, BracketData *bd) { bd->isoRuns[0].level=GET_PARALEVEL(pBiDi, 0); UBiDiLevel t = GET_PARALEVEL(pBiDi, 0) & 1; bd->isoRuns[0].lastStrong = bd->isoRuns[0].lastBase = t; - bd->isoRuns[0].contextDir = (UBiDiDirection)t; + bd->isoRuns[0].contextDir = static_cast(t); bd->isoRuns[0].contextPos=0; if(pBiDi->openingsMemory) { bd->openings=pBiDi->openingsMemory; @@ -696,7 +696,7 @@ bracketProcessB(BracketData *bd, UBiDiLevel level) { bd->isoRuns[0].limit=0; bd->isoRuns[0].level=level; bd->isoRuns[0].lastStrong=bd->isoRuns[0].lastBase=level&1; - bd->isoRuns[0].contextDir=(UBiDiDirection)(level&1); + bd->isoRuns[0].contextDir = static_cast(level & 1); bd->isoRuns[0].contextPos=0; } @@ -713,8 +713,8 @@ bracketProcessBoundary(BracketData *bd, int32_t lastCcPos, pLastIsoRun->limit=pLastIsoRun->start; pLastIsoRun->level=embeddingLevel; pLastIsoRun->lastStrong=pLastIsoRun->lastBase=contextLevel&1; - pLastIsoRun->contextDir=(UBiDiDirection)(contextLevel&1); - pLastIsoRun->contextPos=(UBiDiDirection)lastCcPos; + pLastIsoRun->contextDir = static_cast(contextLevel & 1); + pLastIsoRun->contextPos = static_cast(lastCcPos); } /* LRI or RLI */ @@ -729,7 +729,7 @@ bracketProcessLRI_RLI(BracketData *bd, UBiDiLevel level) { pLastIsoRun->start=pLastIsoRun->limit=lastLimit; pLastIsoRun->level=level; pLastIsoRun->lastStrong=pLastIsoRun->lastBase=level&1; - pLastIsoRun->contextDir=(UBiDiDirection)(level&1); + pLastIsoRun->contextDir = static_cast(level & 1); pLastIsoRun->contextPos=0; } @@ -803,7 +803,7 @@ bracketProcessClosing(BracketData *bd, int32_t openIdx, int32_t position) { UBool stable; DirProp newProp; pOpening=&bd->openings[openIdx]; - direction=(UBiDiDirection)(pLastIsoRun->level&1); + direction = static_cast(pLastIsoRun->level & 1); stable=true; /* assume stable until proved otherwise */ /* The stable flag is set when brackets are paired and their @@ -896,7 +896,7 @@ bracketProcessChar(BracketData *bd, int32_t position) { break; } pLastIsoRun->lastBase=ON; - pLastIsoRun->contextDir=(UBiDiDirection)newProp; + pLastIsoRun->contextDir = static_cast(newProp); pLastIsoRun->contextPos=position; level=bd->pBiDi->levels[position]; if(level&UBIDI_LEVEL_OVERRIDE) { /* X4, X5 */ @@ -944,14 +944,14 @@ bracketProcessChar(BracketData *bd, int32_t position) { dirProps[position]=newProp; pLastIsoRun->lastBase=newProp; pLastIsoRun->lastStrong=newProp; - pLastIsoRun->contextDir=(UBiDiDirection)newProp; + pLastIsoRun->contextDir = static_cast(newProp); pLastIsoRun->contextPos=position; } else if(dirProp<=R || dirProp==AL) { newProp= static_cast(DIR_FROM_STRONG(dirProp)); pLastIsoRun->lastBase=dirProp; pLastIsoRun->lastStrong=dirProp; - pLastIsoRun->contextDir=(UBiDiDirection)newProp; + pLastIsoRun->contextDir = static_cast(newProp); pLastIsoRun->contextPos=position; } else if(dirProp==EN) { @@ -960,7 +960,7 @@ bracketProcessChar(BracketData *bd, int32_t position) { newProp=L; /* W7 */ if(!bd->isNumbersSpecial) dirProps[position]=ENL; - pLastIsoRun->contextDir=(UBiDiDirection)L; + pLastIsoRun->contextDir = static_cast(L); pLastIsoRun->contextPos=position; } else { @@ -969,14 +969,14 @@ bracketProcessChar(BracketData *bd, int32_t position) { dirProps[position]=AN; /* W2 */ else dirProps[position]=ENR; - pLastIsoRun->contextDir=(UBiDiDirection)R; + pLastIsoRun->contextDir = static_cast(R); pLastIsoRun->contextPos=position; } } else if(dirProp==AN) { newProp=R; /* N0 */ pLastIsoRun->lastBase=AN; - pLastIsoRun->contextDir=(UBiDiDirection)R; + pLastIsoRun->contextDir = static_cast(R); pLastIsoRun->contextPos=position; } else if(dirProp==NSM) { @@ -1177,10 +1177,10 @@ resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { levels[i]=previousLevel; if (dirProp==LRE || dirProp==LRO) /* least greater even level */ - newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1)); + newLevel = static_cast((embeddingLevel + 2) & ~(UBIDI_LEVEL_OVERRIDE | 1)); else /* least greater odd level */ - newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1); + newLevel = static_cast((NO_OVERRIDE(embeddingLevel) + 1) | 1); if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 && overflowEmbeddingCount==0) { lastCcPos=i; @@ -1213,7 +1213,7 @@ resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { if(stackLast>0 && stack[stackLast](stack[stackLast]); } break; case LRI: @@ -1229,10 +1229,10 @@ resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { /* (X5a, X5b) */ if(dirProp==LRI) /* least greater even level */ - newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1)); + newLevel = static_cast((embeddingLevel + 2) & ~(UBIDI_LEVEL_OVERRIDE | 1)); else /* least greater odd level */ - newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1); + newLevel = static_cast((NO_OVERRIDE(embeddingLevel) + 1) | 1); if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 && overflowEmbeddingCount==0) { flags|=DIRPROP_FLAG(dirProp); @@ -1276,7 +1276,7 @@ resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { } else /* make it WS so that it is handled by adjustWSLevels() */ dirProps[i]=WS; - embeddingLevel=(UBiDiLevel)stack[stackLast]&~ISOLATE; + embeddingLevel = static_cast(stack[stackLast]) & ~ISOLATE; flags|=(DIRPROP_FLAG(ON)|DIRPROP_FLAG_LR(embeddingLevel)); previousLevel=embeddingLevel; levels[i]=NO_OVERRIDE(embeddingLevel); @@ -1315,7 +1315,7 @@ resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { previousLevel=embeddingLevel; levels[i]=embeddingLevel; if(!bracketProcessChar(&bracketData, i)) - return (UBiDiDirection)-1; + return static_cast(-1); /* the dirProp may have been changed in bracketProcessChar() */ flags|=DIRPROP_FLAG(dirProps[i]); break; @@ -1386,7 +1386,7 @@ checkExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) { } else { // Treat explicit level 0 as a wildcard for the paragraph level. // Avoid making the caller guess what the paragraph level would be. - level = (UBiDiLevel)currentParaLevel; + level = static_cast(currentParaLevel); levels[i] = level | overrideFlag; } } else { @@ -1868,7 +1868,7 @@ processPropertySeq(UBiDi *pBiDi, LevState *pLevState, uint8_t _prop, int32_t start0, k; start0=start; /* save original start position */ - oldStateSeq=(uint8_t)pLevState->state; + oldStateSeq = static_cast(pLevState->state); cell=(*pImpTab)[oldStateSeq][_prop]; pLevState->state=GET_STATE(cell); /* isolate the new state */ actionSeq=(*pImpAct)[GET_ACTION(cell)]; /* isolate the action */ @@ -2076,7 +2076,7 @@ lastL_R_AL(UBiDi *pBiDi) { for(i=length; i>0; ) { /* i is decremented by U16_PREV */ U16_PREV(text, 0, i, uchar); - dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar); + dirProp = static_cast(ubidi_getCustomizedClass(pBiDi, uchar)); if(dirProp==L) { return DirProp_L; } @@ -2104,7 +2104,7 @@ firstL_R_AL_EN_AN(UBiDi *pBiDi) { for(i=0; i(ubidi_getCustomizedClass(pBiDi, uchar)); if(dirProp==L) { return DirProp_L; } @@ -2142,18 +2142,18 @@ resolveImplicitLevels(UBiDi *pBiDi, * actions) and different levels state tables (maybe very similar to the * LTR corresponding ones. */ - inverseRTL=(UBool) - ((startlastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) && - (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT || - pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL)); + inverseRTL = + static_cast((start < pBiDi->lastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) && + (pBiDi->reorderingMode == UBIDI_REORDER_INVERSE_LIKE_DIRECT || + pBiDi->reorderingMode == UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL)); /* initialize for property and levels state tables */ levState.startL2EN=-1; /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */ levState.lastStrongRTL=-1; /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */ levState.runStart=start; levState.runLevel=pBiDi->levels[start]; - levState.pImpTab=(const ImpTab*)((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel&1]; - levState.pImpAct=(const ImpAct*)((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel&1]; + levState.pImpTab = static_cast(((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel & 1]); + levState.pImpAct = static_cast(((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel & 1]); if(start==0 && pBiDi->proLength>0) { DirProp lastStrong=lastL_R_AL(pBiDi); if(lastStrong!=DirProp_ON) { @@ -2391,8 +2391,8 @@ setParaRunsOnly(UBiDi *pBiDi, const char16_t *text, int32_t length, goto cleanup3; } visualMap=runsOnlyMemory; - visualText=(char16_t *)&visualMap[length]; - saveLevels=(UBiDiLevel *)&visualText[length]; + visualText = reinterpret_cast(&visualMap[length]); + saveLevels = reinterpret_cast(&visualText[length]); saveOptions=pBiDi->reorderingOptions; if(saveOptions & UBIDI_OPTION_INSERT_MARKS) { pBiDi->reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS; diff --git a/icu4c/source/common/ubidi_props.cpp b/icu4c/source/common/ubidi_props.cpp index 8f3f6a65c4b3..80044cca5413 100644 --- a/icu4c/source/common/ubidi_props.cpp +++ b/icu4c/source/common/ubidi_props.cpp @@ -51,7 +51,7 @@ _enumPropertyStartsRange(const void *context, UChar32 start, UChar32 end, uint32 (void)end; (void)value; /* add the start code point to the USet */ - const USetAdder *sa=(const USetAdder *)context; + const USetAdder* sa = static_cast(context); sa->add(sa->set, start); return true; } diff --git a/icu4c/source/common/ubiditransform.cpp b/icu4c/source/common/ubiditransform.cpp index 23634742b88d..a39cc3100d2b 100644 --- a/icu4c/source/common/ubiditransform.cpp +++ b/icu4c/source/common/ubiditransform.cpp @@ -233,7 +233,7 @@ updateSrc(UBiDiTransform *pTransform, const char16_t *newSrc, uint32_t newLength uprv_free(pTransform->src); pTransform->src = nullptr; } - pTransform->src = (char16_t *)uprv_malloc(newSize * sizeof(char16_t)); + pTransform->src = static_cast(uprv_malloc(newSize * sizeof(char16_t))); if (pTransform->src == nullptr) { *pErrorCode = U_MEMORY_ALLOCATION_ERROR; //pTransform->srcLength = pTransform->srcSize = 0; diff --git a/icu4c/source/common/ucase.cpp b/icu4c/source/common/ucase.cpp index 4fd23fc935c5..40b43cd89275 100644 --- a/icu4c/source/common/ucase.cpp +++ b/icu4c/source/common/ucase.cpp @@ -38,7 +38,7 @@ static UBool U_CALLCONV _enumPropertyStartsRange(const void *context, UChar32 start, UChar32 /*end*/, uint32_t /*value*/) { /* add the start code point to the USet */ - const USetAdder *sa=(const USetAdder *)context; + const USetAdder* sa = static_cast(context); sa->add(sa->set, start); return true; } diff --git a/icu4c/source/common/ucasemap.cpp b/icu4c/source/common/ucasemap.cpp index f419f65c32a4..928c52421537 100644 --- a/icu4c/source/common/ucasemap.cpp +++ b/icu4c/source/common/ucasemap.cpp @@ -160,12 +160,12 @@ appendResult(int32_t cpLength, int32_t result, const char16_t *s, } // See unicode/utf8.h U8_APPEND_UNSAFE(). -inline uint8_t getTwoByteLead(UChar32 c) { return (uint8_t)((c >> 6) | 0xc0); } -inline uint8_t getTwoByteTrail(UChar32 c) { return (uint8_t)((c & 0x3f) | 0x80); } +inline uint8_t getTwoByteLead(UChar32 c) { return static_cast((c >> 6) | 0xc0); } +inline uint8_t getTwoByteTrail(UChar32 c) { return static_cast((c & 0x3f) | 0x80); } UChar32 U_CALLCONV utf8_caseContextIterator(void *context, int8_t dir) { - UCaseContext *csc=(UCaseContext *)context; + UCaseContext* csc = static_cast(context); UChar32 c; if(dir<0) { @@ -234,7 +234,7 @@ void toLower(int32_t caseLocale, uint32_t options, if (d == 0) { continue; } ByteSinkUtil::appendUnchanged(src + prev, srcIndex - 1 - prev, sink, options, edits, errorCode); - char ascii = (char)(lead + d); + char ascii = static_cast(lead + d); sink.Append(&ascii, 1); if (edits != nullptr) { edits->addReplace(1, 1); @@ -342,7 +342,7 @@ void toUpper(int32_t caseLocale, uint32_t options, if (d == 0) { continue; } ByteSinkUtil::appendUnchanged(src + prev, srcIndex - 1 - prev, sink, options, edits, errorCode); - char ascii = (char)(lead + d); + char ascii = static_cast(lead + d); sink.Append(&ascii, 1); if (edits != nullptr) { edits->addReplace(1, 1); @@ -747,14 +747,14 @@ void toUpper(uint32_t options, int32_t i2 = i + 2; if ((data & HAS_EITHER_DIALYTIKA) != 0) { change |= (i2 + 2) > nextIndex || - src[i2] != (uint8_t)u8"\u0308"[0] || - src[i2 + 1] != (uint8_t)u8"\u0308"[1]; + src[i2] != static_cast(u8"\u0308"[0]) || + src[i2 + 1] != static_cast(u8"\u0308"[1]); i2 += 2; } if (addTonos) { change |= (i2 + 2) > nextIndex || - src[i2] != (uint8_t)u8"\u0301"[0] || - src[i2 + 1] != (uint8_t)u8"\u0301"[1]; + src[i2] != static_cast(u8"\u0301"[0]) || + src[i2 + 1] != static_cast(u8"\u0301"[1]); i2 += 2; } int32_t oldLength = nextIndex - i; @@ -867,14 +867,14 @@ ucasemap_mapUTF8(int32_t caseLocale, uint32_t options, UCASEMAP_BREAK_ITERATOR_P // Get the string length. if (srcLength == -1) { - srcLength = (int32_t)uprv_strlen((const char *)src); + srcLength = static_cast(uprv_strlen(src)); } if (edits != nullptr && (options & U_EDITS_NO_RESET) == 0) { edits->reset(); } stringCaseMapper(caseLocale, options, UCASEMAP_BREAK_ITERATOR - (const uint8_t *)src, srcLength, sink, edits, errorCode); + reinterpret_cast(src), srcLength, sink, edits, errorCode); sink.Flush(); if (U_SUCCESS(errorCode)) { if (edits != nullptr) { @@ -904,7 +904,7 @@ ucasemap_mapUTF8(int32_t caseLocale, uint32_t options, UCASEMAP_BREAK_ITERATOR_P /* get the string length */ if(srcLength==-1) { - srcLength=(int32_t)uprv_strlen((const char *)src); + srcLength = static_cast(uprv_strlen(src)); } /* check for overlapping source and destination */ @@ -923,7 +923,7 @@ ucasemap_mapUTF8(int32_t caseLocale, uint32_t options, UCASEMAP_BREAK_ITERATOR_P dest, destCapacity, [&](ByteSink& sink, UErrorCode& status) { stringCaseMapper(caseLocale, options, UCASEMAP_BREAK_ITERATOR - (const uint8_t *)src, srcLength, sink, edits, status); + reinterpret_cast(src), srcLength, sink, edits, status); }, errorCode); if (U_SUCCESS(errorCode) && edits != nullptr) { diff --git a/icu4c/source/common/ucasemap_titlecase_brkiter.cpp b/icu4c/source/common/ucasemap_titlecase_brkiter.cpp index c2b44a2c7887..ebc952a97975 100644 --- a/icu4c/source/common/ucasemap_titlecase_brkiter.cpp +++ b/icu4c/source/common/ucasemap_titlecase_brkiter.cpp @@ -107,7 +107,7 @@ ucasemap_utf8ToTitle(UCaseMap *csm, return 0; } UText utext=UTEXT_INITIALIZER; - utext_openUTF8(&utext, (const char *)src, srcLength, pErrorCode); + utext_openUTF8(&utext, src, srcLength, pErrorCode); if (U_FAILURE(*pErrorCode)) { return 0; } diff --git a/icu4c/source/common/uchar.cpp b/icu4c/source/common/uchar.cpp index 52dccfe482d2..f22d861c96e9 100644 --- a/icu4c/source/common/uchar.cpp +++ b/icu4c/source/common/uchar.cpp @@ -68,9 +68,9 @@ _enumTypeValue(const void *context, uint32_t value) { static UBool U_CALLCONV _enumTypeRange(const void *context, UChar32 start, UChar32 end, uint32_t value) { /* just cast the value to UCharCategory */ - return ((struct _EnumTypeCallback *)context)-> - enumRange(((struct _EnumTypeCallback *)context)->context, - start, end+1, (UCharCategory)value); + return static_cast(context)-> + enumRange(static_cast(context)->context, + start, end + 1, static_cast(value)); } U_CAPI void U_EXPORT2 @@ -637,7 +637,7 @@ ublock_getCode(UChar32 c) { static UBool U_CALLCONV _enumPropertyStartsRange(const void *context, UChar32 start, UChar32 end, uint32_t value) { /* add the start code point to the USet */ - const USetAdder *sa=(const USetAdder *)context; + const USetAdder* sa = static_cast(context); sa->add(sa->set, start); (void)end; (void)value; diff --git a/icu4c/source/common/ucharstrie.cpp b/icu4c/source/common/ucharstrie.cpp index ba9cea7ba390..4c48323c9176 100644 --- a/icu4c/source/common/ucharstrie.cpp +++ b/icu4c/source/common/ucharstrie.cpp @@ -297,7 +297,7 @@ UCharsTrie::findUniqueValueFromBranch(const char16_t *pos, int32_t length, ++pos; // ignore a comparison unit // handle its value int32_t node=*pos++; - UBool isFinal=(UBool)(node>>15); + UBool isFinal = static_cast(node >> 15); node&=0x7fff; int32_t value=readValue(pos, node); pos=skipValue(pos, node); @@ -339,7 +339,7 @@ UCharsTrie::findUniqueValue(const char16_t *pos, UBool haveUniqueValue, int32_t pos+=node-kMinLinearMatch+1; // Ignore the match units. node=*pos++; } else { - UBool isFinal=(UBool)(node>>15); + UBool isFinal = static_cast(node >> 15); int32_t value; if(isFinal) { value=readValue(pos, node&0x7fff); diff --git a/icu4c/source/common/ucharstriebuilder.cpp b/icu4c/source/common/ucharstriebuilder.cpp index 95b32711a8e2..bf3216bd1bc0 100644 --- a/icu4c/source/common/ucharstriebuilder.cpp +++ b/icu4c/source/common/ucharstriebuilder.cpp @@ -75,7 +75,7 @@ UCharsTrieElement::setTo(const UnicodeString &s, int32_t val, return; } stringOffset=strings.length(); - strings.append((char16_t)length); + strings.append(static_cast(length)); value=val; strings.append(s); } @@ -186,7 +186,7 @@ UCharsTrieBuilder::buildUChars(UStringTrieBuildOption buildOption, UErrorCode &e errorCode=U_MEMORY_ALLOCATION_ERROR; return; } - uprv_sortArray(elements, elementsLength, (int32_t)sizeof(UCharsTrieElement), + uprv_sortArray(elements, elementsLength, static_cast(sizeof(UCharsTrieElement)), compareElementStrings, &strings, false, // need not be a stable sort &errorCode); @@ -351,7 +351,7 @@ UCharsTrieBuilder::write(int32_t unit) { int32_t newLength=ucharsLength+1; if(ensureCapacity(newLength)) { ucharsLength=newLength; - uchars[ucharsCapacity-ucharsLength]=(char16_t)unit; + uchars[ucharsCapacity - ucharsLength] = static_cast(unit); } return ucharsLength; } @@ -379,19 +379,19 @@ UCharsTrieBuilder::writeValueAndFinal(int32_t i, UBool isFinal) { char16_t intUnits[3]; int32_t length; if(i<0 || i>UCharsTrie::kMaxTwoUnitValue) { - intUnits[0]=(char16_t)(UCharsTrie::kThreeUnitValueLead); - intUnits[1]=(char16_t)((uint32_t)i>>16); - intUnits[2]=(char16_t)i; + intUnits[0] = static_cast(UCharsTrie::kThreeUnitValueLead); + intUnits[1] = static_cast(static_cast(i) >> 16); + intUnits[2] = static_cast(i); length=3; // } else if(i<=UCharsTrie::kMaxOneUnitValue) { // intUnits[0]=(char16_t)(i); // length=1; } else { - intUnits[0]=(char16_t)(UCharsTrie::kMinTwoUnitValueLead+(i>>16)); - intUnits[1]=(char16_t)i; + intUnits[0] = static_cast(UCharsTrie::kMinTwoUnitValueLead + (i >> 16)); + intUnits[1] = static_cast(i); length=2; } - intUnits[0]=(char16_t)(intUnits[0]|(isFinal<<15)); + intUnits[0] = static_cast(intUnits[0] | (isFinal << 15)); return write(intUnits, length); } @@ -403,19 +403,19 @@ UCharsTrieBuilder::writeValueAndType(UBool hasValue, int32_t value, int32_t node char16_t intUnits[3]; int32_t length; if(value<0 || value>UCharsTrie::kMaxTwoUnitNodeValue) { - intUnits[0]=(char16_t)(UCharsTrie::kThreeUnitNodeValueLead); - intUnits[1]=(char16_t)((uint32_t)value>>16); - intUnits[2]=(char16_t)value; + intUnits[0] = static_cast(UCharsTrie::kThreeUnitNodeValueLead); + intUnits[1] = static_cast(static_cast(value) >> 16); + intUnits[2] = static_cast(value); length=3; } else if(value<=UCharsTrie::kMaxOneUnitNodeValue) { - intUnits[0]=(char16_t)((value+1)<<6); + intUnits[0] = static_cast((value + 1) << 6); length=1; } else { - intUnits[0]=(char16_t)(UCharsTrie::kMinTwoUnitNodeValueLead+((value>>10)&0x7fc0)); - intUnits[1]=(char16_t)value; + intUnits[0] = static_cast(UCharsTrie::kMinTwoUnitNodeValueLead + ((value >> 10) & 0x7fc0)); + intUnits[1] = static_cast(value); length=2; } - intUnits[0]|=(char16_t)node; + intUnits[0] |= static_cast(node); return write(intUnits, length); } @@ -429,14 +429,14 @@ UCharsTrieBuilder::writeDeltaTo(int32_t jumpTarget) { char16_t intUnits[3]; int32_t length; if(i<=UCharsTrie::kMaxTwoUnitDelta) { - intUnits[0]=(char16_t)(UCharsTrie::kMinTwoUnitDeltaLead+(i>>16)); + intUnits[0] = static_cast(UCharsTrie::kMinTwoUnitDeltaLead + (i >> 16)); length=1; } else { - intUnits[0]=(char16_t)(UCharsTrie::kThreeUnitDeltaLead); - intUnits[1]=(char16_t)(i>>16); + intUnits[0] = static_cast(UCharsTrie::kThreeUnitDeltaLead); + intUnits[1] = static_cast(i >> 16); length=2; } - intUnits[length++]=(char16_t)i; + intUnits[length++] = static_cast(i); return write(intUnits, length); } diff --git a/icu4c/source/common/ucharstrieiterator.cpp b/icu4c/source/common/ucharstrieiterator.cpp index 176aed68259c..8a212b8b36da 100644 --- a/icu4c/source/common/ucharstrieiterator.cpp +++ b/icu4c/source/common/ucharstrieiterator.cpp @@ -114,7 +114,7 @@ UCharsTrie::Iterator::next(UErrorCode &errorCode) { pos=uchars_+stack_->elementAti(stackSize-2); stack_->setSize(stackSize-2); str_.truncate(length&0xffff); - length=(int32_t)((uint32_t)length>>16); + length = static_cast(static_cast(length) >> 16); if(length>1) { pos=branchNext(pos, length, errorCode); if(pos==nullptr) { @@ -138,7 +138,7 @@ UCharsTrie::Iterator::next(UErrorCode &errorCode) { skipValue_=false; } else { // Deliver value for the string so far. - UBool isFinal=(UBool)(node>>15); + UBool isFinal = static_cast(node >> 15); if(isFinal) { value_=readValue(pos, node&0x7fff); } else { @@ -187,7 +187,7 @@ UCharsTrie::Iterator::branchNext(const char16_t *pos, int32_t length, UErrorCode while(length>kMaxBranchLinearSubNodeLength) { ++pos; // ignore the comparison unit // Push state for the greater-or-equal edge. - stack_->addElement((int32_t)(skipDelta(pos)-uchars_), errorCode); + stack_->addElement(static_cast(skipDelta(pos) - uchars_), errorCode); stack_->addElement(((length-(length>>1))<<16)|str_.length(), errorCode); // Follow the less-than edge. length>>=1; @@ -197,10 +197,10 @@ UCharsTrie::Iterator::branchNext(const char16_t *pos, int32_t length, UErrorCode // Read the first (key, value) pair. char16_t trieUnit=*pos++; int32_t node=*pos++; - UBool isFinal=(UBool)(node>>15); + UBool isFinal = static_cast(node >> 15); int32_t value=readValue(pos, node&=0x7fff); pos=skipValue(pos, node); - stack_->addElement((int32_t)(pos-uchars_), errorCode); + stack_->addElement(static_cast(pos - uchars_), errorCode); stack_->addElement(((length-1)<<16)|str_.length(), errorCode); str_.append(trieUnit); if(isFinal) { diff --git a/icu4c/source/common/uchriter.cpp b/icu4c/source/common/uchriter.cpp index c8b86e5d4df3..b3402989011b 100644 --- a/icu4c/source/common/uchriter.cpp +++ b/icu4c/source/common/uchriter.cpp @@ -172,7 +172,7 @@ UCharCharacterIterator::nextPostInc() { UBool UCharCharacterIterator::hasNext() { - return (UBool)(pos < end ? true : false); + return static_cast(pos < end); } char16_t @@ -186,7 +186,7 @@ UCharCharacterIterator::previous() { UBool UCharCharacterIterator::hasPrevious() { - return (UBool)(pos > begin ? true : false); + return static_cast(pos > begin); } UChar32 diff --git a/icu4c/source/common/ucmndata.cpp b/icu4c/source/common/ucmndata.cpp index 69575d4e830a..45717ffd712a 100644 --- a/icu4c/source/common/ucmndata.cpp +++ b/icu4c/source/common/ucmndata.cpp @@ -108,8 +108,8 @@ strcmpAfterPrefix(const char *s1, const char *s2, int32_t *pPrefixLength) { s1+=pl; s2+=pl; for(;;) { - int32_t c1=(uint8_t)*s1++; - int32_t c2=(uint8_t)*s2++; + int32_t c1 = static_cast(*s1++); + int32_t c2 = static_cast(*s2++); cmp=c1-c2; if(cmp!=0 || c1==0) { /* different or done */ break; @@ -271,7 +271,7 @@ offsetTOCLookupFn(const UDataMemory *pData, static uint32_t U_CALLCONV pointerTOCEntryCount(const UDataMemory *pData) { const PointerTOC *toc = (PointerTOC *)pData->toc; - return (uint32_t)((toc != nullptr) ? (toc->count) : 0); + return toc != nullptr ? toc->count : 0; } static const DataHeader * U_CALLCONV pointerTOCLookupFn(const UDataMemory *pData, diff --git a/icu4c/source/common/ucnv.cpp b/icu4c/source/common/ucnv.cpp index 34a5a203d09d..2ea88cca691a 100644 --- a/icu4c/source/common/ucnv.cpp +++ b/icu4c/source/common/ucnv.cpp @@ -916,7 +916,7 @@ _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { * s(U_SUCCESS(*err) && pArgs->flush && pArgs->source==pArgs->sourceLimit && cnv->fromUChar32==0); } else { @@ -941,7 +941,7 @@ _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { for(;;) { /* update offsets if we write any */ if(offsets!=nullptr) { - int32_t length=(int32_t)(pArgs->target-t); + int32_t length = static_cast(pArgs->target - t); if(length>0) { _updateOffsets(offsets, length, sourceIndex, errorInputLength); @@ -956,7 +956,7 @@ _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { } if(sourceIndex>=0) { - sourceIndex+=(int32_t)(pArgs->source-s); + sourceIndex += static_cast(pArgs->source - s); } } @@ -1066,10 +1066,10 @@ _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { U_ASSERT(cnv->preFromULength==0); - length=(int32_t)(pArgs->sourceLimit-pArgs->source); + length = static_cast(pArgs->sourceLimit - pArgs->source); if(length>0) { u_memcpy(cnv->preFromU, pArgs->source, length); - cnv->preFromULength=(int8_t)-length; + cnv->preFromULength = static_cast(-length); } pArgs->source=realSource; @@ -1089,7 +1089,7 @@ _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { codePoint=cnv->fromUChar32; errorInputLength=0; U16_APPEND_UNSAFE(cnv->invalidUCharBuffer, errorInputLength, codePoint); - cnv->invalidUCharLength=(int8_t)errorInputLength; + cnv->invalidUCharLength = static_cast(errorInputLength); /* set the converter state to deal with the next character */ cnv->fromUChar32=0; @@ -1134,7 +1134,7 @@ ucnv_outputOverflowFromUnicode(UConverter *cnv, offsets=nullptr; } - overflow=(char *)cnv->charErrorBuffer; + overflow = reinterpret_cast(cnv->charErrorBuffer); length=cnv->charErrorBufferLength; i=0; while(icharErrorBufferLength=(int8_t)j; + cnv->charErrorBufferLength = static_cast(j); *target=t; if(offsets!=nullptr) { *pOffsets=offsets; @@ -1361,7 +1361,7 @@ _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) { * s(U_SUCCESS(*err) && pArgs->flush && pArgs->source==pArgs->sourceLimit && cnv->toULength==0); } else { @@ -1386,7 +1386,7 @@ _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) { for(;;) { /* update offsets if we write any */ if(offsets!=nullptr) { - int32_t length=(int32_t)(pArgs->target-t); + int32_t length = static_cast(pArgs->target - t); if(length>0) { _updateOffsets(offsets, length, sourceIndex, errorInputLength); @@ -1401,7 +1401,7 @@ _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) { } if(sourceIndex>=0) { - sourceIndex+=(int32_t)(pArgs->source-s); + sourceIndex += static_cast(pArgs->source - s); } } @@ -1513,10 +1513,10 @@ _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) { U_ASSERT(cnv->preToULength==0); - length=(int32_t)(pArgs->sourceLimit-pArgs->source); + length = static_cast(pArgs->sourceLimit - pArgs->source); if(length>0) { uprv_memcpy(cnv->preToU, pArgs->source, length); - cnv->preToULength=(int8_t)-length; + cnv->preToULength = static_cast(-length); } pArgs->source=realSource; @@ -1592,7 +1592,7 @@ ucnv_outputOverflowToUnicode(UConverter *cnv, overflow[j++]=overflow[i++]; } while(iUCharErrorBufferLength=(int8_t)j; + cnv->UCharErrorBufferLength = static_cast(j); *target=t; if(offsets!=nullptr) { *pOffsets=offsets; @@ -2437,7 +2437,7 @@ ucnv_internalConvert(UConverter *outConverter, UConverter *inConverter, false, true, pErrorCode); - targetLength=(int32_t)(myTarget-target); + targetLength = static_cast(myTarget - target); } /* @@ -2460,7 +2460,7 @@ ucnv_internalConvert(UConverter *outConverter, UConverter *inConverter, false, true, pErrorCode); - targetLength+=(int32_t)(myTarget-targetBuffer); + targetLength += static_cast(myTarget - targetBuffer); } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR); /* done with preflighting, set warnings and errors as appropriate */ diff --git a/icu4c/source/common/ucnv2022.cpp b/icu4c/source/common/ucnv2022.cpp index 5989c1b405a7..7572ce477afd 100644 --- a/icu4c/source/common/ucnv2022.cpp +++ b/icu4c/source/common/ucnv2022.cpp @@ -436,10 +436,10 @@ fromUWriteUInt8(UConverter *cnv, int32_t sourceIndex, UErrorCode *pErrorCode) { - char *targetChars = (char *)*target; + char* targetChars = reinterpret_cast(*target); ucnv_fromUWriteBytes(cnv, bytes, length, &targetChars, targetLimit, offsets, sourceIndex, pErrorCode); - *target = (uint8_t*)targetChars; + *target = reinterpret_cast(targetChars); } @@ -484,7 +484,7 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){ if(cnv->extraInfo != nullptr) { UConverterNamePieces stackPieces; UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER; - UConverterDataISO2022 *myConverterData=(UConverterDataISO2022 *) cnv->extraInfo; + UConverterDataISO2022* myConverterData = static_cast(cnv->extraInfo); uint32_t version; stackArgs.onlyTestIsLoadable = pArgs->onlyTestIsLoadable; @@ -528,12 +528,12 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){ } /* set the function pointers to appropriate functions */ - cnv->sharedData=(UConverterSharedData*)(&_ISO2022JPData); + cnv->sharedData = const_cast(&_ISO2022JPData); uprv_strcpy(myConverterData->locale,"ja"); (void)uprv_strcpy(myConverterData->name,"ISO_2022,locale=ja,version="); size_t len = uprv_strlen(myConverterData->name); - myConverterData->name[len]=(char)(myConverterData->version+(int)'0'); + myConverterData->name[len] = static_cast(myConverterData->version + static_cast('0')); myConverterData->name[len+1]='\0'; } #if !UCONFIG_ONLY_HTML_CONVERSION @@ -579,7 +579,7 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){ setInitialStateFromUnicodeKR(cnv, myConverterData); /* set the function pointers to appropriate functions */ - cnv->sharedData=(UConverterSharedData*)&_ISO2022KRData; + cnv->sharedData = const_cast(&_ISO2022KRData); uprv_strcpy(myConverterData->locale,"ko"); } } @@ -606,7 +606,7 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){ /* set the function pointers to appropriate functions */ - cnv->sharedData=(UConverterSharedData*)&_ISO2022CNData; + cnv->sharedData = const_cast(&_ISO2022CNData); uprv_strcpy(myConverterData->locale,"cn"); if (version==0){ @@ -655,7 +655,7 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){ static void U_CALLCONV _ISO2022Close(UConverter *converter) { - UConverterDataISO2022* myData =(UConverterDataISO2022 *) (converter->extraInfo); + UConverterDataISO2022* myData = static_cast(converter->extraInfo); UConverterSharedData **array = myData->myConverterArray; int32_t i; @@ -678,7 +678,7 @@ _ISO2022Close(UConverter *converter) { static void U_CALLCONV _ISO2022Reset(UConverter *converter, UConverterResetChoice choice) { - UConverterDataISO2022 *myConverterData=(UConverterDataISO2022 *) (converter->extraInfo); + UConverterDataISO2022* myConverterData = static_cast(converter->extraInfo); if(choice<=UCNV_RESET_TO_UNICODE) { uprv_memset(&myConverterData->toU2022State, 0, sizeof(ISO2022State)); myConverterData->key = 0; @@ -784,7 +784,7 @@ getKey_2022(char c,int32_t* key,int32_t* offset){ int32_t hi = MAX_STATES_2022; int32_t oldmid=0; - togo = normalize_esq_chars_2022[(uint8_t)c]; + togo = normalize_esq_chars_2022[static_cast(c)]; if(togo == 0) { /* not a valid character anywhere in an escape sequence */ *key = 0; @@ -809,7 +809,7 @@ getKey_2022(char c,int32_t* key,int32_t* offset){ else /*we found it*/{ *key = togo; *offset = mid; - return (UCNV_TableStates_2022)escSeqStateTable_Value_2022[mid]; + return static_cast(escSeqStateTable_Value_2022[mid]); } oldmid = mid; @@ -829,7 +829,7 @@ changeState_2022(UConverter* _this, Variant2022 var, UErrorCode* err){ UCNV_TableStates_2022 value; - UConverterDataISO2022* myData2022 = ((UConverterDataISO2022*)_this->extraInfo); + UConverterDataISO2022* myData2022 = static_cast(_this->extraInfo); uint32_t key = myData2022->key; int32_t offset = 0; int8_t initialToULength = _this->toULength; @@ -838,8 +838,8 @@ changeState_2022(UConverter* _this, value = VALID_NON_TERMINAL_2022; while (*source < sourceLimit) { c = *(*source)++; - _this->toUBytes[_this->toULength++]=(uint8_t)c; - value = getKey_2022(c,(int32_t *) &key, &offset); + _this->toUBytes[_this->toULength++] = static_cast(c); + value = getKey_2022(c, reinterpret_cast(&key), &offset); switch (value){ @@ -910,7 +910,7 @@ changeState_2022(UConverter* _this, #endif case ISO_2022_JP: { - StateEnum tempState=(StateEnum)nextStateToUnicodeJP[offset]; + StateEnum tempState = static_cast(nextStateToUnicodeJP[offset]); switch(tempState) { case INVALID_STATE: *err = U_UNSUPPORTED_ESCAPE_SEQUENCE; @@ -933,7 +933,7 @@ changeState_2022(UConverter* _this, *err = U_UNSUPPORTED_ESCAPE_SEQUENCE; } else { /* G2 charset for SS2 */ - myData2022->toU2022State.cs[2]=(int8_t)tempState; + myData2022->toU2022State.cs[2] = static_cast(tempState); } break; default: @@ -941,7 +941,7 @@ changeState_2022(UConverter* _this, *err = U_UNSUPPORTED_ESCAPE_SEQUENCE; } else { /* G0 charset */ - myData2022->toU2022State.cs[0]=(int8_t)tempState; + myData2022->toU2022State.cs[0] = static_cast(tempState); } break; } @@ -950,7 +950,7 @@ changeState_2022(UConverter* _this, #if !UCONFIG_ONLY_HTML_CONVERSION case ISO_2022_CN: { - StateEnum tempState=(StateEnum)nextStateToUnicodeCN[offset]; + StateEnum tempState = static_cast(nextStateToUnicodeCN[offset]); switch(tempState) { case INVALID_STATE: *err = U_UNSUPPORTED_ESCAPE_SEQUENCE; @@ -986,17 +986,17 @@ changeState_2022(UConverter* _this, case GB2312_1: U_FALLTHROUGH; case CNS_11643_1: - myData2022->toU2022State.cs[1]=(int8_t)tempState; + myData2022->toU2022State.cs[1] = static_cast(tempState); break; case CNS_11643_2: - myData2022->toU2022State.cs[2]=(int8_t)tempState; + myData2022->toU2022State.cs[2] = static_cast(tempState); break; default: /* other CNS 11643 planes */ if(myData2022->version==0) { *err = U_UNSUPPORTED_ESCAPE_SEQUENCE; } else { - myData2022->toU2022State.cs[3]=(int8_t)tempState; + myData2022->toU2022State.cs[3] = static_cast(tempState); } break; } @@ -1039,7 +1039,7 @@ changeState_2022(UConverter* _this, *source-=backOutDistance; } else { /* Back out bytes from the previous buffer: Need to replay them. */ - _this->preToULength=(int8_t)(bytesFromThisBuffer-backOutDistance); + _this->preToULength = static_cast(bytesFromThisBuffer - backOutDistance); /* same as -(initialToULength-1) */ /* preToULength is negative! */ uprv_memcpy(_this->preToU, _this->toUBytes+1, -_this->preToULength); @@ -1145,7 +1145,7 @@ MBCS_FROM_UCHAR32_ISO2022(UConverterSharedData* sharedData, } } else /* outputType==MBCS_OUTPUT_3 */ { p=MBCS_POINTER_3_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); - myValue=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; + myValue = (static_cast(*p) << 16) | (static_cast(p[1]) << 8) | p[2]; if(myValue<=0xff) { length=1; } else if(myValue<=0xffff) { @@ -1201,7 +1201,7 @@ MBCS_SINGLE_FROM_UCHAR32(UConverterSharedData* sharedData, /* get the byte for the output */ value=MBCS_SINGLE_RESULT_FROM_U(table, (uint16_t *)sharedData->mbcs.fromUnicodeBytes, c); /* is this code point assigned, or do we use fallbacks? */ - *retval=(uint32_t)(value&0xff); + *retval = static_cast(value & 0xff); if(value>=0xf00) { return 1; /* roundtrip */ } else if(useFallback ? value>=0x800 : value>=0xc00) { @@ -1219,8 +1219,8 @@ MBCS_SINGLE_FROM_UCHAR32(UConverterSharedData* sharedData, */ static inline uint32_t _2022FromGR94DBCS(uint32_t value) { - if( (uint16_t)(value - 0xa1a1) <= (0xfefe - 0xa1a1) && - (uint8_t)(value - 0xa1) <= (0xfe - 0xa1) + if (static_cast(value - 0xa1a1) <= (0xfefe - 0xa1a1) && + static_cast(value - 0xa1) <= (0xfe - 0xa1) ) { return value - 0x8080; /* shift down to 21..7e byte range */ } else { @@ -1368,12 +1368,12 @@ toUnicodeCallback(UConverter *cnv, const uint32_t sourceChar, const uint32_t targetUniChar, UErrorCode* err){ if(sourceChar>0xff){ - cnv->toUBytes[0] = (uint8_t)(sourceChar>>8); - cnv->toUBytes[1] = (uint8_t)sourceChar; + cnv->toUBytes[0] = static_cast(sourceChar >> 8); + cnv->toUBytes[1] = static_cast(sourceChar); cnv->toULength = 2; } else{ - cnv->toUBytes[0] =(char) sourceChar; + cnv->toUBytes[0] = static_cast(sourceChar); cnv->toULength = 1; } @@ -1527,7 +1527,7 @@ _2022FromSJIS(uint32_t value) { return 0; /* beyond JIS X 0208 */ } - trail = (uint8_t)value; + trail = static_cast(value); value &= 0xff00; /* lead byte */ if(value <= 0x9f00) { @@ -1569,7 +1569,7 @@ _2022ToSJIS(uint8_t c1, uint8_t c2, char bytes[2]) { c2 = 0; /* invalid */ } } else { - if((uint8_t)(c2-0x21) <= ((0x7e)-0x21)) { + if (static_cast(c2 - 0x21) <= ((0x7e) - 0x21)) { c2 += 0x7e; } else { c2 = 0; /* invalid */ @@ -1583,8 +1583,8 @@ _2022ToSJIS(uint8_t c1, uint8_t c2, char bytes[2]) { } else { c1 = 0; /* invalid */ } - bytes[0] = (char)c1; - bytes[1] = (char)c2; + bytes[0] = static_cast(c1); + bytes[1] = static_cast(c2); } /* @@ -1665,8 +1665,8 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args UConverter *cnv = args->converter; UConverterDataISO2022 *converterData; ISO2022State *pFromU2022State; - uint8_t *target = (uint8_t *) args->target; - const uint8_t *targetLimit = (const uint8_t *) args->targetLimit; + uint8_t* target = reinterpret_cast(args->target); + const uint8_t* targetLimit = reinterpret_cast(args->targetLimit); const char16_t* source = args->source; const char16_t* sourceLimit = args->sourceLimit; int32_t* offsets = args->offsets; @@ -1682,7 +1682,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args int8_t cs, g; /* set up the state */ - converterData = (UConverterDataISO2022*)cnv->extraInfo; + converterData = static_cast(cnv->extraInfo); pFromU2022State = &converterData->fromU2022State; choiceCount = 0; @@ -1703,7 +1703,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /*look ahead to find the trail surrogate*/ if(source < sourceLimit) { /* test the following code unit */ - char16_t trail=(char16_t) *source; + char16_t trail = *source; if(U16_IS_TRAIL(trail)) { source++; sourceChar=U16_GET_SUPPLEMENTARY(sourceChar, trail); @@ -1753,7 +1753,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* JIS7/8: try single-byte half-width Katakana before JISX208 */ if(converterData->version == 3 || converterData->version == 4) { - choices[choiceCount++] = (int8_t)HWKANA_7BIT; + choices[choiceCount++] = static_cast(HWKANA_7BIT); } /* Do not try single-byte half-width Katakana for other versions. */ csm &= ~CSM(HWKANA_7BIT); @@ -1770,7 +1770,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* try all the other possible charsets */ for(i = 0; i < UPRV_LENGTHOF(jpCharsetPref); ++i) { - cs = (int8_t)jpCharsetPref[i]; + cs = static_cast(jpCharsetPref[i]); if(CSM(cs) & csm) { choices[choiceCount++] = cs; csm &= ~CSM(cs); @@ -1800,7 +1800,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args switch(cs0) { case ASCII: if(sourceChar <= 0x7f) { - targetValue = (uint32_t)sourceChar; + targetValue = static_cast(sourceChar); len = 1; cs = cs0; g = 0; @@ -1808,31 +1808,31 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args break; case ISO8859_1: if(GR96_START <= sourceChar && sourceChar <= GR96_END) { - targetValue = (uint32_t)sourceChar - 0x80; + targetValue = static_cast(sourceChar) - 0x80; len = 1; cs = cs0; g = 2; } break; case HWKANA_7BIT: - if((uint32_t)(sourceChar - HWKANA_START) <= (HWKANA_END - HWKANA_START)) { + if (static_cast(sourceChar - HWKANA_START) <= (HWKANA_END - HWKANA_START)) { if(converterData->version==3) { /* JIS7: use G1 (SO) */ /* Shift U+FF61..U+FF9F to bytes 21..5F. */ - targetValue = (uint32_t)(sourceChar - (HWKANA_START - 0x21)); + targetValue = static_cast(sourceChar - (HWKANA_START - 0x21)); len = 1; pFromU2022State->cs[1] = cs = cs0; /* do not output an escape sequence */ g = 1; } else if(converterData->version==4) { /* JIS8: use 8-bit bytes with any single-byte charset, see escape sequence output below */ /* Shift U+FF61..U+FF9F to bytes A1..DF. */ - targetValue = (uint32_t)(sourceChar - (HWKANA_START - 0xa1)); + targetValue = static_cast(sourceChar - (HWKANA_START - 0xa1)); len = 1; cs = pFromU2022State->cs[0]; if(IS_JP_DBCS(cs)) { /* switch from a DBCS charset to JISX201 */ - cs = (int8_t)JISX201; + cs = static_cast(JISX201); } /* else stay in the current G0 charset */ g = 0; @@ -1867,7 +1867,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args useFallback = false; } } else if(len == 0 && useFallback && - (uint32_t)(sourceChar - HWKANA_START) <= (HWKANA_END - HWKANA_START)) { + static_cast(sourceChar - HWKANA_START) <= (HWKANA_END - HWKANA_START)) { targetValue = hwkana_fb[sourceChar - HWKANA_START]; len = -2; cs = cs0; @@ -1958,10 +1958,10 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* write the output bytes */ if(len == 1) { - buffer[outLen++] = (char)targetValue; + buffer[outLen++] = static_cast(targetValue); } else /* len == 2 */ { - buffer[outLen++] = (char)(targetValue >> 8); - buffer[outLen++] = (char)targetValue; + buffer[outLen++] = static_cast(targetValue >> 8); + buffer[outLen++] = static_cast(targetValue); } } else { /* @@ -1983,13 +1983,13 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args if(outLen == 1) { *target++ = buffer[0]; if(offsets) { - *offsets++ = (int32_t)(source - args->source - 1); /* -1: known to be ASCII */ + *offsets++ = static_cast(source - args->source - 1); /* -1: known to be ASCII */ } } else if(outLen == 2 && (target + 2) <= targetLimit) { *target++ = buffer[0]; *target++ = buffer[1]; if(offsets) { - int32_t sourceIndex = (int32_t)(source - args->source - U16_LENGTH(sourceChar)); + int32_t sourceIndex = static_cast(source - args->source - U16_LENGTH(sourceChar)); *offsets++ = sourceIndex; *offsets++ = sourceIndex; } @@ -1997,8 +1997,8 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args fromUWriteUInt8( cnv, buffer, outLen, - &target, (const char *)targetLimit, - &offsets, (int32_t)(source - args->source - U16_LENGTH(sourceChar)), + &target, reinterpret_cast(targetLimit), + &offsets, static_cast(source - args->source - U16_LENGTH(sourceChar)), err); if(U_FAILURE(*err)) { break; @@ -2039,7 +2039,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args int32_t escLen = escSeqCharsLen[ASCII]; uprv_memcpy(buffer + outLen, escSeqChars[ASCII], escLen); outLen += escLen; - pFromU2022State->cs[0] = (int8_t)ASCII; + pFromU2022State->cs[0] = static_cast(ASCII); } /* get the source index of the last input character */ @@ -2050,7 +2050,7 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args * this code gives an incorrect result for the rare case of an unmatched * trail surrogate that is alone in the last buffer of the text stream */ - sourceIndex=(int32_t)(source-args->source); + sourceIndex = static_cast(source - args->source); if(sourceIndex>0) { --sourceIndex; if( U16_IS_TRAIL(args->source[sourceIndex]) && @@ -2065,14 +2065,14 @@ UConverter_fromUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args fromUWriteUInt8( cnv, buffer, outLen, - &target, (const char *)targetLimit, + &target, reinterpret_cast(targetLimit), &offsets, sourceIndex, err); } /*save the state and return */ args->source = source; - args->target = (char*)target; + args->target = reinterpret_cast(target); } /*************** to unicode *******************/ @@ -2081,7 +2081,7 @@ static void U_CALLCONV UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UErrorCode* err){ char tempBuf[2]; - const char *mySource = (char *) args->source; + const char* mySource = const_cast(args->source); char16_t *myTarget = args->target; const char *mySourceLimit = args->sourceLimit; uint32_t targetUniChar = 0x0000; @@ -2091,7 +2091,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, ISO2022State *pToU2022State; StateEnum cs; - myData=(UConverterDataISO2022*)(args->converter->extraInfo); + myData = static_cast(args->converter->extraInfo); pToU2022State = &myData->toU2022State; if(myData->key != 0) { @@ -2101,7 +2101,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, /* continue with a partial double-byte character */ mySourceChar = args->converter->toUBytes[0]; args->converter->toULength = 0; - cs = (StateEnum)pToU2022State->cs[pToU2022State->g]; + cs = static_cast(pToU2022State->cs[pToU2022State->g]); targetUniChar = missingCharMarker; goto getTrailByte; } @@ -2112,7 +2112,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if(myTarget < args->targetLimit){ - mySourceChar= (unsigned char) *mySource++; + mySourceChar = static_cast(*mySource++); switch(mySourceChar) { case UCNV_SI: @@ -2128,7 +2128,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, case UCNV_SO: if(myData->version==3) { /* JIS7: switch to G1 half-width Katakana */ - pToU2022State->cs[1] = (int8_t)HWKANA_7BIT; + pToU2022State->cs[1] = static_cast(HWKANA_7BIT); pToU2022State->g=1; continue; } else { @@ -2151,7 +2151,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if(myData->version==0 && myData->key==0 && U_SUCCESS(*err) && myData->isEmptySegment) { *err = U_ILLEGAL_ESCAPE_SEQUENCE; args->converter->toUCallbackReason = UCNV_IRREGULAR; - args->converter->toULength = (int8_t)(toULengthBefore + (mySource - mySourceBefore)); + args->converter->toULength = static_cast(toULengthBefore + (mySource - mySourceBefore)); } } @@ -2173,8 +2173,9 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, case CR: case LF: /* automatically reset to single-byte mode */ - if((StateEnum)pToU2022State->cs[0] != ASCII && (StateEnum)pToU2022State->cs[0] != JISX201) { - pToU2022State->cs[0] = (int8_t)ASCII; + if (static_cast(pToU2022State->cs[0]) != ASCII && + static_cast(pToU2022State->cs[0]) != JISX201) { + pToU2022State->cs[0] = static_cast(ASCII); } pToU2022State->cs[2] = 0; pToU2022State->g = 0; @@ -2182,8 +2183,8 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, default: /* convert one or two bytes */ myData->isEmptySegment = false; - cs = (StateEnum)pToU2022State->cs[pToU2022State->g]; - if( (uint8_t)(mySourceChar - 0xa1) <= (0xdf - 0xa1) && myData->version==4 && + cs = static_cast(pToU2022State->cs[pToU2022State->g]); + if (static_cast(mySourceChar - 0xa1) <= (0xdf - 0xa1) && myData->version == 4 && !IS_JP_DBCS(cs) ) { /* 8-bit halfwidth katakana in any single-byte mode for JIS8 */ @@ -2223,7 +2224,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, } break; case HWKANA_7BIT: - if((uint8_t)(mySourceChar - 0x21) <= (0x5f - 0x21)) { + if (static_cast(mySourceChar - 0x21) <= (0x5f - 0x21)) { /* 7-bit halfwidth Katakana */ targetUniChar = mySourceChar + (HWKANA_START - 0x21); } @@ -2234,7 +2235,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, int leadIsOk, trailIsOk; uint8_t trailByte; getTrailByte: - trailByte = (uint8_t)*mySource; + trailByte = static_cast(*mySource); /* * Ticket 5691: consistent illegal sequences: * - We include at least the first byte in the illegal sequence. @@ -2245,13 +2246,13 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, * an ESC/SO/SI, we report only the first byte as the illegal sequence. * Otherwise we convert or report the pair of bytes. */ - leadIsOk = (uint8_t)(mySourceChar - 0x21) <= (0x7e - 0x21); - trailIsOk = (uint8_t)(trailByte - 0x21) <= (0x7e - 0x21); + leadIsOk = static_cast(mySourceChar - 0x21) <= (0x7e - 0x21); + trailIsOk = static_cast(trailByte - 0x21) <= (0x7e - 0x21); if (leadIsOk && trailIsOk) { ++mySource; tmpSourceChar = (mySourceChar << 8) | trailByte; if(cs == JISX208) { - _2022ToSJIS((uint8_t)mySourceChar, trailByte, tempBuf); + _2022ToSJIS(static_cast(mySourceChar), trailByte, tempBuf); mySourceChar = tmpSourceChar; } else { /* Copy before we modify tmpSourceChar so toUnicodeCallback() sees the correct bytes. */ @@ -2259,8 +2260,8 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if (cs == KSC5601) { tmpSourceChar += 0x8080; /* = _2022ToGR94DBCS(tmpSourceChar) */ } - tempBuf[0] = (char)(tmpSourceChar >> 8); - tempBuf[1] = (char)(tmpSourceChar); + tempBuf[0] = static_cast(tmpSourceChar >> 8); + tempBuf[1] = static_cast(tmpSourceChar); } targetUniChar = ucnv_MBCSSimpleGetNextUChar(myData->myConverterArray[cs], tempBuf, 2, false); } else if (!(trailIsOk || IS_2022_CONTROL(trailByte))) { @@ -2270,7 +2271,7 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, mySourceChar = 0x10000 | (mySourceChar << 8) | trailByte; } } else { - args->converter->toUBytes[0] = (uint8_t)mySourceChar; + args->converter->toUBytes[0] = static_cast(mySourceChar); args->converter->toULength = 1; goto endloop; } @@ -2279,27 +2280,27 @@ UConverter_toUnicode_ISO_2022_JP_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, } /* End of outer switch */ if(targetUniChar < (missingCharMarker-1/*0xfffe*/)){ if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } - *(myTarget++)=(char16_t)targetUniChar; + *(myTarget++) = static_cast(targetUniChar); } else if(targetUniChar > missingCharMarker){ /* disassemble the surrogate pair and write to output*/ targetUniChar-=0x0010000; - *myTarget = (char16_t)(0xd800+(char16_t)(targetUniChar>>10)); + *myTarget = static_cast(0xd800 + static_cast(targetUniChar >> 10)); if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } ++myTarget; if(myTarget< args->targetLimit){ - *myTarget = (char16_t)(0xdc00+(char16_t)(targetUniChar&0x3ff)); + *myTarget = static_cast(0xdc00 + static_cast(targetUniChar & 0x3ff)); if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } ++myTarget; }else{ args->converter->UCharErrorBuffer[args->converter->UCharErrorBufferLength++]= - (char16_t)(0xdc00+(char16_t)(targetUniChar&0x3ff)); + static_cast(0xdc00 + static_cast(targetUniChar & 0x3ff)); } } @@ -2333,7 +2334,7 @@ static void U_CALLCONV UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC_IBM(UConverterFromUnicodeArgs* args, UErrorCode* err){ UConverter* saveConv = args->converter; - UConverterDataISO2022 *myConverterData=(UConverterDataISO2022*)saveConv->extraInfo; + UConverterDataISO2022* myConverterData = static_cast(saveConv->extraInfo); args->converter=myConverterData->currentConverter; myConverterData->currentConverter->fromUChar32 = saveConv->fromUChar32; @@ -2358,8 +2359,8 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args const char16_t *source = args->source; const char16_t *sourceLimit = args->sourceLimit; - unsigned char *target = (unsigned char *) args->target; - unsigned char *targetLimit = (unsigned char *) args->targetLimit; + unsigned char *target = reinterpret_cast(args->target); + unsigned char *targetLimit = reinterpret_cast(const_cast(args->targetLimit)); int32_t* offsets = args->offsets; uint32_t targetByteUnit = 0x0000; UChar32 sourceChar = 0x0000; @@ -2370,7 +2371,7 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args UBool useFallback; int32_t length =0; - converterData=(UConverterDataISO2022*)args->converter->extraInfo; + converterData = static_cast(args->converter->extraInfo); /* if the version is 1 then the user is requesting * conversion with ibm-25546 pass the arguments to * MBCS converter and return @@ -2383,10 +2384,10 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* initialize data */ sharedData = converterData->currentConverter->sharedData; useFallback = args->converter->useFallback; - isTargetByteDBCS=(UBool)args->converter->fromUnicodeStatus; + isTargetByteDBCS = static_cast(args->converter->fromUnicodeStatus); oldIsTargetByteDBCS = isTargetByteDBCS; - isTargetByteDBCS = (UBool) args->converter->fromUnicodeStatus; + isTargetByteDBCS = static_cast(args->converter->fromUnicodeStatus); if((sourceChar = args->converter->fromUChar32)!=0 && target 2 || length==0 || (length == 1 && targetByteUnit > 0x7f) || (length == 2 && - ((uint16_t)(targetByteUnit - 0xa1a1) > (0xfefe - 0xa1a1) || - (uint8_t)(targetByteUnit - 0xa1) > (0xfe - 0xa1))) + (static_cast(targetByteUnit - 0xa1a1) > (0xfefe - 0xa1a1) || + static_cast(targetByteUnit - 0xa1) > (0xfe - 0xa1))) ) { targetByteUnit=missingCharMarker; } if (targetByteUnit != missingCharMarker){ oldIsTargetByteDBCS = isTargetByteDBCS; - isTargetByteDBCS = (UBool)(targetByteUnit>0x00FF); + isTargetByteDBCS = static_cast(targetByteUnit > 0x00FF); /* append the shift sequence */ if (oldIsTargetByteDBCS != isTargetByteDBCS ){ @@ -2431,38 +2432,38 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args else *target++ = UCNV_SI; if(offsets) - *(offsets++) = (int32_t)(source - args->source-1); + *(offsets++) = static_cast(source - args->source - 1); } /* write the targetUniChar to target */ if(targetByteUnit <= 0x00FF){ if( target < targetLimit){ - *(target++) = (unsigned char) targetByteUnit; + *(target++) = static_cast(targetByteUnit); if(offsets){ - *(offsets++) = (int32_t)(source - args->source-1); + *(offsets++) = static_cast(source - args->source - 1); } }else{ - args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = (unsigned char) (targetByteUnit); + args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = static_cast(targetByteUnit); *err = U_BUFFER_OVERFLOW_ERROR; } }else{ if(target < targetLimit){ - *(target++) =(unsigned char) ((targetByteUnit>>8) -0x80); + *(target++) = static_cast((targetByteUnit >> 8) - 0x80); if(offsets){ - *(offsets++) = (int32_t)(source - args->source-1); + *(offsets++) = static_cast(source - args->source - 1); } if(target < targetLimit){ - *(target++) =(unsigned char) (targetByteUnit -0x80); + *(target++) = static_cast(targetByteUnit - 0x80); if(offsets){ - *(offsets++) = (int32_t)(source - args->source-1); + *(offsets++) = static_cast(source - args->source - 1); } }else{ - args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = (unsigned char) (targetByteUnit -0x80); + args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = static_cast(targetByteUnit - 0x80); *err = U_BUFFER_OVERFLOW_ERROR; } }else{ - args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = (unsigned char) ((targetByteUnit>>8) -0x80); - args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = (unsigned char) (targetByteUnit-0x80); + args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = static_cast((targetByteUnit >> 8) - 0x80); + args->converter->charErrorBuffer[args->converter->charErrorBufferLength++] = static_cast(targetByteUnit - 0x80); *err = U_BUFFER_OVERFLOW_ERROR; } } @@ -2480,7 +2481,7 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /*look ahead to find the trail surrogate*/ if(source < sourceLimit) { /* test the following code unit */ - char16_t trail=(char16_t) *source; + char16_t trail = *source; if(U16_IS_TRAIL(trail)) { source++; sourceChar=U16_GET_SUPPLEMENTARY(sourceChar, trail); @@ -2544,7 +2545,7 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args * this code gives an incorrect result for the rare case of an unmatched * trail surrogate that is alone in the last buffer of the text stream */ - sourceIndex=(int32_t)(source-args->source); + sourceIndex = static_cast(source - args->source); if(sourceIndex>0) { --sourceIndex; if( U16_IS_TRAIL(args->source[sourceIndex]) && @@ -2559,15 +2560,15 @@ UConverter_fromUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args fromUWriteUInt8( args->converter, SHIFT_IN_STR, 1, - &target, (const char *)targetLimit, + &target, reinterpret_cast(targetLimit), &offsets, sourceIndex, err); } /*save the state and return */ args->source = source; - args->target = (char*)target; - args->converter->fromUnicodeStatus = (uint32_t)isTargetByteDBCS; + args->target = reinterpret_cast(target); + args->converter->fromUnicodeStatus = static_cast(isTargetByteDBCS); } /************************ To Unicode ***************************************/ @@ -2576,7 +2577,7 @@ static void U_CALLCONV UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC_IBM(UConverterToUnicodeArgs *args, UErrorCode* err){ char const* sourceStart; - UConverterDataISO2022* myData=(UConverterDataISO2022*)(args->converter->extraInfo); + UConverterDataISO2022* myData = static_cast(args->converter->extraInfo); UConverterToUnicodeArgs subArgs; int32_t minArgsSize; @@ -2585,11 +2586,11 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC_IBM(UConverterToUnicodeArgs *args if(args->sizesize; } else { - minArgsSize = (int32_t)sizeof(UConverterToUnicodeArgs); + minArgsSize = static_cast(sizeof(UConverterToUnicodeArgs)); } uprv_memcpy(&subArgs, args, minArgsSize); - subArgs.size = (uint16_t)minArgsSize; + subArgs.size = static_cast(minArgsSize); subArgs.converter = myData->currentConverter; /* remember the original start of the input for offsets */ @@ -2628,7 +2629,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC_IBM(UConverterToUnicodeArgs *args /* update offsets to base them on the actual start of the input */ int32_t *offsets = args->offsets; char16_t *target = args->target; - int32_t delta = (int32_t)(args->source - sourceStart); + int32_t delta = static_cast(args->source - sourceStart); while(target < subArgs.target) { if(*offsets >= 0) { *offsets += delta; @@ -2674,7 +2675,7 @@ static void U_CALLCONV UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UErrorCode* err){ char tempBuf[2]; - const char *mySource = ( char *) args->source; + const char* mySource = const_cast(args->source); char16_t *myTarget = args->target; const char *mySourceLimit = args->sourceLimit; UChar32 targetUniChar = 0x0000; @@ -2683,7 +2684,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UConverterSharedData* sharedData ; UBool useFallback; - myData=(UConverterDataISO2022*)(args->converter->extraInfo); + myData = static_cast(args->converter->extraInfo); if(myData->version==1){ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC_IBM(args,err); return; @@ -2707,7 +2708,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if(myTarget < args->targetLimit){ - mySourceChar= (unsigned char) *mySource++; + mySourceChar = static_cast(*mySource++); if(mySourceChar==UCNV_SI){ myData->toU2022State.g = 0; @@ -2715,7 +2716,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, myData->isEmptySegment = false; /* we are handling it, reset to avoid future spurious errors */ *err = U_ILLEGAL_ESCAPE_SEQUENCE; args->converter->toUCallbackReason = UCNV_IRREGULAR; - args->converter->toUBytes[0] = (uint8_t)mySourceChar; + args->converter->toUBytes[0] = static_cast(mySourceChar); args->converter->toULength = 1; args->target = myTarget; args->source = mySource; @@ -2749,7 +2750,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, uint8_t trailByte; getTrailByte: targetUniChar = missingCharMarker; - trailByte = (uint8_t)*mySource; + trailByte = static_cast(*mySource); /* * Ticket 5691: consistent illegal sequences: * - We include at least the first byte in the illegal sequence. @@ -2760,12 +2761,12 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, * an ESC/SO/SI, we report only the first byte as the illegal sequence. * Otherwise we convert or report the pair of bytes. */ - leadIsOk = (uint8_t)(mySourceChar - 0x21) <= (0x7e - 0x21); - trailIsOk = (uint8_t)(trailByte - 0x21) <= (0x7e - 0x21); + leadIsOk = static_cast(mySourceChar - 0x21) <= (0x7e - 0x21); + trailIsOk = static_cast(trailByte - 0x21) <= (0x7e - 0x21); if (leadIsOk && trailIsOk) { ++mySource; - tempBuf[0] = (char)(mySourceChar + 0x80); - tempBuf[1] = (char)(trailByte + 0x80); + tempBuf[0] = static_cast(mySourceChar + 0x80); + tempBuf[1] = static_cast(trailByte + 0x80); targetUniChar = ucnv_MBCSSimpleGetNextUChar(sharedData, tempBuf, 2, useFallback); mySourceChar = (mySourceChar << 8) | trailByte; } else if (!(trailIsOk || IS_2022_CONTROL(trailByte))) { @@ -2775,7 +2776,7 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, mySourceChar = static_cast(0x10000 | (mySourceChar << 8) | trailByte); } } else { - args->converter->toUBytes[0] = (uint8_t)mySourceChar; + args->converter->toUBytes[0] = static_cast(mySourceChar); args->converter->toULength = 1; break; } @@ -2787,9 +2788,9 @@ UConverter_toUnicode_ISO_2022_KR_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, } if(targetUniChar < 0xfffe){ if(args->offsets) { - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } - *(myTarget++)=(char16_t)targetUniChar; + *(myTarget++) = static_cast(targetUniChar); } else { /* Call the callback function*/ @@ -2917,8 +2918,8 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args UConverter *cnv = args->converter; UConverterDataISO2022 *converterData; ISO2022State *pFromU2022State; - uint8_t *target = (uint8_t *) args->target; - const uint8_t *targetLimit = (const uint8_t *) args->targetLimit; + uint8_t* target = reinterpret_cast(args->target); + const uint8_t* targetLimit = reinterpret_cast(args->targetLimit); const char16_t* source = args->source; const char16_t* sourceLimit = args->sourceLimit; int32_t* offsets = args->offsets; @@ -2931,7 +2932,7 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args UBool useFallback; /* set up the state */ - converterData = (UConverterDataISO2022*)cnv->extraInfo; + converterData = static_cast(cnv->extraInfo); pFromU2022State = &converterData->fromU2022State; choiceCount = 0; @@ -2952,7 +2953,7 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /*look ahead to find the trail surrogate*/ if(source < sourceLimit) { /* test the following code unit */ - char16_t trail=(char16_t) *source; + char16_t trail = *source; if(U16_IS_TRAIL(trail)) { source++; sourceChar=U16_GET_SUPPLEMENTARY(sourceChar, trail); @@ -2992,11 +2993,11 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* US-ASCII */ if(pFromU2022State->g == 0) { - buffer[0] = (char)sourceChar; + buffer[0] = static_cast(sourceChar); len = 1; } else { buffer[0] = UCNV_SI; - buffer[1] = (char)sourceChar; + buffer[1] = static_cast(sourceChar); len = 2; pFromU2022State->g = 0; choiceCount = 0; @@ -3026,9 +3027,9 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* try the other SO/G1 converter; a CNS_11643_1 lookup may result in any plane */ if(choices[0] == GB2312_1) { - choices[1] = (int8_t)CNS_11643_1; + choices[1] = static_cast(CNS_11643_1); } else { - choices[1] = (int8_t)GB2312_1; + choices[1] = static_cast(GB2312_1); } choiceCount = 2; @@ -3038,23 +3039,23 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args /* try one of the other converters */ switch(choices[0]) { case GB2312_1: - choices[1] = (int8_t)CNS_11643_1; - choices[2] = (int8_t)ISO_IR_165; + choices[1] = static_cast(CNS_11643_1); + choices[2] = static_cast(ISO_IR_165); break; case ISO_IR_165: - choices[1] = (int8_t)GB2312_1; - choices[2] = (int8_t)CNS_11643_1; + choices[1] = static_cast(GB2312_1); + choices[2] = static_cast(CNS_11643_1); break; default: /* CNS_11643_x */ - choices[1] = (int8_t)GB2312_1; - choices[2] = (int8_t)ISO_IR_165; + choices[1] = static_cast(GB2312_1); + choices[2] = static_cast(ISO_IR_165); break; } choiceCount = 3; } else { - choices[0] = (int8_t)CNS_11643_1; - choices[1] = (int8_t)GB2312_1; + choices[0] = static_cast(CNS_11643_1); + choices[1] = static_cast(GB2312_1); } } @@ -3087,7 +3088,7 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args MBCS_OUTPUT_3); if(len2 == 3 || (len2 == -3 && len == 0)) { targetValue = value; - cs = (int8_t)(CNS_11643_0 + (value >> 16) - 0x80); + cs = static_cast(CNS_11643_0 + (value >> 16) - 0x80); if(len2 >= 0) { len = 2; } else { @@ -3165,8 +3166,8 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args } /* write the two output bytes */ - buffer[len++] = (char)(targetValue >> 8); - buffer[len++] = (char)targetValue; + buffer[len++] = static_cast(targetValue >> 8); + buffer[len++] = static_cast(targetValue); } else { /* if we cannot find the character after checking all codepages * then this is an error @@ -3181,13 +3182,13 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args if(len == 1) { *target++ = buffer[0]; if(offsets) { - *offsets++ = (int32_t)(source - args->source - 1); /* -1: known to be ASCII */ + *offsets++ = static_cast(source - args->source - 1); /* -1: known to be ASCII */ } } else if(len == 2 && (target + 2) <= targetLimit) { *target++ = buffer[0]; *target++ = buffer[1]; if(offsets) { - int32_t sourceIndex = (int32_t)(source - args->source - U16_LENGTH(sourceChar)); + int32_t sourceIndex = static_cast(source - args->source - U16_LENGTH(sourceChar)); *offsets++ = sourceIndex; *offsets++ = sourceIndex; } @@ -3195,8 +3196,8 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args fromUWriteUInt8( cnv, buffer, len, - &target, (const char *)targetLimit, - &offsets, (int32_t)(source - args->source - U16_LENGTH(sourceChar)), + &target, reinterpret_cast(targetLimit), + &offsets, static_cast(source - args->source - U16_LENGTH(sourceChar)), err); if(U_FAILURE(*err)) { break; @@ -3237,7 +3238,7 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args * this code gives an incorrect result for the rare case of an unmatched * trail surrogate that is alone in the last buffer of the text stream */ - sourceIndex=(int32_t)(source-args->source); + sourceIndex = static_cast(source - args->source); if(sourceIndex>0) { --sourceIndex; if( U16_IS_TRAIL(args->source[sourceIndex]) && @@ -3252,14 +3253,14 @@ UConverter_fromUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterFromUnicodeArgs* args fromUWriteUInt8( cnv, SHIFT_IN_STR, 1, - &target, (const char *)targetLimit, + &target, reinterpret_cast(targetLimit), &offsets, sourceIndex, err); } /*save the state and return */ args->source = source; - args->target = (char*)target; + args->target = reinterpret_cast(target); } @@ -3267,7 +3268,7 @@ static void U_CALLCONV UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UErrorCode* err){ char tempBuf[3]; - const char *mySource = (char *) args->source; + const char* mySource = const_cast(args->source); char16_t *myTarget = args->target; const char *mySourceLimit = args->sourceLimit; uint32_t targetUniChar = 0x0000; @@ -3275,7 +3276,7 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UConverterDataISO2022* myData; ISO2022State *pToU2022State; - myData=(UConverterDataISO2022*)(args->converter->extraInfo); + myData = static_cast(args->converter->extraInfo); pToU2022State = &myData->toU2022State; if(myData->key != 0) { @@ -3295,7 +3296,7 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if(myTarget < args->targetLimit){ - mySourceChar= (unsigned char) *mySource++; + mySourceChar = static_cast(*mySource++); switch(mySourceChar){ case UCNV_SI: @@ -3337,7 +3338,7 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, if(myData->key==0 && U_SUCCESS(*err) && myData->isEmptySegment) { *err = U_ILLEGAL_ESCAPE_SEQUENCE; args->converter->toUCallbackReason = UCNV_IRREGULAR; - args->converter->toULength = (int8_t)(toULengthBefore + (mySource - mySourceBefore)); + args->converter->toULength = static_cast(toULengthBefore + (mySource - mySourceBefore)); } } @@ -3367,7 +3368,7 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, int leadIsOk, trailIsOk; uint8_t trailByte; getTrailByte: - trailByte = (uint8_t)*mySource; + trailByte = static_cast(*mySource); /* * Ticket 5691: consistent illegal sequences: * - We include at least the first byte in the illegal sequence. @@ -3378,23 +3379,23 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, * an ESC/SO/SI, we report only the first byte as the illegal sequence. * Otherwise we convert or report the pair of bytes. */ - leadIsOk = (uint8_t)(mySourceChar - 0x21) <= (0x7e - 0x21); - trailIsOk = (uint8_t)(trailByte - 0x21) <= (0x7e - 0x21); + leadIsOk = static_cast(mySourceChar - 0x21) <= (0x7e - 0x21); + trailIsOk = static_cast(trailByte - 0x21) <= (0x7e - 0x21); if (leadIsOk && trailIsOk) { ++mySource; - tempState = (StateEnum)pToU2022State->cs[pToU2022State->g]; + tempState = static_cast(pToU2022State->cs[pToU2022State->g]); if(tempState >= CNS_11643_0) { cnv = myData->myConverterArray[CNS_11643]; - tempBuf[0] = (char) (0x80+(tempState-CNS_11643_0)); - tempBuf[1] = (char) (mySourceChar); - tempBuf[2] = (char) trailByte; + tempBuf[0] = static_cast(0x80 + (tempState - CNS_11643_0)); + tempBuf[1] = static_cast(mySourceChar); + tempBuf[2] = static_cast(trailByte); tempBufLen = 3; }else{ U_ASSERT(tempStatemyConverterArray[tempState]; - tempBuf[0] = (char) (mySourceChar); - tempBuf[1] = (char) trailByte; + tempBuf[0] = static_cast(mySourceChar); + tempBuf[1] = static_cast(trailByte); tempBufLen = 2; } targetUniChar = ucnv_MBCSSimpleGetNextUChar(cnv, tempBuf, tempBufLen, false); @@ -3410,41 +3411,41 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, pToU2022State->g=pToU2022State->prevG; } } else { - args->converter->toUBytes[0] = (uint8_t)mySourceChar; + args->converter->toUBytes[0] = static_cast(mySourceChar); args->converter->toULength = 1; goto endloop; } } else{ if(mySourceChar <= 0x7f) { - targetUniChar = (char16_t) mySourceChar; + targetUniChar = static_cast(mySourceChar); } } break; } if(targetUniChar < (missingCharMarker-1/*0xfffe*/)){ if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } - *(myTarget++)=(char16_t)targetUniChar; + *(myTarget++) = static_cast(targetUniChar); } else if(targetUniChar > missingCharMarker){ /* disassemble the surrogate pair and write to output*/ targetUniChar-=0x0010000; - *myTarget = (char16_t)(0xd800+(char16_t)(targetUniChar>>10)); + *myTarget = static_cast(0xd800 + static_cast(targetUniChar >> 10)); if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } ++myTarget; if(myTarget< args->targetLimit){ - *myTarget = (char16_t)(0xdc00+(char16_t)(targetUniChar&0x3ff)); + *myTarget = static_cast(0xdc00 + static_cast(targetUniChar & 0x3ff)); if(args->offsets){ - args->offsets[myTarget - args->target] = (int32_t)(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); + args->offsets[myTarget - args->target] = static_cast(mySource - args->source - (mySourceChar <= 0xff ? 1 : 2)); } ++myTarget; }else{ args->converter->UCharErrorBuffer[args->converter->UCharErrorBufferLength++]= - (char16_t)(0xdc00+(char16_t)(targetUniChar&0x3ff)); + static_cast(0xdc00 + static_cast(targetUniChar & 0x3ff)); } } @@ -3468,13 +3469,13 @@ UConverter_toUnicode_ISO_2022_CN_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, static void U_CALLCONV _ISO_2022_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorCode *err) { UConverter *cnv = args->converter; - UConverterDataISO2022 *myConverterData=(UConverterDataISO2022 *) cnv->extraInfo; + UConverterDataISO2022* myConverterData = static_cast(cnv->extraInfo); ISO2022State *pFromU2022State=&myConverterData->fromU2022State; char *p, *subchar; char buffer[8]; int32_t length; - subchar=(char *)cnv->subChars; + subchar = reinterpret_cast(cnv->subChars); length=cnv->subCharLen; /* assume length==1 for most variants */ p = buffer; @@ -3492,7 +3493,7 @@ _ISO_2022_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorC cs = pFromU2022State->cs[0]; if(cs != ASCII && cs != JISX201) { /* not in ASCII or JIS X 0201: switch to ASCII */ - pFromU2022State->cs[0] = (int8_t)ASCII; + pFromU2022State->cs[0] = static_cast(ASCII); *p++ = '\x1b'; *p++ = '\x28'; *p++ = '\x42'; @@ -3534,8 +3535,8 @@ _ISO_2022_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorC int8_t currentSubCharLen = myConverterData->currentConverter->subCharLen; /* set our substitution string into the subconverter */ - myConverterData->currentConverter->subChars = (uint8_t *)subchar; - myConverterData->currentConverter->subCharLen = (int8_t)length; + myConverterData->currentConverter->subChars = reinterpret_cast(subchar); + myConverterData->currentConverter->subCharLen = static_cast(length); /* let the subconverter write the subchar, set/retrieve fromUChar32 state */ args->converter = myConverterData->currentConverter; @@ -3565,7 +3566,7 @@ _ISO_2022_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorC break; } ucnv_cbFromUWriteBytes(args, - buffer, (int32_t)(p - buffer), + buffer, static_cast(p - buffer), offsetIndex, err); } @@ -3656,7 +3657,7 @@ _ISO_2022_GetUnicodeSet(const UConverter *cnv, } #endif - cnvData = (UConverterDataISO2022*)cnv->extraInfo; + cnvData = static_cast(cnv->extraInfo); /* open a set and initialize it with code points that are algorithmically round-tripped */ switch(cnvData->locale[0]){ diff --git a/icu4c/source/common/ucnv_bld.cpp b/icu4c/source/common/ucnv_bld.cpp index 564b645bed76..eb7ae1eaa9da 100644 --- a/icu4c/source/common/ucnv_bld.cpp +++ b/icu4c/source/common/ucnv_bld.cpp @@ -231,7 +231,7 @@ static void ucnv_flushAvailableConverterCache() { gAvailableConverterCount = 0; if (gAvailableConverters) { - uprv_free((char **)gAvailableConverters); + uprv_free(const_cast(gAvailableConverters)); gAvailableConverters = nullptr; } gAvailableConvertersInitOnce.reset(); @@ -270,7 +270,7 @@ static UBool U_CALLCONV isCnvAcceptable(void * /*context*/, const char * /*type*/, const char * /*name*/, const UDataInfo *pInfo) { - return (UBool)( + return static_cast( pInfo->size>=20 && pInfo->isBigEndian==U_IS_BIG_ENDIAN && pInfo->charsetFamily==U_CHARSET_FAMILY && @@ -289,15 +289,15 @@ static UConverterSharedData* ucnv_data_unFlattenClone(UConverterLoadArgs *pArgs, UDataMemory *pData, UErrorCode *status) { /* UDataInfo info; -- necessary only if some converters have different formatVersion */ - const uint8_t *raw = (const uint8_t *)udata_getMemory(pData); - const UConverterStaticData *source = (const UConverterStaticData *) raw; + const uint8_t* raw = static_cast(udata_getMemory(pData)); + const UConverterStaticData* source = reinterpret_cast(raw); UConverterSharedData *data; - UConverterType type = (UConverterType)source->conversionType; + UConverterType type = static_cast(source->conversionType); if(U_FAILURE(*status)) return nullptr; - if( (uint16_t)type >= UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES || + if (static_cast(type) >= UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES || converterData[type] == nullptr || !converterData[type]->isReferenceCounted || converterData[type]->referenceCounter != 1 || @@ -307,7 +307,7 @@ ucnv_data_unFlattenClone(UConverterLoadArgs *pArgs, UDataMemory *pData, UErrorCo return nullptr; } - data = (UConverterSharedData *)uprv_malloc(sizeof(UConverterSharedData)); + data = static_cast(uprv_malloc(sizeof(UConverterSharedData))); if(data == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -397,7 +397,7 @@ getAlgorithmicTypeFromName(const char *realName) lastMid = UINT32_MAX; for (;;) { - mid = (uint32_t)((start + limit) / 2); + mid = (start + limit) / 2; if (lastMid == mid) { /* Have we moved? */ break; /* We haven't moved, and it wasn't found. */ } @@ -491,7 +491,7 @@ ucnv_getSharedConverterData(const char *name) { UConverterSharedData *rc; - rc = (UConverterSharedData*)uhash_get(SHARED_DATA_HASHTABLE, name); + rc = static_cast(uhash_get(SHARED_DATA_HASHTABLE, name)); UCNV_DEBUG_LOG("get",name,rc); return rc; } @@ -682,8 +682,8 @@ parseConverterOptions(const char *inName, if(c==0) { pArgs->options=(pPieces->options&=~UCNV_OPTION_VERSION); return; - } else if((uint8_t)(c-'0')<10) { - pArgs->options=pPieces->options=(pPieces->options&~UCNV_OPTION_VERSION)|(uint32_t)(c-'0'); + } else if (static_cast(c - '0') < 10) { + pArgs->options = pPieces->options = (pPieces->options & ~UCNV_OPTION_VERSION) | static_cast(c - '0'); ++inName; } } else if(uprv_strncmp(inName, "swaplfnl", 8)==0) { @@ -909,7 +909,7 @@ ucnv_createAlgorithmicConverter(UConverter *myUConverter, stackArgs.options = options; stackArgs.locale=locale; cnv = ucnv_createConverterFromSharedData( - myUConverter, (UConverterSharedData *)sharedData, + myUConverter, const_cast(sharedData), &stackArgs, err); UTRACE_EXIT_PTR_STATUS(cnv, *err); @@ -1112,7 +1112,7 @@ static void U_CALLCONV initAvailableConvertersList(UErrorCode &errCode) { } /* We can't have more than "*converterTable" converters to open */ - gAvailableConverters = (const char **) uprv_malloc(allConverterCount * sizeof(char*)); + gAvailableConverters = static_cast(uprv_malloc(allConverterCount * sizeof(char*))); if (!gAvailableConverters) { errCode = U_MEMORY_ALLOCATION_ERROR; return; diff --git a/icu4c/source/common/ucnv_ct.cpp b/icu4c/source/common/ucnv_ct.cpp index 46f30e5ece6d..aa0a6a1169b4 100644 --- a/icu4c/source/common/ucnv_ct.cpp +++ b/icu4c/source/common/ucnv_ct.cpp @@ -368,7 +368,7 @@ UConverter_fromUnicode_CompoundText_OFFSETS(UConverterFromUnicodeArgs* args, UEr /*look ahead to find the trail surrogate*/ if(source < sourceLimit) { /* test the following code unit */ - char16_t trail=(char16_t) *source; + char16_t trail = *source; if(U16_IS_TRAIL(trail)) { source++; sourceChar=U16_GET_SUPPLEMENTARY(sourceChar, trail); diff --git a/icu4c/source/common/ucnv_ext.cpp b/icu4c/source/common/ucnv_ext.cpp index 10d00a62c2ce..1f12d05b265e 100644 --- a/icu4c/source/common/ucnv_ext.cpp +++ b/icu4c/source/common/ucnv_ext.cpp @@ -41,8 +41,8 @@ ucnv_extFindToU(const uint32_t *toUSection, int32_t length, uint8_t byte) { int32_t i, start, limit; /* check the input byte against the lowest and highest section bytes */ - start=(int32_t)UCNV_EXT_TO_U_GET_BYTE(toUSection[0]); - limit=(int32_t)UCNV_EXT_TO_U_GET_BYTE(toUSection[length-1]); + start = static_cast(UCNV_EXT_TO_U_GET_BYTE(toUSection[0])); + limit = static_cast(UCNV_EXT_TO_U_GET_BYTE(toUSection[length - 1])); if(byte(pre[i++]); } else if(j(src[j++]); } else { /* all input consumed, partial match */ if(flush || (length=(i+j))>UCNV_EXT_MAX_BYTES) { @@ -206,7 +206,7 @@ ucnv_extMatchToU(const int32_t *cx, int8_t sisoState, } else { if(UCNV_EXT_TO_U_IS_PARTIAL(value)) { /* partial match, continue */ - idx=(int32_t)UCNV_EXT_TO_U_GET_PARTIAL_INDEX(value); + idx = static_cast(UCNV_EXT_TO_U_GET_PARTIAL_INDEX(value)); } else { if( (UCNV_EXT_TO_U_IS_ROUNDTRIP(value) || TO_U_USE_FALLBACK(useFallback)) && @@ -572,7 +572,7 @@ ucnv_extMatchFromU(const int32_t *cx, if(UCNV_EXT_TO_U_IS_PARTIAL(value)) { /* partial match, enter the loop below */ - idx=(int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value); + idx = static_cast(UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value)); /* initialize */ fromUTableUChars=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_UCHARS_INDEX, char16_t); @@ -627,7 +627,7 @@ ucnv_extMatchFromU(const int32_t *cx, value=fromUSectionValues[idx]; if(UCNV_EXT_FROM_U_IS_PARTIAL(value)) { /* partial match, continue */ - idx=(int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value); + idx = static_cast(UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value)); } else { if(extFromUUseMapping(useFallback, value, firstCP)) { /* full match, stop with result */ @@ -679,7 +679,7 @@ ucnv_extWriteFromU(UConverter *cnv, const int32_t *cx, int32_t length, prevLength; length=UCNV_EXT_FROM_U_GET_LENGTH(value); - value=(uint32_t)UCNV_EXT_FROM_U_GET_DATA(value); + value = UCNV_EXT_FROM_U_GET_DATA(value); /* output the result */ if(length<=UCNV_EXT_FROM_U_MAX_DIRECT_LENGTH) { @@ -692,13 +692,13 @@ ucnv_extWriteFromU(UConverter *cnv, const int32_t *cx, uint8_t *p=buffer+1; /* reserve buffer[0] for shiftByte below */ switch(length) { case 3: - *p++=(uint8_t)(value>>16); + *p++ = static_cast(value >> 16); U_FALLTHROUGH; case 2: - *p++=(uint8_t)(value>>8); + *p++ = static_cast(value >> 8); U_FALLTHROUGH; case 1: - *p++=(uint8_t)value; + *p++ = static_cast(value); U_FALLTHROUGH; default: break; /* will never occur */ @@ -716,11 +716,11 @@ ucnv_extWriteFromU(UConverter *cnv, const int32_t *cx, if(prevLength>1 && length==1) { /* change from double-byte mode to single-byte */ - shiftByte=(uint8_t)UCNV_SI; + shiftByte = static_cast(UCNV_SI); cnv->fromUnicodeStatus=1; } else if(prevLength==1 && length>1) { /* change from single-byte mode to double-byte */ - shiftByte=(uint8_t)UCNV_SO; + shiftByte = static_cast(UCNV_SO); cnv->fromUnicodeStatus=2; } else { shiftByte=0; @@ -737,7 +737,7 @@ ucnv_extWriteFromU(UConverter *cnv, const int32_t *cx, } } - ucnv_fromUWriteBytes(cnv, (const char *)result, length, + ucnv_fromUWriteBytes(cnv, reinterpret_cast(result), length, target, targetLimit, offsets, srcIndex, pErrorCode); @@ -830,7 +830,7 @@ ucnv_extSimpleMatchFromU(const int32_t *cx, isRoundtrip=UCNV_EXT_FROM_U_IS_ROUNDTRIP(value); length=UCNV_EXT_FROM_U_GET_LENGTH(value); - value=(uint32_t)UCNV_EXT_FROM_U_GET_DATA(value); + value = UCNV_EXT_FROM_U_GET_DATA(value); if(length<=UCNV_EXT_FROM_U_MAX_DIRECT_LENGTH) { *pValue=value; @@ -1018,7 +1018,7 @@ ucnv_extGetUnicodeSetString(const UConverterSharedData *sharedData, ucnv_extGetUnicodeSetString( sharedData, cx, sa, which, minLength, firstCP, s, length+1, - (int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value), + static_cast(UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value)), pErrorCode); } else if(extSetUseMapping(which, minLength, value)) { sa->addString(sa->set, s, length+1); diff --git a/icu4c/source/common/ucnv_io.cpp b/icu4c/source/common/ucnv_io.cpp index 48bb5be42bd5..abd19022ebb3 100644 --- a/icu4c/source/common/ucnv_io.cpp +++ b/icu4c/source/common/ucnv_io.cpp @@ -205,7 +205,7 @@ static UBool U_CALLCONV isAcceptable(void * /*context*/, const char * /*type*/, const char * /*name*/, const UDataInfo *pInfo) { - return (UBool)( + return static_cast( pInfo->size>=20 && pInfo->isBigEndian==U_IS_BIG_ENDIAN && pInfo->charsetFamily==U_CHARSET_FAMILY && @@ -244,8 +244,8 @@ static void U_CALLCONV initAliasData(UErrorCode &errCode) { return; } - sectionSizes = (const uint32_t *)udata_getMemory(data); - table = (const uint16_t *)sectionSizes; + sectionSizes = static_cast(udata_getMemory(data)); + table = reinterpret_cast(sectionSizes); tableStart = sectionSizes[0]; if (tableStart < minTocLength) { @@ -289,10 +289,10 @@ static void U_CALLCONV initAliasData(UErrorCode &errCode) { currOffset += gMainTable.taggedAliasListsSize; if (gMainTable.optionTableSize > 0 - && ((const UConverterAliasOptions *)(table + currOffset))->stringNormalizationType < UCNV_IO_NORM_TYPE_COUNT) + && reinterpret_cast(table + currOffset)->stringNormalizationType < UCNV_IO_NORM_TYPE_COUNT) { /* Faster table */ - gMainTable.optionTable = (const UConverterAliasOptions *)(table + currOffset); + gMainTable.optionTable = reinterpret_cast(table + currOffset); } else { /* Smaller table, or I can't handle this normalization mode! @@ -321,7 +321,7 @@ isAlias(const char *alias, UErrorCode *pErrorCode) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return false; } - return (UBool)(*alias!=0); + return static_cast(*alias != 0); } static uint32_t getTagNumber(const char *tagname) { @@ -574,7 +574,7 @@ findConverter(const char *alias, UBool *containsOption, UErrorCode *pErrorCode) lastMid = UINT32_MAX; for (;;) { - mid = (uint32_t)((start + limit) / 2); + mid = (start + limit) / 2; if (lastMid == mid) { /* Have we moved? */ break; /* We haven't moved, and it wasn't found. */ } @@ -601,8 +601,8 @@ findConverter(const char *alias, UBool *containsOption, UErrorCode *pErrorCode) /* State whether the canonical converter name contains an option. This information is contained in this list in order to maintain backward & forward compatibility. */ if (containsOption) { - UBool containsCnvOptionInfo = (UBool)gMainTable.optionTable->containsCnvOptionInfo; - *containsOption = (UBool)((containsCnvOptionInfo + UBool containsCnvOptionInfo = static_cast(gMainTable.optionTable->containsCnvOptionInfo); + *containsOption = static_cast((containsCnvOptionInfo && ((gMainTable.untaggedConvArray[mid] & UCNV_CONTAINS_OPTION_BIT) != 0)) || !containsCnvOptionInfo); } @@ -939,7 +939,7 @@ static uint16_t ucnv_io_countStandards(UErrorCode *pErrorCode) { if (haveAliasData(pErrorCode)) { /* Don't include the empty list */ - return (uint16_t)(gMainTable.tagListSize - UCNV_NUM_HIDDEN_TAGS); + return static_cast(gMainTable.tagListSize - UCNV_NUM_HIDDEN_TAGS); } return 0; @@ -1130,8 +1130,9 @@ io_compareRows(const void *context, const void *left, const void *right) { TempAliasTable *tempTable=(TempAliasTable *)context; const char *chars=tempTable->chars; - return (int32_t)uprv_strcmp(tempTable->stripForCompare(strippedLeft, chars+2*((const TempRow *)left)->strIndex), - tempTable->stripForCompare(strippedRight, chars+2*((const TempRow *)right)->strIndex)); + return static_cast(uprv_strcmp( + tempTable->stripForCompare(strippedLeft, chars + 2 * static_cast(left)->strIndex), + tempTable->stripForCompare(strippedRight, chars + 2 * static_cast(right)->strIndex))); } U_CAPI int32_t U_EXPORT2 diff --git a/icu4c/source/common/ucnv_lmb.cpp b/icu4c/source/common/ucnv_lmb.cpp index ab14a119efb8..bbcf2d579aad 100644 --- a/icu4c/source/common/ucnv_lmb.cpp +++ b/icu4c/source/common/ucnv_lmb.cpp @@ -633,7 +633,7 @@ _LMBCSOpenWorker(UConverter* _this, UErrorCode* err, ulmbcs_byte_t OptGroup) { - UConverterDataLMBCS * extraInfo = (UConverterDataLMBCS*)uprv_malloc (sizeof (UConverterDataLMBCS)); + UConverterDataLMBCS* extraInfo = static_cast(uprv_malloc(sizeof(UConverterDataLMBCS))); _this->extraInfo = extraInfo; if(extraInfo != nullptr) { diff --git a/icu4c/source/common/ucnv_u16.cpp b/icu4c/source/common/ucnv_u16.cpp index c3bcfef50cb5..a5963e1202cb 100644 --- a/icu4c/source/common/ucnv_u16.cpp +++ b/icu4c/source/common/ucnv_u16.cpp @@ -236,10 +236,10 @@ _UTF16BEFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* output length bytes with overflow (length>targetCapacity>0) */ ucnv_fromUWriteBytes(cnv, overflow, length, - (char **)&target, pArgs->targetLimit, + &target, pArgs->targetLimit, &offsets, sourceIndex, pErrorCode); - targetCapacity=(uint32_t)(pArgs->targetLimit-(char *)target); + targetCapacity = static_cast(pArgs->targetLimit - target); } if(U_SUCCESS(*pErrorCode) && sourcesourceLimit && targetCapacity==0) { @@ -248,7 +248,7 @@ _UTF16BEFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* write back the updated pointers */ pArgs->source=source; - pArgs->target=(char *)target; + pArgs->target = target; pArgs->offsets=offsets; } @@ -840,7 +840,7 @@ _UTF16LEFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, &target, pArgs->targetLimit, &offsets, sourceIndex, pErrorCode); - targetCapacity=(uint32_t)(pArgs->targetLimit-(char *)target); + targetCapacity = static_cast(pArgs->targetLimit - target); } if(U_SUCCESS(*pErrorCode) && sourcesourceLimit && targetCapacity==0) { diff --git a/icu4c/source/common/ucnv_u8.cpp b/icu4c/source/common/ucnv_u8.cpp index cf3bb22a02a7..18c57c61482a 100644 --- a/icu4c/source/common/ucnv_u8.cpp +++ b/icu4c/source/common/ucnv_u8.cpp @@ -49,8 +49,8 @@ U_CFUNC void ucnv_fromUnicode_UTF8_OFFSETS_LOGIC(UConverterFromUnicodeArgs *args #define MAXIMUM_UCS2 0x0000FFFF static const uint32_t offsetsFromUTF8[5] = {0, - (uint32_t) 0x00000000, (uint32_t) 0x00003080, (uint32_t) 0x000E2080, - (uint32_t) 0x03C82080 + static_cast(0x00000000), static_cast(0x00003080), + static_cast(0x000E2080), static_cast(0x03C82080) }; static UBool hasCESU8Data(const UConverter *cnv) @@ -58,7 +58,7 @@ static UBool hasCESU8Data(const UConverter *cnv) #if UCONFIG_ONLY_HTML_CONVERSION return false; #else - return (UBool)(cnv->sharedData == &_CESU8Data); + return static_cast(cnv->sharedData == &_CESU8Data); #endif } U_CDECL_BEGIN @@ -571,7 +571,7 @@ static UChar32 U_CALLCONV ucnv_getNextUChar_UTF8(UConverterToUnicodeArgs *args, return 0xffff; } - myByte = (uint8_t)*(source++); + myByte = *(source++); if (U8_IS_SINGLE(myByte)) { args->source = (const char *)source; diff --git a/icu4c/source/common/ucnvbocu.cpp b/icu4c/source/common/ucnvbocu.cpp index 3b736aa1e908..5c9bb3ac456a 100644 --- a/icu4c/source/common/ucnvbocu.cpp +++ b/icu4c/source/common/ucnvbocu.cpp @@ -338,7 +338,7 @@ packDiff(int32_t diff) { */ result|=BOCU1_TRAIL_TO_BYTE(diff)<<16; - result|=((uint32_t)BOCU1_START_POS_4)<<24; + result |= static_cast(BOCU1_START_POS_4) << 24; } } else { /* two- to four-byte negative differences */ @@ -405,13 +405,13 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; - target=(uint8_t *)pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + target = reinterpret_cast(pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); offsets=pArgs->offsets; /* get the converter state from UConverter */ c=cnv->fromUChar32; - prev=(int32_t)cnv->fromUnicodeStatus; + prev = static_cast(cnv->fromUnicodeStatus); if(prev==0) { prev=BOCU1_ASCII_PREV; } @@ -428,7 +428,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, fastSingle: /* fast loop for single-byte differences */ /* use only one loop counter variable, targetCapacity, not also source */ - diff=(int32_t)(sourceLimit-source); + diff = static_cast(sourceLimit - source); if(targetCapacity>diff) { targetCapacity=diff; } @@ -437,7 +437,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(uint8_t)c; + *target++ = static_cast(c); *offsets++=nextSourceIndex++; ++source; --targetCapacity; @@ -445,7 +445,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, diff=c-prev; if(DIFF_IS_SINGLE(diff)) { prev=BOCU1_SIMPLE_PREV(c); - *target++=(uint8_t)PACK_SINGLE_DIFF(diff); + *target++ = static_cast(PACK_SINGLE_DIFF(diff)); *offsets++=nextSourceIndex++; ++source; --targetCapacity; @@ -455,7 +455,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, } } /* restore real values */ - targetCapacity=(int32_t)((const uint8_t *)pArgs->targetLimit-target); + targetCapacity = static_cast(reinterpret_cast(pArgs->targetLimit) - target); sourceIndex=nextSourceIndex; /* wrong if offsets==nullptr but does not matter */ /* regular loop for all cases */ @@ -473,7 +473,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(uint8_t)c; + *target++ = static_cast(c); *offsets++=sourceIndex; --targetCapacity; @@ -510,7 +510,7 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, diff=c-prev; prev=BOCU1_PREV(c); if(DIFF_IS_SINGLE(diff)) { - *target++=(uint8_t)PACK_SINGLE_DIFF(diff); + *target++ = static_cast(PACK_SINGLE_DIFF(diff)); *offsets++=sourceIndex; --targetCapacity; sourceIndex=nextSourceIndex; @@ -531,8 +531,8 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); diff+=BOCU1_START_NEG_2; } - *target++=(uint8_t)diff; - *target++=(uint8_t)BOCU1_TRAIL_TO_BYTE(m); + *target++ = static_cast(diff); + *target++ = static_cast(BOCU1_TRAIL_TO_BYTE(m)); *offsets++=sourceIndex; *offsets++=sourceIndex; targetCapacity-=2; @@ -549,18 +549,18 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, switch(length) { /* each branch falls through to the next one */ case 4: - *target++=(uint8_t)(diff>>24); + *target++ = static_cast(diff >> 24); *offsets++=sourceIndex; U_FALLTHROUGH; case 3: - *target++=(uint8_t)(diff>>16); + *target++ = static_cast(diff >> 16); *offsets++=sourceIndex; U_FALLTHROUGH; case 2: - *target++=(uint8_t)(diff>>8); + *target++ = static_cast(diff >> 8); *offsets++=sourceIndex; /* case 1: handled above */ - *target++=(uint8_t)diff; + *target++ = static_cast(diff); *offsets++=sourceIndex; U_FALLTHROUGH; default: @@ -584,34 +584,34 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, switch(length) { /* each branch falls through to the next one */ case 3: - *charErrorBuffer++=(uint8_t)(diff>>16); + *charErrorBuffer++ = static_cast(diff >> 16); U_FALLTHROUGH; case 2: - *charErrorBuffer++=(uint8_t)(diff>>8); + *charErrorBuffer++ = static_cast(diff >> 8); U_FALLTHROUGH; case 1: - *charErrorBuffer=(uint8_t)diff; + *charErrorBuffer = static_cast(diff); U_FALLTHROUGH; default: /* will never occur */ break; } - cnv->charErrorBufferLength=(int8_t)length; + cnv->charErrorBufferLength = static_cast(length); /* now output what fits into the regular target */ diff>>=8*length; /* length was reduced by targetCapacity */ switch(targetCapacity) { /* each branch falls through to the next one */ case 3: - *target++=(uint8_t)(diff>>16); + *target++ = static_cast(diff >> 16); *offsets++=sourceIndex; U_FALLTHROUGH; case 2: - *target++=(uint8_t)(diff>>8); + *target++ = static_cast(diff >> 8); *offsets++=sourceIndex; U_FALLTHROUGH; case 1: - *target++=(uint8_t)diff; + *target++ = static_cast(diff); *offsets++=sourceIndex; U_FALLTHROUGH; default: @@ -634,11 +634,11 @@ _Bocu1FromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* set the converter state back into UConverter */ cnv->fromUChar32= c<0 ? -c : 0; - cnv->fromUnicodeStatus=(uint32_t)prev; + cnv->fromUnicodeStatus = static_cast(prev); /* write back the updated pointers */ pArgs->source=source; - pArgs->target=(char *)target; + pArgs->target = reinterpret_cast(target); pArgs->offsets=offsets; } @@ -663,12 +663,12 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; - target=(uint8_t *)pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + target = reinterpret_cast(pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); /* get the converter state from UConverter */ c=cnv->fromUChar32; - prev=(int32_t)cnv->fromUnicodeStatus; + prev = static_cast(cnv->fromUnicodeStatus); if(prev==0) { prev=BOCU1_ASCII_PREV; } @@ -681,7 +681,7 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, fastSingle: /* fast loop for single-byte differences */ /* use only one loop counter variable, targetCapacity, not also source */ - diff=(int32_t)(sourceLimit-source); + diff = static_cast(sourceLimit - source); if(targetCapacity>diff) { targetCapacity=diff; } @@ -690,12 +690,12 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(uint8_t)c; + *target++ = static_cast(c); } else { diff=c-prev; if(DIFF_IS_SINGLE(diff)) { prev=BOCU1_SIMPLE_PREV(c); - *target++=(uint8_t)PACK_SINGLE_DIFF(diff); + *target++ = static_cast(PACK_SINGLE_DIFF(diff)); } else { break; } @@ -704,7 +704,7 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, --targetCapacity; } /* restore real values */ - targetCapacity=(int32_t)((const uint8_t *)pArgs->targetLimit-target); + targetCapacity = static_cast(reinterpret_cast(pArgs->targetLimit) - target); /* regular loop for all cases */ while(source(c); --targetCapacity; continue; } @@ -753,7 +753,7 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, diff=c-prev; prev=BOCU1_PREV(c); if(DIFF_IS_SINGLE(diff)) { - *target++=(uint8_t)PACK_SINGLE_DIFF(diff); + *target++ = static_cast(PACK_SINGLE_DIFF(diff)); --targetCapacity; if(c<0x3000) { goto fastSingle; @@ -772,8 +772,8 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, NEGDIVMOD(diff, BOCU1_TRAIL_COUNT, m); diff+=BOCU1_START_NEG_2; } - *target++=(uint8_t)diff; - *target++=(uint8_t)BOCU1_TRAIL_TO_BYTE(m); + *target++ = static_cast(diff); + *target++ = static_cast(BOCU1_TRAIL_TO_BYTE(m)); targetCapacity-=2; } else { int32_t length; /* will be 2..4 */ @@ -787,14 +787,14 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, switch(length) { /* each branch falls through to the next one */ case 4: - *target++=(uint8_t)(diff>>24); + *target++ = static_cast(diff >> 24); U_FALLTHROUGH; case 3: - *target++=(uint8_t)(diff>>16); + *target++ = static_cast(diff >> 16); /* case 2: handled above */ - *target++=(uint8_t)(diff>>8); + *target++ = static_cast(diff >> 8); /* case 1: handled above */ - *target++=(uint8_t)diff; + *target++ = static_cast(diff); U_FALLTHROUGH; default: /* will never occur */ @@ -816,32 +816,32 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, switch(length) { /* each branch falls through to the next one */ case 3: - *charErrorBuffer++=(uint8_t)(diff>>16); + *charErrorBuffer++ = static_cast(diff >> 16); U_FALLTHROUGH; case 2: - *charErrorBuffer++=(uint8_t)(diff>>8); + *charErrorBuffer++ = static_cast(diff >> 8); U_FALLTHROUGH; case 1: - *charErrorBuffer=(uint8_t)diff; + *charErrorBuffer = static_cast(diff); U_FALLTHROUGH; default: /* will never occur */ break; } - cnv->charErrorBufferLength=(int8_t)length; + cnv->charErrorBufferLength = static_cast(length); /* now output what fits into the regular target */ diff>>=8*length; /* length was reduced by targetCapacity */ switch(targetCapacity) { /* each branch falls through to the next one */ case 3: - *target++=(uint8_t)(diff>>16); + *target++ = static_cast(diff >> 16); U_FALLTHROUGH; case 2: - *target++=(uint8_t)(diff>>8); + *target++ = static_cast(diff >> 8); U_FALLTHROUGH; case 1: - *target++=(uint8_t)diff; + *target++ = static_cast(diff); U_FALLTHROUGH; default: /* will never occur */ @@ -863,11 +863,11 @@ _Bocu1FromUnicode(UConverterFromUnicodeArgs *pArgs, /* set the converter state back into UConverter */ cnv->fromUChar32= c<0 ? -c : 0; - cnv->fromUnicodeStatus=(uint32_t)prev; + cnv->fromUnicodeStatus = static_cast(prev); /* write back the updated pointers */ pArgs->source=source; - pArgs->target=(char *)target; + pArgs->target = reinterpret_cast(target); } /* BOCU-1-to-Unicode conversion functions ----------------------------------- */ @@ -887,11 +887,11 @@ decodeBocu1LeadByte(int32_t b) { /* positive difference */ if(b=BOCU1_START_NEG_3) { /* two bytes */ - diff=((int32_t)b-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; + diff = (b - BOCU1_START_NEG_2) * BOCU1_TRAIL_COUNT + BOCU1_REACH_NEG_1; count=1; } else if(b>BOCU1_MIN) { /* three bytes */ - diff=((int32_t)b-BOCU1_START_NEG_3)*BOCU1_TRAIL_COUNT*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_2; + diff = (b - BOCU1_START_NEG_3) * BOCU1_TRAIL_COUNT * BOCU1_TRAIL_COUNT + BOCU1_REACH_NEG_2; count=2; } else { /* four bytes */ @@ -916,7 +916,7 @@ decodeBocu1LeadByte(int32_t b) { } /* return the state for decoding the trail byte(s) */ - return ((uint32_t)diff<<2)|count; + return (static_cast(diff) << 2) | count; } /** @@ -970,14 +970,14 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* set up the local pointers */ cnv=pArgs->converter; - source=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); target=pArgs->target; targetLimit=pArgs->targetLimit; offsets=pArgs->offsets; /* get the converter state from UConverter */ - prev=(int32_t)cnv->toUnicodeStatus; + prev = static_cast(cnv->toUnicodeStatus); if(prev==0) { prev=BOCU1_ASCII_PREV; } @@ -1000,8 +1000,8 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, fastSingle: /* fast loop for single-byte differences */ /* use count as the only loop counter variable */ - diff=(int32_t)(sourceLimit-source); - count=(int32_t)(pArgs->targetLimit-target); + diff = static_cast(sourceLimit - source); + count = static_cast(pArgs->targetLimit - target); if(count>diff) { count=diff; } @@ -1009,7 +1009,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, if(BOCU1_START_NEG_2<=(c=*source) && c(c); *offsets++=nextSourceIndex++; prev=BOCU1_SIMPLE_PREV(c); } else { @@ -1019,7 +1019,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(char16_t)c; + *target++ = static_cast(c); *offsets++=nextSourceIndex++; } else { break; @@ -1043,7 +1043,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* Write a code point directly from a single-byte difference. */ c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { - *target++=(char16_t)c; + *target++ = static_cast(c); *offsets++=sourceIndex; prev=BOCU1_SIMPLE_PREV(c); sourceIndex=nextSourceIndex; @@ -1057,22 +1057,22 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(char16_t)c; + *target++ = static_cast(c); *offsets++=sourceIndex; sourceIndex=nextSourceIndex; continue; } else if(BOCU1_START_NEG_3<=c && c=BOCU1_MIDDLE) { - diff=((int32_t)c-BOCU1_START_POS_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_1+1; + diff = (c - BOCU1_START_POS_2) * BOCU1_TRAIL_COUNT + BOCU1_REACH_POS_1 + 1; } else { - diff=((int32_t)c-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; + diff = (c - BOCU1_START_NEG_2) * BOCU1_TRAIL_COUNT + BOCU1_REACH_NEG_1; } /* trail byte */ ++nextSourceIndex; c=decodeBocu1TrailByte(1, *source++); - if(c<0 || (uint32_t)(c=prev+diff+c)>0x10ffff) { + if (c < 0 || static_cast(c = prev + diff + c) > 0x10ffff) { bytes[0]=source[-2]; bytes[1]=source[-1]; byteIndex=2; @@ -1090,7 +1090,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, * with the partial difference value from the lead byte and * with the number of trail bytes. */ - bytes[0]=(uint8_t)c; + bytes[0] = static_cast(c); byteIndex=1; diff=decodeBocu1LeadByte(c); @@ -1116,7 +1116,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* final trail byte, deliver a code point */ byteIndex=0; c=prev+diff; - if((uint32_t)c>0x10ffff) { + if (static_cast(c) > 0x10ffff) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } @@ -1128,7 +1128,7 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* calculate the next prev and output c */ prev=BOCU1_PREV(c); if(c<=0xffff) { - *target++=(char16_t)c; + *target++ = static_cast(c); *offsets++=sourceIndex; } else { /* output surrogate pair */ @@ -1156,13 +1156,13 @@ _Bocu1ToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, cnv->mode=0; } else { /* set the converter state back into UConverter */ - cnv->toUnicodeStatus=(uint32_t)prev; - cnv->mode=(int32_t)((uint32_t)diff<<2)|count; + cnv->toUnicodeStatus = static_cast(prev); + cnv->mode = static_cast(static_cast(diff) << 2) | count; } cnv->toULength=byteIndex; /* write back the updated pointers */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); pArgs->target=target; pArgs->offsets=offsets; } @@ -1189,13 +1189,13 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, /* set up the local pointers */ cnv=pArgs->converter; - source=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); target=pArgs->target; targetLimit=pArgs->targetLimit; /* get the converter state from UConverter */ - prev=(int32_t)cnv->toUnicodeStatus; + prev = static_cast(cnv->toUnicodeStatus); if(prev==0) { prev=BOCU1_ASCII_PREV; } @@ -1214,8 +1214,8 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, fastSingle: /* fast loop for single-byte differences */ /* use count as the only loop counter variable */ - diff=(int32_t)(sourceLimit-source); - count=(int32_t)(pArgs->targetLimit-target); + diff = static_cast(sourceLimit - source); + count = static_cast(pArgs->targetLimit - target); if(count>diff) { count=diff; } @@ -1223,7 +1223,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, if(BOCU1_START_NEG_2<=(c=*source) && c(c); prev=BOCU1_SIMPLE_PREV(c); } else { break; @@ -1232,7 +1232,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(char16_t)c; + *target++ = static_cast(c); } else { break; } @@ -1253,7 +1253,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, /* Write a code point directly from a single-byte difference. */ c=prev+(c-BOCU1_MIDDLE); if(c<0x3000) { - *target++=(char16_t)c; + *target++ = static_cast(c); prev=BOCU1_SIMPLE_PREV(c); goto fastSingle; } @@ -1265,19 +1265,19 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, if(c!=0x20) { prev=BOCU1_ASCII_PREV; } - *target++=(char16_t)c; + *target++ = static_cast(c); continue; } else if(BOCU1_START_NEG_3<=c && c=BOCU1_MIDDLE) { - diff=((int32_t)c-BOCU1_START_POS_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_POS_1+1; + diff = (c - BOCU1_START_POS_2) * BOCU1_TRAIL_COUNT + BOCU1_REACH_POS_1 + 1; } else { - diff=((int32_t)c-BOCU1_START_NEG_2)*BOCU1_TRAIL_COUNT+BOCU1_REACH_NEG_1; + diff = (c - BOCU1_START_NEG_2) * BOCU1_TRAIL_COUNT + BOCU1_REACH_NEG_1; } /* trail byte */ c=decodeBocu1TrailByte(1, *source++); - if(c<0 || (uint32_t)(c=prev+diff+c)>0x10ffff) { + if (c < 0 || static_cast(c = prev + diff + c) > 0x10ffff) { bytes[0]=source[-2]; bytes[1]=source[-1]; byteIndex=2; @@ -1294,7 +1294,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, * with the partial difference value from the lead byte and * with the number of trail bytes. */ - bytes[0]=(uint8_t)c; + bytes[0] = static_cast(c); byteIndex=1; diff=decodeBocu1LeadByte(c); @@ -1319,7 +1319,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, /* final trail byte, deliver a code point */ byteIndex=0; c=prev+diff; - if((uint32_t)c>0x10ffff) { + if (static_cast(c) > 0x10ffff) { *pErrorCode=U_ILLEGAL_CHAR_FOUND; goto endloop; } @@ -1331,7 +1331,7 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, /* calculate the next prev and output c */ prev=BOCU1_PREV(c); if(c<=0xffff) { - *target++=(char16_t)c; + *target++ = static_cast(c); } else { /* output surrogate pair */ *target++=U16_LEAD(c); @@ -1354,13 +1354,13 @@ _Bocu1ToUnicode(UConverterToUnicodeArgs *pArgs, cnv->mode=0; } else { /* set the converter state back into UConverter */ - cnv->toUnicodeStatus=(uint32_t)prev; - cnv->mode=((uint32_t)diff<<2)|count; + cnv->toUnicodeStatus = static_cast(prev); + cnv->mode = (static_cast(diff) << 2) | count; } cnv->toULength=byteIndex; /* write back the updated pointers */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); pArgs->target=target; } diff --git a/icu4c/source/common/ucnvhz.cpp b/icu4c/source/common/ucnvhz.cpp index fa0f2b40ea71..cfef63272cb6 100644 --- a/icu4c/source/common/ucnvhz.cpp +++ b/icu4c/source/common/ucnvhz.cpp @@ -345,7 +345,7 @@ UConverter_fromUnicode_HZ_OFFSETS_LOGIC (UConverterFromUnicodeArgs * args, uint32_t targetUniChar = 0x0000; UChar32 mySourceChar = 0x0000; UConverterDataHZ *myConverterData=(UConverterDataHZ*)args->converter->extraInfo; - UBool isTargetUCharDBCS = (UBool) myConverterData->isTargetUCharDBCS; + UBool isTargetUCharDBCS = myConverterData->isTargetUCharDBCS; UBool oldIsTargetUCharDBCS; int len =0; const char* escSeq=nullptr; @@ -363,7 +363,7 @@ UConverter_fromUnicode_HZ_OFFSETS_LOGIC (UConverterFromUnicodeArgs * args, targetUniChar = missingCharMarker; if (myTargetIndex < targetLength){ - mySourceChar = (char16_t) mySource[mySourceIndex++]; + mySourceChar = mySource[mySourceIndex++]; oldIsTargetUCharDBCS = isTargetUCharDBCS; diff --git a/icu4c/source/common/ucnvisci.cpp b/icu4c/source/common/ucnvisci.cpp index c14dbaa08c66..9f3a8125e28d 100644 --- a/icu4c/source/common/ucnvisci.cpp +++ b/icu4c/source/common/ucnvisci.cpp @@ -174,7 +174,7 @@ isPNJConsonant(UChar32 c) { if (c < 0xa00 || 0xa50 <= c) { return false; } else { - return (UBool)(pnjMap[c - 0xa00] & 1); + return static_cast(pnjMap[c - 0xa00] & 1); } } @@ -183,7 +183,7 @@ isPNJBindiTippi(UChar32 c) { if (c < 0xa00 || 0xa50 <= c) { return false; } else { - return (UBool)(pnjMap[c - 0xa00] >> 1); + return static_cast(pnjMap[c - 0xa00] >> 1); } } U_CDECL_BEGIN @@ -1484,7 +1484,7 @@ UConverter_toUnicode_ISCII_OFFSETS_LOGIC(UConverterToUnicodeArgs *args, UErrorCo */ *err = U_INVALID_CHAR_FOUND; CALLBACK: - args->converter->toUBytes[0] = (uint8_t) sourceChar; + args->converter->toUBytes[0] = sourceChar; args->converter->toULength = 1; break; } diff --git a/icu4c/source/common/ucnvlat1.cpp b/icu4c/source/common/ucnvlat1.cpp index 09206885269d..09473ef16cb9 100644 --- a/icu4c/source/common/ucnvlat1.cpp +++ b/icu4c/source/common/ucnvlat1.cpp @@ -381,7 +381,7 @@ ucnv_Latin1FromUTF8(UConverterFromUnicodeArgs *pFromUArgs, b=*source++; if(U8_IS_SINGLE(b)) { /* convert ASCII */ - *target++=(uint8_t)b; + *target++ = b; --targetCapacity; } else if( /* handle U+0080..U+00FF inline */ b>=0xc2 && b<=0xc3 && diff --git a/icu4c/source/common/ucnvmbcs.cpp b/icu4c/source/common/ucnvmbcs.cpp index d76060398002..6b4d1491a2a6 100644 --- a/icu4c/source/common/ucnvmbcs.cpp +++ b/icu4c/source/common/ucnvmbcs.cpp @@ -665,7 +665,7 @@ enumToU(UConverterMBCSTable *mbcsTable, int8_t stateProps[], if(!enumToU( mbcsTable, stateProps, nextState, offset+MBCS_ENTRY_TRANSITION_OFFSET(entry), - value|(uint32_t)b, + value | static_cast(b), callback, context, pErrorCode)) { return false; @@ -683,7 +683,7 @@ enumToU(UConverterMBCSTable *mbcsTable, int8_t stateProps[], action=MBCS_ENTRY_FINAL_ACTION(entry); if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ - c=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + c = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); } else if(action==MBCS_STATE_VALID_16) { int32_t finalOffset=offset+MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[finalOffset]; @@ -708,7 +708,7 @@ enumToU(UConverterMBCSTable *mbcsTable, int8_t stateProps[], } } else if(action==MBCS_STATE_VALID_DIRECT_20) { /* output supplementary code point */ - c=(UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); + c = static_cast(MBCS_ENTRY_FINAL_VALUE(entry) + 0x10000); } else { c=U_SENTINEL; } @@ -718,7 +718,7 @@ enumToU(UConverterMBCSTable *mbcsTable, int8_t stateProps[], } if(((++b)&0x1f)==0) { if(anyCodePoints>=0) { - if(!callback(context, value|(uint32_t)(b-0x20), codePoints)) { + if (!callback(context, value | static_cast(b - 0x20), codePoints)) { return false; } anyCodePoints=-1; @@ -760,7 +760,7 @@ getStateProp(const int32_t (*stateTable)[256], int8_t stateProps[], int state) { return stateProps[state]; } } - stateProps[state]|=(int8_t)((min>>5)<<3); + stateProps[state] |= static_cast((min >> 5) << 3); /* find last non-ignorable state */ for(max=0xff; min>5); + stateProps[state] |= static_cast(max >> 5); /* recurse further and collect direct-state information */ while(min<=max) { @@ -1117,7 +1117,7 @@ _extFromU(UConverter *cnv, const UConverterSharedData *sharedData, ucnv_extInitialMatchFromU( cnv, cx, cp, source, sourceLimit, - (char **)target, (char *)targetLimit, + reinterpret_cast(target), reinterpret_cast(targetLimit), offsets, sourceIndex, flush, pErrorCode) @@ -1132,7 +1132,7 @@ _extFromU(UConverter *cnv, const UConverterSharedData *sharedData, range=gb18030Ranges[0]; for(i=0; i(cp) && static_cast(cp) <= range[1]) { /* found the Unicode code point, output the four-byte sequence for it */ uint32_t linear; char bytes[4]; @@ -1141,17 +1141,17 @@ _extFromU(UConverter *cnv, const UConverterSharedData *sharedData, linear=range[2]-LINEAR_18030_BASE; /* add the offset from the beginning of the range */ - linear+=((uint32_t)cp-range[0]); + linear += (static_cast(cp) - range[0]); /* turn this into a four-byte sequence */ - bytes[3]=(char)(0x30+linear%10); linear/=10; - bytes[2]=(char)(0x81+linear%126); linear/=126; - bytes[1]=(char)(0x30+linear%10); linear/=10; - bytes[0]=(char)(0x81+linear); + bytes[3] = static_cast(0x30 + linear % 10); linear /= 10; + bytes[2] = static_cast(0x81 + linear % 126); linear /= 126; + bytes[1] = static_cast(0x30 + linear % 10); linear /= 10; + bytes[0] = static_cast(0x81 + linear); /* output this sequence */ ucnv_fromUWriteBytes(cnv, - bytes, 4, (char **)target, (char *)targetLimit, + bytes, 4, reinterpret_cast(target), reinterpret_cast(targetLimit), offsets, sourceIndex, pErrorCode); return 0; } @@ -1181,7 +1181,7 @@ _extToU(UConverter *cnv, const UConverterSharedData *sharedData, if( (cx=sharedData->mbcs.extIndexes)!=nullptr && ucnv_extInitialMatchToU( cnv, cx, - length, (const char **)source, (const char *)sourceLimit, + length, reinterpret_cast(source), reinterpret_cast(sourceLimit), target, targetLimit, offsets, sourceIndex, flush, @@ -1273,7 +1273,7 @@ _EBCDICSwapLFNL(UConverterSharedData *sharedData, UErrorCode *pErrorCode) { table=mbcsTable->fromUnicodeTable; bytes=mbcsTable->fromUnicodeBytes; - results=(const uint16_t *)bytes; + results = reinterpret_cast(bytes); /* * Check that this is an EBCDIC table with SBCS portion - @@ -1348,21 +1348,21 @@ _EBCDICSwapLFNL(UConverterSharedData *sharedData, UErrorCode *pErrorCode) { mbcsTable->countStates*1024+ sizeofFromUBytes+ UCNV_MAX_CONVERTER_NAME_LENGTH+20; - p=(uint8_t *)uprv_malloc(size); + p = static_cast(uprv_malloc(size)); if(p==nullptr) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return false; } /* copy and modify the to-Unicode state table */ - newStateTable=(int32_t (*)[256])p; + newStateTable = reinterpret_cast(p); uprv_memcpy(newStateTable, mbcsTable->stateTable, mbcsTable->countStates*1024); newStateTable[0][EBCDIC_LF]=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_NL); newStateTable[0][EBCDIC_NL]=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_LF); /* copy and modify the from-Unicode result table */ - newResults=(uint16_t *)newStateTable[mbcsTable->countStates]; + newResults = reinterpret_cast(newStateTable[mbcsTable->countStates]); uprv_memcpy(newResults, bytes, sizeofFromUBytes); /* conveniently, the table access macros work on the left side of expressions */ @@ -1378,7 +1378,7 @@ _EBCDICSwapLFNL(UConverterSharedData *sharedData, UErrorCode *pErrorCode) { } /* set the canonical converter name */ - name=(char *)newResults+sizeofFromUBytes; + name = reinterpret_cast(newResults) + sizeofFromUBytes; uprv_strcpy(name, sharedData->staticData->name); uprv_strcat(name, UCNV_SWAP_LFNL_OPTION_STRING); @@ -1386,7 +1386,7 @@ _EBCDICSwapLFNL(UConverterSharedData *sharedData, UErrorCode *pErrorCode) { icu::umtx_lock(nullptr); if(mbcsTable->swapLFNLStateTable==nullptr) { mbcsTable->swapLFNLStateTable=newStateTable; - mbcsTable->swapLFNLFromUnicodeBytes=(uint8_t *)newResults; + mbcsTable->swapLFNLFromUnicodeBytes = reinterpret_cast(newResults); mbcsTable->swapLFNLName=name; newStateTable=nullptr; @@ -1413,7 +1413,7 @@ writeStage3Roundtrip(const void *context, uint32_t value, UChar32 codePoints[32] int32_t i, st3; table=mbcsTable->fromUnicodeTable; - bytes=(uint8_t *)mbcsTable->fromUnicodeBytes; + bytes = const_cast(mbcsTable->fromUnicodeBytes); /* for EUC outputTypes, modify the value like genmbcs.c's transformEUC() */ switch(mbcsTable->outputType) { @@ -1454,23 +1454,23 @@ writeStage3Roundtrip(const void *context, uint32_t value, UChar32 codePoints[32] /* locate the stage 2 & 3 data */ stage2=((uint32_t *)table)+table[c>>10]+((c>>4)&0x3f); p=bytes; - st3=(int32_t)(uint16_t)*stage2*16+(c&0xf); + st3 = static_cast(static_cast(*stage2)) * 16 + (c & 0xf); /* write the codepage bytes into stage 3 */ switch(mbcsTable->outputType) { case MBCS_OUTPUT_3: case MBCS_OUTPUT_4_EUC: p+=st3*3; - p[0]=(uint8_t)(value>>16); - p[1]=(uint8_t)(value>>8); - p[2]=(uint8_t)value; + p[0] = static_cast(value >> 16); + p[1] = static_cast(value >> 8); + p[2] = static_cast(value); break; case MBCS_OUTPUT_4: - ((uint32_t *)p)[st3]=value; + reinterpret_cast(p)[st3] = value; break; default: /* 2 bytes per character */ - ((uint16_t *)p)[st3]=(uint16_t)value; + reinterpret_cast(p)[st3] = static_cast(value); break; } @@ -1488,7 +1488,7 @@ reconstituteData(UConverterMBCSTable *mbcsTable, uint16_t *stage1; uint32_t *stage2; uint32_t dataLength=stage1Length*2+fullStage2Length*4+mbcsTable->fromUBytesLength; - mbcsTable->reconstitutedData=(uint8_t *)uprv_malloc(dataLength); + mbcsTable->reconstitutedData = static_cast(uprv_malloc(dataLength)); if(mbcsTable->reconstitutedData==nullptr) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; @@ -1496,29 +1496,29 @@ reconstituteData(UConverterMBCSTable *mbcsTable, uprv_memset(mbcsTable->reconstitutedData, 0, dataLength); /* copy existing data and reroute the pointers */ - stage1=(uint16_t *)mbcsTable->reconstitutedData; + stage1 = reinterpret_cast(mbcsTable->reconstitutedData); uprv_memcpy(stage1, mbcsTable->fromUnicodeTable, stage1Length*2); - stage2=(uint32_t *)(stage1+stage1Length); + stage2 = reinterpret_cast(stage1 + stage1Length); uprv_memcpy(stage2+(fullStage2Length-stage2Length), mbcsTable->fromUnicodeTable+stage1Length, stage2Length*4); mbcsTable->fromUnicodeTable=stage1; - mbcsTable->fromUnicodeBytes=(uint8_t *)(stage2+fullStage2Length); + mbcsTable->fromUnicodeBytes = reinterpret_cast(stage2 + fullStage2Length); /* indexes into stage 2 count from the bottom of the fromUnicodeTable */ - stage2=(uint32_t *)stage1; + stage2 = reinterpret_cast(stage1); /* reconstitute the initial part of stage 2 from the mbcsIndex */ { - int32_t stageUTF8Length=((int32_t)mbcsTable->maxFastUChar+1)>>6; + int32_t stageUTF8Length = (static_cast(mbcsTable->maxFastUChar) + 1) >> 6; int32_t stageUTF8Index=0; int32_t st1, st2, st3, i; for(st1=0; stageUTF8Index(stage1Length) / 2) { /* each stage 2 block has 64 entries corresponding to 16 entries in the mbcsIndex */ for(i=0; i<16; ++i) { st3=mbcsTable->mbcsIndex[stageUTF8Index++]; @@ -1568,13 +1568,13 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, } else if(header->version[0]==5 && header->version[1]>=3 && (header->options&MBCS_OPT_UNKNOWN_INCOMPATIBLE_MASK)==0) { headerLength=header->options&MBCS_OPT_LENGTH_MASK; - noFromU=(UBool)((header->options&MBCS_OPT_NO_FROM_U)!=0); + noFromU = static_cast((header->options & MBCS_OPT_NO_FROM_U) != 0); } else { *pErrorCode=U_INVALID_TABLE_FORMAT; return; } - mbcsTable->outputType=(uint8_t)header->flags; + mbcsTable->outputType = static_cast(header->flags); if(noFromU && mbcsTable->outputType==MBCS_OUTPUT_1) { *pErrorCode=U_INVALID_TABLE_FORMAT; return; @@ -1583,7 +1583,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, /* extension data, header version 4.2 and higher */ offset=header->flags>>8; if(offset!=0) { - mbcsTable->extIndexes=(const int32_t *)(raw+offset); + mbcsTable->extIndexes = reinterpret_cast(raw + offset); } if(mbcsTable->outputType==MBCS_OUTPUT_EXT_ONLY) { @@ -1606,7 +1606,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, } /* load the base table */ - baseName=(const char *)header+headerLength*4; + baseName = reinterpret_cast(header) + headerLength * 4; if(0==uprv_strcmp(baseName, sharedData->staticData->name)) { /* forbid loading this same extension-only file */ *pErrorCode=U_INVALID_TABLE_FORMAT; @@ -1685,7 +1685,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, MBCS_ENTRY_FINAL_ACTION(entry)==MBCS_STATE_CHANGE_ONLY && MBCS_ENTRY_FINAL_STATE(entry)!=0 ) { - mbcsTable->dbcsOnlyState=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); + mbcsTable->dbcsOnlyState = static_cast(MBCS_ENTRY_FINAL_STATE(entry)); mbcsTable->outputType=MBCS_OUTPUT_DBCS_ONLY; } @@ -1702,7 +1702,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, /* allocate a new state table and copy the base state table contents */ count=mbcsTable->countStates; - newStateTable=(int32_t (*)[256])uprv_malloc((count+1)*1024); + newStateTable = static_cast(uprv_malloc((count + 1) * 1024)); if(newStateTable==nullptr) { ucnv_unload(baseSharedData); *pErrorCode=U_MEMORY_ALLOCATION_ERROR; @@ -1725,7 +1725,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, state[i]=MBCS_ENTRY_FINAL(0, MBCS_STATE_ILLEGAL, 0); } mbcsTable->stateTable=(const int32_t (*)[256])newStateTable; - mbcsTable->countStates=(uint8_t)(count+1); + mbcsTable->countStates = static_cast(count + 1); mbcsTable->stateTableOwned=true; mbcsTable->outputType=MBCS_OUTPUT_DBCS_ONLY; @@ -1766,14 +1766,14 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, return; } - mbcsTable->countStates=(uint8_t)header->countStates; + mbcsTable->countStates = static_cast(header->countStates); mbcsTable->countToUFallbacks=header->countToUFallbacks; - mbcsTable->stateTable=(const int32_t (*)[256])(raw+headerLength*4); - mbcsTable->toUFallbacks=(const _MBCSToUFallback *)(mbcsTable->stateTable+header->countStates); - mbcsTable->unicodeCodeUnits=(const uint16_t *)(raw+header->offsetToUCodeUnits); + mbcsTable->stateTable = reinterpret_cast(raw + headerLength * 4); + mbcsTable->toUFallbacks = reinterpret_cast(mbcsTable->stateTable + header->countStates); + mbcsTable->unicodeCodeUnits = reinterpret_cast(raw + header->offsetToUCodeUnits); - mbcsTable->fromUnicodeTable=(const uint16_t *)(raw+header->offsetFromUTable); - mbcsTable->fromUnicodeBytes=(const uint8_t *)(raw+header->offsetFromUBytes); + mbcsTable->fromUnicodeTable = reinterpret_cast(raw + header->offsetFromUTable); + mbcsTable->fromUnicodeBytes = raw + header->offsetFromUBytes; mbcsTable->fromUBytesLength=header->fromUBytesLength; /* @@ -1784,7 +1784,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, udata_getInfo((UDataMemory *)sharedData->dataMemory, &info); if(info.formatVersion[0]>6 || (info.formatVersion[0]==6 && info.formatVersion[1]>=1)) { /* mask off possible future extensions to be safe */ - mbcsTable->unicodeMask=(uint8_t)(sharedData->staticData->unicodeMask&3); + mbcsTable->unicodeMask = static_cast(sharedData->staticData->unicodeMask & 3); } else { /* for older versions, assume worst case: contains anything possible (prevent over-optimizations) */ mbcsTable->unicodeMask=UCNV_HAS_SUPPLEMENTARY|UCNV_HAS_SURROGATES; @@ -1825,10 +1825,10 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, * The .cnv file is prebuilt with an additional stage table with indexes * to each block. */ - mbcsTable->mbcsIndex=(const uint16_t *) - (mbcsTable->fromUnicodeBytes+ + mbcsTable->mbcsIndex = reinterpret_cast( + mbcsTable->fromUnicodeBytes + (noFromU ? 0 : mbcsTable->fromUBytesLength)); - mbcsTable->maxFastUChar=(((char16_t)header->version[2])<<8)|0xff; + mbcsTable->maxFastUChar = (static_cast(header->version[2]) << 8) | 0xff; } } @@ -1839,7 +1839,7 @@ ucnv_MBCSLoad(UConverterSharedData *sharedData, for(i=0; i<0x80; ++i) { if(mbcsTable->stateTable[0][i]!=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, i)) { - asciiRoundtrips&=~((uint32_t)1<<(i>>2)); + asciiRoundtrips &= ~(static_cast(1) << (i >> 2)); } } mbcsTable->asciiRoundtrips=asciiRoundtrips; @@ -1958,7 +1958,7 @@ ucnv_MBCSOpen(UConverter *cnv, extIndexes=mbcsTable->extIndexes; if(extIndexes!=nullptr) { - maxBytesPerUChar=(int8_t)UCNV_GET_MAX_BYTES_PER_UCHAR(extIndexes); + maxBytesPerUChar = static_cast(UCNV_GET_MAX_BYTES_PER_UCHAR(extIndexes)); if(outputType==MBCS_OUTPUT_2_SISO) { ++maxBytesPerUChar; /* SO + multiple DBCS */ } @@ -2048,8 +2048,8 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* set up the local pointers */ cnv=pArgs->converter; - source=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); target=pArgs->target; targetLimit=pArgs->targetLimit; offsets=pArgs->offsets; @@ -2085,7 +2085,7 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, /* test the most common case first */ if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); if(offsets!=nullptr) { *offsets++=sourceIndex; } @@ -2099,17 +2099,17 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ - action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); + action = static_cast(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { entry=MBCS_ENTRY_FINAL_VALUE(entry); /* output surrogate pair */ - *target++=(char16_t)(0xd800|(char16_t)(entry>>10)); + *target++ = static_cast(0xd800 | static_cast(entry >> 10)); if(offsets!=nullptr) { *offsets++=sourceIndex; } - c=(char16_t)(0xdc00|(char16_t)(entry&0x3ff)); + c = static_cast(0xdc00 | static_cast(entry & 0x3ff)); if(target(MBCS_ENTRY_FINAL_VALUE_16(entry)); if(offsets!=nullptr) { *offsets++=sourceIndex; } @@ -2152,7 +2152,7 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, break; } else /* unassigned sequences indicated with byteIndex>0 */ { /* try an extension mapping */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); cnv->toUBytes[0]=*(source-1); cnv->toULength=_extToU(cnv, cnv->sharedData, 1, &source, sourceLimit, @@ -2160,7 +2160,7 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, &offsets, sourceIndex, pArgs->flush, pErrorCode); - sourceIndex+=1+(int32_t)(source-(const uint8_t *)pArgs->source); + sourceIndex += 1 + static_cast(source - reinterpret_cast(pArgs->source)); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ @@ -2170,7 +2170,7 @@ ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, } /* write back the updated pointers */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); pArgs->target=target; pArgs->offsets=offsets; } @@ -2199,10 +2199,10 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, /* set up the local pointers */ cnv=pArgs->converter; - source=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); target=pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); offsets=pArgs->offsets; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { @@ -2219,7 +2219,7 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, * since the conversion here is 1:1 char16_t:uint8_t, we need only one counter * for the minimum of the sourceLength and targetCapacity */ - length=(int32_t)(sourceLimit-source); + length = static_cast(sourceLimit - source); if(length>4; do { oredEntries=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); oredEntries|=entry=stateTable[0][*source++]; - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); /* were all 16 entries really valid? */ if(!MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(oredEntries)) { @@ -2310,7 +2310,7 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, /* test the most common case first */ if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); --targetCapacity; continue; } @@ -2319,11 +2319,11 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ - action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); + action = static_cast(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ - *target++=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + *target++ = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); --targetCapacity; continue; } @@ -2339,7 +2339,7 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, /* set offsets since the start or the last extension */ if(offsets!=nullptr) { - int32_t count=(int32_t)(source-lastSource); + int32_t count = static_cast(source - lastSource); /* predecrement: do not set the offset for the callback-causing character */ while(--count>0) { @@ -2361,7 +2361,7 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, &offsets, sourceIndex, pArgs->flush, pErrorCode); - sourceIndex+=1+(int32_t)(source-lastSource); + sourceIndex += 1 + static_cast(source - lastSource); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ @@ -2369,8 +2369,8 @@ ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, } /* recalculate the targetCapacity after an extension mapping */ - targetCapacity=(int32_t)(pArgs->targetLimit-target); - length=(int32_t)(sourceLimit-source); + targetCapacity = static_cast(pArgs->targetLimit - target); + length = static_cast(sourceLimit - source); if(lengthsource=(const char *)source; + pArgs->source = reinterpret_cast(source); pArgs->target=target; pArgs->offsets=offsets; } @@ -2432,7 +2432,7 @@ hasValidTrailBytes(const int32_t (*stateTable)[256], uint8_t state) { for(b=0; b<=0xff; ++b) { entry=row[b]; if( MBCS_ENTRY_IS_TRANSITION(entry) && - hasValidTrailBytes(stateTable, (uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry)) + hasValidTrailBytes(stateTable, static_cast(MBCS_ENTRY_TRANSITION_STATE(entry))) ) { return true; } @@ -2450,9 +2450,9 @@ isSingleOrLead(const int32_t (*stateTable)[256], uint8_t state, UBool isDBCSOnly const int32_t *row=stateTable[state]; int32_t entry=row[b]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { /* lead byte */ - return hasValidTrailBytes(stateTable, (uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry)); + return hasValidTrailBytes(stateTable, static_cast(MBCS_ENTRY_TRANSITION_STATE(entry))); } else { - uint8_t action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); + uint8_t action = static_cast(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_CHANGE_ONLY && isDBCSOnly) { return false; /* SI/SO are illegal for DBCS-only conversion */ } else { @@ -2890,8 +2890,8 @@ ucnv_MBCSSingleGetNextUChar(UConverterToUnicodeArgs *pArgs, /* set up the local pointers */ cnv=pArgs->converter; - source=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { @@ -2904,27 +2904,27 @@ ucnv_MBCSSingleGetNextUChar(UConverterToUnicodeArgs *pArgs, /* MBCS_ENTRY_IS_FINAL(entry) */ /* write back the updated pointer early so that we can return directly */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ - return (char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + return static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); } /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ - action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); + action = static_cast(MBCS_ENTRY_FINAL_ACTION(entry)); if( action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { /* output supplementary code point */ - return (UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); + return static_cast(MBCS_ENTRY_FINAL_VALUE(entry) + 0x10000); } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ - return (char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + return static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ @@ -2941,7 +2941,7 @@ ucnv_MBCSSingleGetNextUChar(UConverterToUnicodeArgs *pArgs, break; } else /* unassigned sequence */ { /* defer to the generic implementation */ - pArgs->source=(const char *)source-1; + pArgs->source = reinterpret_cast(source) - 1; return UCNV_GET_NEXT_UCHAR_USE_TO_U; } } @@ -2999,8 +2999,8 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, } /* set up the local pointers */ - source=lastSource=(const uint8_t *)pArgs->source; - sourceLimit=(const uint8_t *)pArgs->sourceLimit; + source = lastSource = reinterpret_cast(pArgs->source); + sourceLimit = reinterpret_cast(pArgs->sourceLimit); if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; @@ -3017,7 +3017,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, * then load the DBCS state from the MBCS data * (dbcsOnlyState==0 if it is not a DBCS-only converter) */ - if((state=(uint8_t)(cnv->mode))==0) { + if ((state = static_cast(cnv->mode)) == 0) { state=cnv->sharedData->mbcs.dbcsOnlyState; } @@ -3026,7 +3026,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, while(source(MBCS_ENTRY_TRANSITION_STATE(entry)); offset+=MBCS_ENTRY_TRANSITION_OFFSET(entry); /* optimization for 1/2-byte input and BMP output */ @@ -3036,7 +3036,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, (c=unicodeCodeUnits[offset+MBCS_ENTRY_FINAL_VALUE_16(entry)])<0xfffe ) { ++source; - state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ + state = static_cast(MBCS_ENTRY_FINAL_STATE(entry)); /* typically 0 */ /* output BMP code point */ break; } @@ -3045,16 +3045,16 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, cnv->mode=state; /* set the next state early so that we can reuse the entry variable */ - state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ + state = static_cast(MBCS_ENTRY_FINAL_STATE(entry)); /* typically 0 */ /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ - action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); + action = static_cast(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ - c=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + c = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); break; } else if(action==MBCS_STATE_VALID_16) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); @@ -3092,7 +3092,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { /* output supplementary code point */ - c=(UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); + c = static_cast(MBCS_ENTRY_FINAL_VALUE(entry) + 0x10000); break; } else if(action==MBCS_STATE_CHANGE_ONLY) { /* @@ -3104,7 +3104,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, */ if(cnv->sharedData->mbcs.dbcsOnlyState!=0) { /* SI/SO are illegal for DBCS-only conversion */ - state=(uint8_t)(cnv->mode); /* restore the previous state */ + state = static_cast(cnv->mode); /* restore the previous state */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; @@ -3112,7 +3112,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ - c=(char16_t)MBCS_ENTRY_FINAL_VALUE_16(entry); + c = static_cast(MBCS_ENTRY_FINAL_VALUE_16(entry)); break; } } else if(action==MBCS_STATE_UNASSIGNED) { @@ -3137,7 +3137,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, /* defer to the generic implementation */ cnv->toUnicodeStatus=0; cnv->mode=state; - pArgs->source=(const char *)lastSource; + pArgs->source = reinterpret_cast(lastSource); return UCNV_GET_NEXT_UCHAR_USE_TO_U; } } @@ -3147,7 +3147,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, if(U_SUCCESS(*pErrorCode) && source==sourceLimit && lastSourcetoUBytes; - cnv->toULength=(int8_t)(source-lastSource); + cnv->toULength = static_cast(source - lastSource); do { *bytes++=*lastSource++; } while(lastSourcesharedData->mbcs.dbcsOnlyState!=0); + UBool isDBCSOnly = static_cast(cnv->sharedData->mbcs.dbcsOnlyState != 0); uint8_t *bytes=cnv->toUBytes; *bytes++=*lastSource++; /* first byte */ if(lastSource==source) { @@ -3188,7 +3188,7 @@ ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, cnv->mode=state; /* write back the updated pointer */ - pArgs->source=(const char *)source; + pArgs->source = reinterpret_cast(source); return c; } @@ -3431,8 +3431,8 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* set up the local pointers */ source=pArgs->source; sourceLimit=pArgs->sourceLimit; - target=(uint8_t *)pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + target = reinterpret_cast(pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; @@ -3474,7 +3474,7 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, c=*source++; ++nextSourceIndex; if(c<=0x7f && IS_ASCII_ROUNDTRIP(c, asciiRoundtrips)) { - *target++=(uint8_t)c; + *target++ = static_cast(c); if(offsets!=nullptr) { *offsets++=sourceIndex; sourceIndex=nextSourceIndex; @@ -3562,7 +3562,7 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, &offsets, sourceIndex, pArgs->flush, pErrorCode); - nextSourceIndex+=(int32_t)(source-pArgs->source); + nextSourceIndex += static_cast(source - pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ @@ -3571,7 +3571,7 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ - targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); + targetCapacity = static_cast(pArgs->targetLimit - reinterpret_cast(target)); /* normal end of conversion: prepare for a new character */ sourceIndex=nextSourceIndex; @@ -3584,15 +3584,15 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* from the first if in the loop we know that targetCapacity>0 */ if(value<=0xff) { /* this is easy because we know that there is enough space */ - *target++=(uint8_t)value; + *target++ = static_cast(value); if(offsets!=nullptr) { *offsets++=sourceIndex; } --targetCapacity; } else /* length==2 */ { - *target++=(uint8_t)(value>>8); + *target++ = static_cast(value >> 8); if(2<=targetCapacity) { - *target++=(uint8_t)value; + *target++ = static_cast(value); if(offsets!=nullptr) { *offsets++=sourceIndex; *offsets++=sourceIndex; @@ -3602,7 +3602,7 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, if(offsets!=nullptr) { *offsets++=sourceIndex; } - cnv->charErrorBuffer[0]=(char)value; + cnv->charErrorBuffer[0] = static_cast(value); cnv->charErrorBufferLength=1; /* target overflow */ @@ -3629,7 +3629,7 @@ ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* write back the updated pointers */ pArgs->source=source; - pArgs->target=(char *)target; + pArgs->target = reinterpret_cast(target); pArgs->offsets=offsets; } @@ -3657,13 +3657,13 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; - target=(uint8_t *)pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + target = reinterpret_cast(pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { - results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; + results = reinterpret_cast(cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes); } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } @@ -3675,7 +3675,7 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* use only roundtrips and fallbacks from private-use characters */ minValue=0xc00; } - hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); + hasSupplementary = static_cast(cnv->sharedData->mbcs.unicodeMask & UCNV_HAS_SUPPLEMENTARY); /* get the converter state from UConverter */ c=cnv->fromUChar32; @@ -3749,7 +3749,7 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* assigned, write the output character bytes from value and length */ /* length==1 */ /* this is easy because we know that there is enough space */ - *target++=(uint8_t)value; + *target++ = static_cast(value); if(offsets!=nullptr) { *offsets++=sourceIndex; } @@ -3768,7 +3768,7 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, &offsets, sourceIndex, pArgs->flush, pErrorCode); - nextSourceIndex+=(int32_t)(source-pArgs->source); + nextSourceIndex += static_cast(source - pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ @@ -3777,7 +3777,7 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ - targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); + targetCapacity = static_cast(pArgs->targetLimit - reinterpret_cast(target)); /* normal end of conversion: prepare for a new character */ sourceIndex=nextSourceIndex; @@ -3795,7 +3795,7 @@ ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, /* write back the updated pointers */ pArgs->source=source; - pArgs->target=(char *)target; + pArgs->target = reinterpret_cast(target); pArgs->offsets=offsets; } @@ -3833,13 +3833,13 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; - target=(uint8_t *)pArgs->target; - targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); + target = reinterpret_cast(pArgs->target); + targetCapacity = static_cast(pArgs->targetLimit - pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { - results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; + results = reinterpret_cast(cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes); } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } @@ -3864,7 +3864,7 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, * since the conversion here is 1:1 char16_t:uint8_t, we need only one counter * for the minimum of the sourceLength and targetCapacity */ - length=(int32_t)(sourceLimit-source); + length = static_cast(sourceLimit - source); if(length(c); --targetCapacity; c=0; continue; @@ -3948,7 +3948,7 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, /* assigned, write the output character bytes from value and length */ /* length==1 */ /* this is easy because we know that there is enough space */ - *target++=(uint8_t)value; + *target++ = static_cast(value); --targetCapacity; /* normal end of conversion: prepare for a new character */ @@ -3993,7 +3993,7 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, /* set offsets since the start or the last extension */ if(offsets!=nullptr) { - int32_t count=(int32_t)(source-lastSource); + int32_t count = static_cast(source - lastSource); /* do not set the offset for this character */ count-=length; @@ -4009,11 +4009,11 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, lastSource=source; c=_extFromU(cnv, cnv->sharedData, c, &source, sourceLimit, - &target, (const uint8_t *)(pArgs->targetLimit), + &target, reinterpret_cast(pArgs->targetLimit), &offsets, sourceIndex, pArgs->flush, pErrorCode); - sourceIndex+=length+(int32_t)(source-lastSource); + sourceIndex += length + static_cast(source - lastSource); lastSource=source; if(U_FAILURE(*pErrorCode)) { @@ -4023,8 +4023,8 @@ ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ - targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); - length=(int32_t)(sourceLimit-source); + targetCapacity = static_cast(pArgs->targetLimit - reinterpret_cast(target)); + length = static_cast(sourceLimit - source); if(lengthsource=source; - pArgs->target=(char *)target; + pArgs->target = reinterpret_cast(target); pArgs->offsets=offsets; } @@ -4777,14 +4777,14 @@ ucnv_MBCSFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, ) { /* EBCDIC_STATEFUL ending with DBCS: emit an SI to return the output stream to SBCS */ if(targetCapacity>0) { - *target++=(uint8_t)siBytes[0]; + *target++ = siBytes[0]; if (siLength == 2) { if (targetCapacity<2) { - cnv->charErrorBuffer[0]=(uint8_t)siBytes[1]; + cnv->charErrorBuffer[0] = siBytes[1]; cnv->charErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; } else { - *target++=(uint8_t)siBytes[1]; + *target++ = siBytes[1]; } } if(offsets!=nullptr) { @@ -4793,9 +4793,9 @@ ucnv_MBCSFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, } } else { /* target is full */ - cnv->charErrorBuffer[0]=(uint8_t)siBytes[0]; + cnv->charErrorBuffer[0] = siBytes[0]; if (siLength == 2) { - cnv->charErrorBuffer[1]=(uint8_t)siBytes[1]; + cnv->charErrorBuffer[1] = siBytes[1]; } cnv->charErrorBufferLength=siLength; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; @@ -5042,13 +5042,13 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, cnv=pFromUArgs->converter; source=(uint8_t *)pToUArgs->source; sourceLimit=(uint8_t *)pToUArgs->sourceLimit; - target=(uint8_t *)pFromUArgs->target; - targetCapacity=(int32_t)(pFromUArgs->targetLimit-pFromUArgs->target); + target = reinterpret_cast(pFromUArgs->target); + targetCapacity = static_cast(pFromUArgs->targetLimit - pFromUArgs->target); table=cnv->sharedData->mbcs.fromUnicodeTable; sbcsIndex=cnv->sharedData->mbcs.sbcsIndex; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { - results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; + results = reinterpret_cast(cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes); } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } @@ -5061,13 +5061,13 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, /* use only roundtrips and fallbacks from private-use characters */ minValue=0xc00; } - hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); + hasSupplementary = static_cast(cnv->sharedData->mbcs.unicodeMask & UCNV_HAS_SUPPLEMENTARY); /* get the converter state from the UTF-8 UConverter */ if(utf8->toULength > 0) { toULength=oldToULength=utf8->toULength; - toULimit=(int8_t)utf8->mode; - c=(UChar32)utf8->toUnicodeStatus; + toULimit = static_cast(utf8->mode); + c = static_cast(utf8->toUnicodeStatus); } else { toULength=oldToULength=toULimit=0; c = 0; @@ -5080,7 +5080,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, { // Do not go back into the bytes that will be read for finishing a partial // sequence from the previous buffer. - int32_t length=(int32_t)(sourceLimit-source) - (toULimit-oldToULength); + int32_t length = static_cast(sourceLimit - source) - (toULimit - oldToULength); if(length>0) { uint8_t b1=*(sourceLimit-1); if(U8_IS_SINGLE(b1)) { @@ -5130,7 +5130,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, if(U8_IS_SINGLE(b)) { /* convert ASCII */ if(IS_ASCII_ROUNDTRIP(b, asciiRoundtrips)) { - *target++=(uint8_t)b; + *target++ = b; --targetCapacity; continue; } else { @@ -5141,13 +5141,13 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, if(b<0xe0) { if( /* handle U+0080..U+07FF inline */ b>=0xc2 && - (t1=(uint8_t)(*source-0x80)) <= 0x3f + (t1 = static_cast(*source - 0x80)) <= 0x3f ) { c=b&0x1f; ++source; value=SBCS_RESULT_FROM_UTF8(sbcsIndex, results, c, t1); if(value>=minValue) { - *target++=(uint8_t)value; + *target++ = static_cast(value); --targetCapacity; continue; } else { @@ -5158,14 +5158,14 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, } } else if(b==0xe0) { if( /* handle U+0800..U+0FFF inline */ - (t1=(uint8_t)(source[0]-0x80)) <= 0x3f && t1 >= 0x20 && - (t2=(uint8_t)(source[1]-0x80)) <= 0x3f + (t1 = static_cast(source[0] - 0x80)) <= 0x3f && t1 >= 0x20 && + (t2 = static_cast(source[1] - 0x80)) <= 0x3f ) { c=t1; source+=2; value=SBCS_RESULT_FROM_UTF8(sbcsIndex, results, c, t2); if(value>=minValue) { - *target++=(uint8_t)value; + *target++ = static_cast(value); --targetCapacity; continue; } else { @@ -5212,7 +5212,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, utf8->toULength=toULength; utf8->mode=toULimit; pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); return; } } @@ -5238,7 +5238,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, } utf8->toULength=toULength; pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); *pErrorCode=U_ILLEGAL_CHAR_FOUND; return; } @@ -5247,7 +5247,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, if(value>=minValue) { /* output the mapping for c */ - *target++=(uint8_t)value; + *target++ = static_cast(value); --targetCapacity; } else { /* valuetargetLimit-(char *)target); + targetCapacity = static_cast(pFromUArgs->targetLimit - reinterpret_cast(target)); } } } else { @@ -5315,7 +5315,7 @@ ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, /* write back the updated pointers */ pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); } static void U_CALLCONV @@ -5345,25 +5345,25 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, cnv=pFromUArgs->converter; source=(uint8_t *)pToUArgs->source; sourceLimit=(uint8_t *)pToUArgs->sourceLimit; - target=(uint8_t *)pFromUArgs->target; - targetCapacity=(int32_t)(pFromUArgs->targetLimit-pFromUArgs->target); + target = reinterpret_cast(pFromUArgs->target); + targetCapacity = static_cast(pFromUArgs->targetLimit - pFromUArgs->target); table=cnv->sharedData->mbcs.fromUnicodeTable; mbcsIndex=cnv->sharedData->mbcs.mbcsIndex; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { - results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; + results = reinterpret_cast(cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes); } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; - hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); + hasSupplementary = static_cast(cnv->sharedData->mbcs.unicodeMask & UCNV_HAS_SUPPLEMENTARY); /* get the converter state from the UTF-8 UConverter */ if(utf8->toULength > 0) { toULength=oldToULength=utf8->toULength; - toULimit=(int8_t)utf8->mode; - c=(UChar32)utf8->toUnicodeStatus; + toULimit = static_cast(utf8->mode); + c = static_cast(utf8->toUnicodeStatus); } else { toULength=oldToULength=toULimit=0; c = 0; @@ -5376,7 +5376,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, { // Do not go back into the bytes that will be read for finishing a partial // sequence from the previous buffer. - int32_t length=(int32_t)(sourceLimit-source) - (toULimit-oldToULength); + int32_t length = static_cast(sourceLimit - source) - (toULimit - oldToULength); if(length>0) { uint8_t b1=*(sourceLimit-1); if(U8_IS_SINGLE(b1)) { @@ -5423,7 +5423,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, if( /* handle U+0800..U+D7FF inline */ b<=0xed && // do not assume maxFastUChar>0xd7ff U8_IS_VALID_LEAD3_AND_T1(b, t1=source[0]) && - (t2=(uint8_t)(source[1]-0x80)) <= 0x3f + (t2 = static_cast(source[1] - 0x80)) <= 0x3f ) { c=((b&0xf)<<6)|(t1&0x3f); source+=2; @@ -5438,7 +5438,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, } else { if( /* handle U+0080..U+07FF inline */ b>=0xc2 && - (t1=(uint8_t)(*source-0x80)) <= 0x3f + (t1 = static_cast(*source - 0x80)) <= 0x3f ) { c=b&0x1f; ++source; @@ -5486,7 +5486,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, utf8->toULength=toULength; utf8->mode=toULimit; pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); return; } } @@ -5512,7 +5512,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, } utf8->toULength=toULength; pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); *pErrorCode=U_ILLEGAL_CHAR_FOUND; return; } @@ -5534,15 +5534,15 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, /* from the first if in the loop we know that targetCapacity>0 */ if(value<=0xff) { /* this is easy because we know that there is enough space */ - *target++=(uint8_t)value; + *target++ = static_cast(value); --targetCapacity; } else /* length==2 */ { - *target++=(uint8_t)(value>>8); + *target++ = static_cast(value >> 8); if(2<=targetCapacity) { - *target++=(uint8_t)value; + *target++ = static_cast(value); targetCapacity-=2; } else { - cnv->charErrorBuffer[0]=(char)value; + cnv->charErrorBuffer[0] = static_cast(value); cnv->charErrorBufferLength=1; /* target overflow */ @@ -5586,7 +5586,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ - targetCapacity=(int32_t)(pFromUArgs->targetLimit-(char *)target); + targetCapacity = static_cast(pFromUArgs->targetLimit - reinterpret_cast(target)); continue; } } @@ -5619,7 +5619,7 @@ ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, /* write back the updated pointers */ pToUArgs->source=(char *)source; - pFromUArgs->target=(char *)target; + pFromUArgs->target = reinterpret_cast(target); } /* miscellaneous ------------------------------------------------------------ */ @@ -5634,7 +5634,7 @@ ucnv_MBCSGetStarters(const UConverter* cnv, state0=cnv->sharedData->mbcs.stateTable[cnv->sharedData->mbcs.dbcsOnlyState]; for(i=0; i<256; ++i) { /* all bytes that cause a state transition from state 0 are lead bytes */ - starters[i]= (UBool)MBCS_ENTRY_IS_TRANSITION(state0[i]); + starters[i] = static_cast(MBCS_ENTRY_IS_TRANSITION(state0[i])); } } @@ -5663,11 +5663,11 @@ ucnv_MBCSWriteSub(UConverterFromUnicodeArgs *pArgs, (cnv->invalidUCharBuffer[0]<=0xff)) ) { /* select subChar1 if it is set (not 0) and the unmappable Unicode code point is up to U+00ff (IBM MBCS behavior) */ - subchar=(char *)&cnv->subChar1; + subchar = reinterpret_cast(&cnv->subChar1); length=1; } else { /* select subChar in all other cases */ - subchar=(char *)cnv->subChars; + subchar = reinterpret_cast(cnv->subChars); length=cnv->subCharLen; } @@ -5701,7 +5701,7 @@ ucnv_MBCSWriteSub(UConverterFromUnicodeArgs *pArgs, return; } subchar=buffer; - length=(int32_t)(p-buffer); + length = static_cast(p - buffer); } ucnv_cbFromUWriteBytes(pArgs, subchar, length, offsetIndex, pErrorCode); diff --git a/icu4c/source/common/ucnvscsu.cpp b/icu4c/source/common/ucnvscsu.cpp index e6f8660df404..6dd1654636a1 100644 --- a/icu4c/source/common/ucnvscsu.cpp +++ b/icu4c/source/common/ucnvscsu.cpp @@ -883,8 +883,8 @@ static int8_t getWindow(const uint32_t offsets[8], uint32_t c) { int i; for(i=0; i<8; ++i) { - if((uint32_t)(c-offsets[i])<=0x7f) { - return (int8_t)(i); + if (c - offsets[i] <= 0x7f) { + return static_cast(i); } } return -1; @@ -893,7 +893,7 @@ getWindow(const uint32_t offsets[8], uint32_t c) { /* is the character in the dynamic window starting at the offset, or in the direct-encoded range? */ static UBool isInOffsetWindowOrDirect(uint32_t offset, uint32_t c) { - return (UBool)(c<=offset+0x7f && + return static_cast(c<=offset+0x7f && (c>=offset || (c<=0x7f && (c>=0x20 || (1UL<>7); + return static_cast(c >> 7); } else if(0xe000<=c && c!=0xfeff && c<0xfff0) { /* For these characters we need to take the gapOffset into account. */ *pOffset=c&0x7fffff80; - return (int)((c-gapOffset)>>7); + return static_cast((c - gapOffset) >> 7); } else { return -1; } @@ -1208,8 +1208,8 @@ _SCSUFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, c=((uint32_t)(SD0+dynamicWindow)<<16)|((uint32_t)code<<8)|(c-currentOffset)|0x80; length=3; goto outputBytes; - } else if((uint32_t)(c-0x3400)<(0xd800-0x3400) && - (source>=sourceLimit || (uint32_t)(*source-0x3400)<(0xd800-0x3400)) + } else if ((c - 0x3400) < (0xd800 - 0x3400) && + (source >= sourceLimit || (uint32_t)(*source - 0x3400) < (0xd800 - 0x3400)) ) { /* * this character is not compressible (a BMP ideograph or similar); @@ -1248,7 +1248,7 @@ _SCSUFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, c=*source++; ++nextSourceIndex; - if((uint32_t)(c-0x3400)<(0xd800-0x3400)) { + if ((c - 0x3400) < (0xd800 - 0x3400)) { /* not compressible, write character directly */ if(targetCapacity>=2) { *target++=(uint8_t)(c>>8); @@ -1262,10 +1262,10 @@ _SCSUFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, length=2; goto outputBytes; } - } else if((uint32_t)(c-0x3400)>=(0xf300-0x3400) /* c<0x3400 || c>=0xf300 */) { + } else if (c - 0x3400 >= 0xf300 - 0x3400 /* c<0x3400 || c>=0xf300 */) { /* compress BMP character if the following one is not an uncompressible ideograph */ if(!(source=sourceLimit || (uint32_t)(*source-0x3400)<(0xd800-0x3400)) + } else if (c - 0x3400 < 0xd800 - 0x3400 && + (source >= sourceLimit || static_cast(*source - 0x3400) < 0xd800 - 0x3400) ) { /* * this character is not compressible (a BMP ideograph or similar); @@ -1729,7 +1729,7 @@ _SCSUFromUnicode(UConverterFromUnicodeArgs *pArgs, } c=*source++; - if((uint32_t)(c-0x3400)<(0xd800-0x3400)) { + if (c - 0x3400 < 0xd800 - 0x3400) { /* not compressible, write character directly */ if(targetCapacity>=2) { *target++=(uint8_t)(c>>8); @@ -1739,10 +1739,10 @@ _SCSUFromUnicode(UConverterFromUnicodeArgs *pArgs, length=2; goto outputBytes; } - } else if((uint32_t)(c-0x3400)>=(0xf300-0x3400) /* c<0x3400 || c>=0xf300 */) { + } else if (c - 0x3400 >= 0xf300 - 0x3400 /* c<0x3400 || c>=0xf300 */) { /* compress BMP character if the following one is not an uncompressible ideograph */ if(!(source(static_cast(inData) + 4); if(!( pInfo->dataFormat[0] == 0x43 && /* dataFormat="CSel" */ pInfo->dataFormat[1] == 0x53 && @@ -407,11 +407,11 @@ ucnvsel_swap(const UDataSwapper *ds, } } - const uint8_t *inBytes = (const uint8_t *)inData + headerSize; - uint8_t *outBytes = (uint8_t *)outData + headerSize; + const uint8_t* inBytes = static_cast(inData) + headerSize; + uint8_t* outBytes = static_cast(outData) + headerSize; /* read the indexes */ - const int32_t *inIndexes = (const int32_t *)inBytes; + const int32_t* inIndexes = reinterpret_cast(inBytes); int32_t indexes[16]; int32_t i; for(i = 0; i < 16; ++i) { diff --git a/icu4c/source/common/ucol_swp.cpp b/icu4c/source/common/ucol_swp.cpp index b5894a1feff8..ea72bb8b8d11 100644 --- a/icu4c/source/common/ucol_swp.cpp +++ b/icu4c/source/common/ucol_swp.cpp @@ -108,11 +108,11 @@ swapFormatVersion3(const UDataSwapper *ds, return 0; } - inBytes=(const uint8_t *)inData; - outBytes=(uint8_t *)outData; + inBytes = static_cast(inData); + outBytes = static_cast(outData); - inHeader=(const UCATableHeader *)inData; - outHeader=(UCATableHeader *)outData; + inHeader = static_cast(inData); + outHeader = static_cast(outData); /* * The collation binary must contain at least the UCATableHeader, @@ -175,7 +175,7 @@ swapFormatVersion3(const UDataSwapper *ds, header.leadByteToScript= ds->readUInt32(inHeader->leadByteToScript); /* swap the 32-bit integers in the header */ - ds->swapArray32(ds, inHeader, (int32_t)((const char *)&inHeader->jamoSpecial-(const char *)inHeader), + ds->swapArray32(ds, inHeader, static_cast(reinterpret_cast(&inHeader->jamoSpecial) - reinterpret_cast(inHeader)), outHeader, pErrorCode); ds->swapArray32(ds, &(inHeader->scriptToLeadByte), sizeof(header.scriptToLeadByte) + sizeof(header.leadByteToScript), &(outHeader->scriptToLeadByte), pErrorCode); @@ -198,7 +198,7 @@ swapFormatVersion3(const UDataSwapper *ds, /* no contractions: expansions bounded by the main trie */ count=header.mappingPosition-header.expansion; } - ds->swapArray32(ds, inBytes+header.expansion, (int32_t)count, + ds->swapArray32(ds, inBytes + header.expansion, static_cast(count), outBytes+header.expansion, pErrorCode); } @@ -216,7 +216,7 @@ swapFormatVersion3(const UDataSwapper *ds, /* swap the main trie */ if(header.mappingPosition!=0) { count=header.endExpansionCE-header.mappingPosition; - utrie_swap(ds, inBytes+header.mappingPosition, (int32_t)count, + utrie_swap(ds, inBytes + header.mappingPosition, static_cast(count), outBytes+header.mappingPosition, pErrorCode); } @@ -241,7 +241,7 @@ swapFormatVersion3(const UDataSwapper *ds, /* swap UCA contractions */ if(header.contractionUCACombosSize!=0) { count=header.contractionUCACombosSize*inHeader->contractionUCACombosWidth*U_SIZEOF_UCHAR; - ds->swapArray16(ds, inBytes+header.contractionUCACombos, (int32_t)count, + ds->swapArray16(ds, inBytes + header.contractionUCACombos, static_cast(count), outBytes+header.contractionUCACombos, pErrorCode); } @@ -306,10 +306,10 @@ swapFormatVersion4(const UDataSwapper *ds, UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return 0; } - const uint8_t *inBytes=(const uint8_t *)inData; - uint8_t *outBytes=(uint8_t *)outData; + const uint8_t* inBytes = static_cast(inData); + uint8_t* outBytes = static_cast(outData); - const int32_t *inIndexes=(const int32_t *)inBytes; + const int32_t* inIndexes = reinterpret_cast(inBytes); int32_t indexes[IX_TOTAL_SIZE+1]; // Need at least IX_INDEXES_LENGTH and IX_OPTIONS. diff --git a/icu4c/source/common/ucptrie.cpp b/icu4c/source/common/ucptrie.cpp index 0004160a238b..3e4b6a606e5e 100644 --- a/icu4c/source/common/ucptrie.cpp +++ b/icu4c/source/common/ucptrie.cpp @@ -258,11 +258,11 @@ inline uint32_t maybeFilterValue(uint32_t value, uint32_t trieNullValue, uint32_ UChar32 getRange(const void *t, UChar32 start, UCPMapValueFilter *filter, const void *context, uint32_t *pValue) { - if ((uint32_t)start > MAX_UNICODE) { + if (static_cast(start) > MAX_UNICODE) { return U_SENTINEL; } const UCPTrie *trie = reinterpret_cast(t); - UCPTrieValueWidth valueWidth = (UCPTrieValueWidth)trie->valueWidth; + UCPTrieValueWidth valueWidth = static_cast(trie->valueWidth); if (start >= trie->highStart) { if (pValue != nullptr) { int32_t di = trie->dataLength - UCPTRIE_HIGH_VALUE_NEG_DATA_OFFSET; @@ -304,7 +304,7 @@ UChar32 getRange(const void *t, UChar32 start, i1 += UCPTRIE_SMALL_INDEX_LENGTH; } i3Block = trie->index[ - (int32_t)trie->index[i1] + ((c >> UCPTRIE_SHIFT_2) & UCPTRIE_INDEX_2_MASK)]; + static_cast(trie->index[i1]) + ((c >> UCPTRIE_SHIFT_2) & UCPTRIE_INDEX_2_MASK)]; if (i3Block == prevI3Block && (c - start) >= UCPTRIE_CP_PER_INDEX_2_ENTRY) { // The index-3 block is the same as the previous one, and filled with value. U_ASSERT((c & (UCPTRIE_CP_PER_INDEX_2_ENTRY - 1)) == 0); @@ -341,7 +341,7 @@ UChar32 getRange(const void *t, UChar32 start, // 18-bit indexes stored in groups of 9 entries per 8 indexes. int32_t group = (i3Block & 0x7fff) + (i3 & ~7) + (i3 >> 3); int32_t gi = i3 & 7; - block = ((int32_t)index[group++] << (2 + (2 * gi))) & 0x30000; + block = (static_cast(index[group++]) << (2 + (2 * gi))) & 0x30000; block |= index[group + gi]; } if (block == prevBlock && (c - start) >= dataBlockLength) { diff --git a/icu4c/source/common/ucurr.cpp b/icu4c/source/common/ucurr.cpp index cbd1a0e39e9d..282199257376 100644 --- a/icu4c/source/common/ucurr.cpp +++ b/icu4c/source/common/ucurr.cpp @@ -130,7 +130,7 @@ class EquivIterator : public icu::UMemory { const icu::UnicodeString * EquivIterator::next() { - const icu::UnicodeString* _next = (const icu::UnicodeString*) _hash.get(*_current); + const icu::UnicodeString* _next = static_cast(_hash.get(*_current)); if (_next == nullptr) { U_ASSERT(_current == _start); return nullptr; @@ -260,7 +260,7 @@ currSymbolsEquiv_cleanup() */ static void U_CALLCONV deleteIsoCodeEntry(void *obj) { - IsoCodeEntry *entry = (IsoCodeEntry*)obj; + IsoCodeEntry* entry = static_cast(obj); uprv_free(entry); } @@ -269,7 +269,7 @@ deleteIsoCodeEntry(void *obj) { */ static void U_CALLCONV deleteUnicode(void *obj) { - icu::UnicodeString *entry = (icu::UnicodeString*)obj; + icu::UnicodeString* entry = static_cast(obj); delete entry; } @@ -372,8 +372,8 @@ struct CReg : public icu::UMemory { CReg(const char16_t* _iso, const char* _id) : next(nullptr) { - int32_t len = (int32_t)uprv_strlen(_id); - if (len > (int32_t)(sizeof(id)-1)) { + int32_t len = static_cast(uprv_strlen(_id)); + if (len > static_cast(sizeof(id) - 1)) { len = (sizeof(id)-1); } uprv_strncpy(id, _id, len); @@ -855,8 +855,8 @@ typedef struct { // Comparison function used in quick sort. static int U_CALLCONV currencyNameComparator(const void* a, const void* b) { - const CurrencyNameStruct* currName_1 = (const CurrencyNameStruct*)a; - const CurrencyNameStruct* currName_2 = (const CurrencyNameStruct*)b; + const CurrencyNameStruct* currName_1 = static_cast(a); + const CurrencyNameStruct* currName_2 = static_cast(b); for (int32_t i = 0; i < MIN(currName_1->currencyNameLen, currName_2->currencyNameLen); ++i) { @@ -937,7 +937,7 @@ toUpperCase(const char16_t* source, int32_t len, const char* locale) { int32_t destLen = u_strToUpper(dest, 0, source, len, locale, &ec); ec = U_ZERO_ERROR; - dest = (char16_t*)uprv_malloc(sizeof(char16_t) * MAX(destLen, len)); + dest = static_cast(uprv_malloc(sizeof(char16_t) * MAX(destLen, len))); if (dest == nullptr) { return nullptr; } @@ -984,16 +984,16 @@ collectCurrencyNames(const char* locale, // Get maximum currency name count first. getCurrencyNameCount(loc.data(), total_currency_name_count, total_currency_symbol_count); - *currencyNames = (CurrencyNameStruct*)uprv_malloc - (sizeof(CurrencyNameStruct) * (*total_currency_name_count)); + *currencyNames = static_cast( + uprv_malloc(sizeof(CurrencyNameStruct) * (*total_currency_name_count))); if(*currencyNames == nullptr) { *currencySymbols = nullptr; *total_currency_name_count = *total_currency_symbol_count = 0; ec = U_MEMORY_ALLOCATION_ERROR; return; } - *currencySymbols = (CurrencyNameStruct*)uprv_malloc - (sizeof(CurrencyNameStruct) * (*total_currency_symbol_count)); + *currencySymbols = static_cast( + uprv_malloc(sizeof(CurrencyNameStruct) * (*total_currency_symbol_count))); if(*currencySymbols == nullptr) { uprv_free(*currencyNames); @@ -1026,13 +1026,13 @@ collectCurrencyNames(const char* locale, int32_t len; s = ures_getStringByIndex(names.getAlias(), UCURR_SYMBOL_NAME, &len, &ec2); // TODO: uhash_put wont change key/value? - iso = (char*)ures_getKey(names.getAlias()); + iso = const_cast(ures_getKey(names.getAlias())); if (localeLevel != 0 && uhash_get(currencyIsoCodes.getAlias(), iso) != nullptr) { continue; } uhash_put(currencyIsoCodes.getAlias(), iso, iso, &ec3); // Add currency symbol. - (*currencySymbols)[(*total_currency_symbol_count)++] = {iso, (char16_t*)s, len, 0}; + (*currencySymbols)[(*total_currency_symbol_count)++] = {iso, const_cast(s), len, 0}; // Add equivalent symbols if (currencySymbolsEquiv != nullptr) { @@ -1056,7 +1056,7 @@ collectCurrencyNames(const char* locale, // put (iso, 3, and iso) in to array // Add currency ISO code. - char16_t* isoCode = (char16_t*)uprv_malloc(sizeof(char16_t)*3); + char16_t* isoCode = static_cast(uprv_malloc(sizeof(char16_t) * 3)); if (isoCode == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; goto error; @@ -1072,7 +1072,7 @@ collectCurrencyNames(const char* locale, n = ures_getSize(curr_p.getAlias()); for (int32_t i=0; i(ures_getKey(names.getAlias())); // Using hash to remove duplicated ISO codes in fallback chain. if (localeLevel != 0 && uhash_get(currencyPluralIsoCodes.getAlias(), iso) != nullptr) { continue; @@ -1473,7 +1473,7 @@ getCacheEntry(const char* locale, UErrorCode& ec) { deleteCacheEntry(cacheEntry); } } - cacheEntry = (CurrencyNameCacheEntry*)uprv_malloc(sizeof(CurrencyNameCacheEntry)); + cacheEntry = static_cast(uprv_malloc(sizeof(CurrencyNameCacheEntry))); if (cacheEntry == nullptr) { deleteCurrencyNames(currencyNames, total_currency_name_count); deleteCurrencyNames(currencySymbols, total_currency_symbol_count); diff --git a/icu4c/source/common/udata.cpp b/icu4c/source/common/udata.cpp index 4c2ba57303a0..cdd37f6a03f9 100644 --- a/icu4c/source/common/udata.cpp +++ b/icu4c/source/common/udata.cpp @@ -274,7 +274,7 @@ typedef struct DataCacheElement { * here for each entry. */ static void U_CALLCONV DataCacheElement_deleter(void *pDCEl) { - DataCacheElement *p = (DataCacheElement *)pDCEl; + DataCacheElement* p = static_cast(pDCEl); udata_close(p->item); /* unmaps storage */ uprv_free(p->name); /* delete the hash key string. */ uprv_free(pDCEl); /* delete 'this' */ @@ -316,7 +316,7 @@ static UDataMemory *udata_findCachedData(const char *path, UErrorCode &err) baseName = findBasename(path); /* Cache remembers only the base name, not the full path. */ umtx_lock(nullptr); - el = (DataCacheElement *)uhash_get(htable, baseName); + el = static_cast(uhash_get(htable, baseName)); umtx_unlock(nullptr); if (el != nullptr) { retVal = el->item; @@ -344,7 +344,7 @@ static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UEr /* Create a new DataCacheElement - the thingy we store in the hash table - * and copy the supplied path and UDataMemoryItems into it. */ - newElement = (DataCacheElement *)uprv_malloc(sizeof(DataCacheElement)); + newElement = static_cast(uprv_malloc(sizeof(DataCacheElement))); if (newElement == nullptr) { *pErr = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -357,8 +357,8 @@ static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UEr UDatamemory_assign(newElement->item, item); baseName = findBasename(path); - nameLen = (int32_t)uprv_strlen(baseName); - newElement->name = (char *)uprv_malloc(nameLen+1); + nameLen = static_cast(uprv_strlen(baseName)); + newElement->name = static_cast(uprv_malloc(nameLen + 1)); if (newElement->name == nullptr) { *pErr = U_MEMORY_ALLOCATION_ERROR; uprv_free(newElement->item); @@ -370,7 +370,7 @@ static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UEr /* Stick the new DataCacheElement into the hash table. */ umtx_lock(nullptr); - oldValue = (DataCacheElement *)uhash_get(htable, path); + oldValue = static_cast(uhash_get(htable, path)); if (oldValue != nullptr) { subErr = U_USING_DEFAULT_WARNING; } @@ -469,13 +469,13 @@ UDataPathIterator::UDataPathIterator(const char *inPath, const char *pkg, /** Item **/ basename = findBasename(item); - basenameLen = (int32_t)uprv_strlen(basename); + basenameLen = static_cast(uprv_strlen(basename)); /** Item path **/ if(basename == item) { nextPath = path; } else { - itemPath.append(item, (int32_t)(basename-item), *pErrorCode); + itemPath.append(item, static_cast(basename - item), *pErrorCode); nextPath = itemPath.data(); } #ifdef UDATA_DEBUG @@ -531,16 +531,16 @@ const char *UDataPathIterator::next(UErrorCode *pErrorCode) if(nextPath == itemPath.data()) { /* we were processing item's path. */ nextPath = path; /* start with regular path next tm. */ - pathLen = (int32_t)uprv_strlen(currentPath); + pathLen = static_cast(uprv_strlen(currentPath)); } else { /* fix up next for next time */ nextPath = uprv_strchr(currentPath, U_PATH_SEP_CHAR); if(nextPath == nullptr) { /* segment: entire path */ - pathLen = (int32_t)uprv_strlen(currentPath); + pathLen = static_cast(uprv_strlen(currentPath)); } else { /* segment: until next segment */ - pathLen = (int32_t)(nextPath - currentPath); + pathLen = static_cast(nextPath - currentPath); /* skip divider */ nextPath ++; } @@ -1231,7 +1231,7 @@ doOpenChoice(const char *path, const char *type, const char *name, if(isICUData) { pkgName.append(U_ICUDATA_NAME, *pErrorCode); } else { - pkgName.append(path, (int32_t)(treeChar-path), *pErrorCode); + pkgName.append(path, static_cast(treeChar - path), *pErrorCode); if (first == nullptr) { /* This user data has no path, but there is a tree name. diff --git a/icu4c/source/common/udataswp.cpp b/icu4c/source/common/udataswp.cpp index 0f194f47e892..09adf9510ce1 100644 --- a/icu4c/source/common/udataswp.cpp +++ b/icu4c/source/common/udataswp.cpp @@ -47,12 +47,12 @@ uprv_swapArray16(const UDataSwapper *ds, } /* setup and swapping */ - p=(const uint16_t *)inData; - q=(uint16_t *)outData; + p = static_cast(inData); + q = static_cast(outData); count=length/2; while(count>0) { x=*p++; - *q++=(uint16_t)((x<<8)|(x>>8)); + *q++ = static_cast((x << 8) | (x >> 8)); --count; } @@ -95,12 +95,12 @@ uprv_swapArray32(const UDataSwapper *ds, } /* setup and swapping */ - p=(const uint32_t *)inData; - q=(uint32_t *)outData; + p = static_cast(inData); + q = static_cast(outData); count=length/4; while(count>0) { x=*p++; - *q++=(uint32_t)((x<<24)|((x<<8)&0xff0000)|((x>>8)&0xff00)|(x>>24)); + *q++ = (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | (x >> 24); --count; } @@ -142,8 +142,8 @@ uprv_swapArray64(const UDataSwapper *ds, } /* setup and swapping */ - p=(const uint64_t *)inData; - q=(uint64_t *)outData; + p = static_cast(inData); + q = static_cast(outData); count=length/8; while(count>0) { uint64_t x=*p++; @@ -176,7 +176,7 @@ uprv_copyArray64(const UDataSwapper *ds, static uint16_t U_CALLCONV uprv_readSwapUInt16(uint16_t x) { - return (uint16_t)((x<<8)|(x>>8)); + return static_cast((x << 8) | (x >> 8)); } static uint16_t U_CALLCONV @@ -186,7 +186,7 @@ uprv_readDirectUInt16(uint16_t x) { static uint32_t U_CALLCONV uprv_readSwapUInt32(uint32_t x) { - return (uint32_t)((x<<24)|((x<<8)&0xff0000)|((x>>8)&0xff00)|(x>>24)); + return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | (x >> 24); } static uint32_t U_CALLCONV @@ -196,7 +196,7 @@ uprv_readDirectUInt32(uint32_t x) { static void U_CALLCONV uprv_writeSwapUInt16(uint16_t *p, uint16_t x) { - *p=(uint16_t)((x<<8)|(x>>8)); + *p = static_cast((x << 8) | (x >> 8)); } static void U_CALLCONV @@ -206,7 +206,7 @@ uprv_writeDirectUInt16(uint16_t *p, uint16_t x) { static void U_CALLCONV uprv_writeSwapUInt32(uint32_t *p, uint32_t x) { - *p=(uint32_t)((x<<24)|((x<<8)&0xff0000)|((x>>8)&0xff00)|(x>>24)); + *p = (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | (x >> 24); } static void U_CALLCONV diff --git a/icu4c/source/common/uenum.cpp b/icu4c/source/common/uenum.cpp index 7aab58c44c7f..b4a5071ae7bc 100644 --- a/icu4c/source/common/uenum.cpp +++ b/icu4c/source/common/uenum.cpp @@ -34,14 +34,14 @@ static const int32_t PAD = 8; static void* _getBuffer(UEnumeration* en, int32_t capacity) { if (en->baseContext != nullptr) { - if (((_UEnumBuffer*) en->baseContext)->len < capacity) { + if (static_cast<_UEnumBuffer*>(en->baseContext)->len < capacity) { capacity += PAD; en->baseContext = uprv_realloc(en->baseContext, sizeof(int32_t) + capacity); if (en->baseContext == nullptr) { return nullptr; } - ((_UEnumBuffer*) en->baseContext)->len = capacity; + static_cast<_UEnumBuffer*>(en->baseContext)->len = capacity; } } else { capacity += PAD; @@ -49,10 +49,10 @@ static void* _getBuffer(UEnumeration* en, int32_t capacity) { if (en->baseContext == nullptr) { return nullptr; } - ((_UEnumBuffer*) en->baseContext)->len = capacity; + static_cast<_UEnumBuffer*>(en->baseContext)->len = capacity; } - return (void*) & ((_UEnumBuffer*) en->baseContext)->data; + return static_cast(&static_cast<_UEnumBuffer*>(en->baseContext)->data); } U_CAPI void U_EXPORT2 diff --git a/icu4c/source/common/uhash.cpp b/icu4c/source/common/uhash.cpp index 4d92dfa93fe1..bc9a885e2500 100644 --- a/icu4c/source/common/uhash.cpp +++ b/icu4c/source/common/uhash.cpp @@ -224,8 +224,8 @@ _uhash_allocate(UHashtable *hash, hash->primeIndex = static_cast(primeIndex); hash->length = PRIMES[primeIndex]; - p = hash->elements = (UHashElement*) - uprv_malloc(sizeof(UHashElement) * hash->length); + p = hash->elements = static_cast( + uprv_malloc(sizeof(UHashElement) * hash->length)); if (hash->elements == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; @@ -244,8 +244,8 @@ _uhash_allocate(UHashtable *hash, } hash->count = 0; - hash->lowWaterMark = (int32_t)(hash->length * hash->lowWaterRatio); - hash->highWaterMark = (int32_t)(hash->length * hash->highWaterRatio); + hash->lowWaterMark = static_cast(hash->length * hash->lowWaterRatio); + hash->highWaterMark = static_cast(hash->length * hash->highWaterRatio); } static UHashtable* @@ -287,7 +287,7 @@ _uhash_create(UHashFunction *keyHash, if (U_FAILURE(*status)) return nullptr; - result = (UHashtable*) uprv_malloc(sizeof(UHashtable)); + result = static_cast(uprv_malloc(sizeof(UHashtable))); if (result == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; return nullptr; diff --git a/icu4c/source/common/uidna.cpp b/icu4c/source/common/uidna.cpp index 949d128f93c5..cc9c8e405f4f 100644 --- a/icu4c/source/common/uidna.cpp +++ b/icu4c/source/common/uidna.cpp @@ -107,7 +107,7 @@ compareCaseInsensitiveASCII(const char16_t* s1, int32_t s1Len, /* Case-insensitive comparison */ if(c1!=c2) { - rc=(int32_t)toASCIILower(c1)-(int32_t)toASCIILower(c2); + rc = static_cast(toASCIILower(c1)) - static_cast(toASCIILower(c2)); if(rc!=0) { lengthResult=rc; break; @@ -219,7 +219,7 @@ _internal_toASCII(const char16_t* src, int32_t srcLength, int32_t j=0; //get the options - UBool useSTD3ASCIIRules = (UBool)((options & UIDNA_USE_STD3_RULES) != 0); + UBool useSTD3ASCIIRules = static_cast((options & UIDNA_USE_STD3_RULES) != 0); int32_t failPos = -1; @@ -228,7 +228,7 @@ _internal_toASCII(const char16_t* src, int32_t srcLength, } if(srcLength > b1Capacity){ - b1 = (char16_t*) uprv_malloc(srcLength * U_SIZEOF_UCHAR); + b1 = static_cast(uprv_malloc(srcLength * U_SIZEOF_UCHAR)); if(b1==nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -256,7 +256,7 @@ _internal_toASCII(const char16_t* src, int32_t srcLength, if(b1 != b1Stack){ uprv_free(b1); } - b1 = (char16_t*) uprv_malloc(b1Len * U_SIZEOF_UCHAR); + b1 = static_cast(uprv_malloc(b1Len * U_SIZEOF_UCHAR)); if(b1==nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -338,7 +338,7 @@ _internal_toASCII(const char16_t* src, int32_t srcLength, if(*status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ - b2 = (char16_t*) uprv_malloc(b2Len * U_SIZEOF_UCHAR); + b2 = static_cast(uprv_malloc(b2Len * U_SIZEOF_UCHAR)); if(b2 == nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -458,7 +458,7 @@ _internal_toUnicode(const char16_t* src, int32_t srcLength, if(*status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ - b1 = (char16_t*) uprv_malloc(b1Len * U_SIZEOF_UCHAR); + b1 = static_cast(uprv_malloc(b1Len * U_SIZEOF_UCHAR)); if(b1==nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -475,7 +475,7 @@ _internal_toUnicode(const char16_t* src, int32_t srcLength, }else{ //just point src to b1 - b1 = (char16_t*) src; + b1 = const_cast(src); b1Len = srcLength; } @@ -498,7 +498,7 @@ _internal_toUnicode(const char16_t* src, int32_t srcLength, if(*status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ - b2 = (char16_t*) uprv_malloc(b2Len * U_SIZEOF_UCHAR); + b2 = static_cast(uprv_malloc(b2Len * U_SIZEOF_UCHAR)); if(b2==nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -516,7 +516,7 @@ _internal_toUnicode(const char16_t* src, int32_t srcLength, if(*status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ - b3 = (char16_t*) uprv_malloc(b3Len * U_SIZEOF_UCHAR); + b3 = static_cast(uprv_malloc(b3Len * U_SIZEOF_UCHAR)); if(b3==nullptr){ *status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -689,9 +689,9 @@ uidna_IDNToASCII( const char16_t *src, int32_t srcLength, } //initialize pointers - char16_t *delimiter = (char16_t*)src; - char16_t *labelStart = (char16_t*)src; - char16_t *currentDest = (char16_t*) dest; + char16_t* delimiter = const_cast(src); + char16_t* labelStart = const_cast(src); + char16_t* currentDest = dest; int32_t remainingLen = srcLength; int32_t remainingDestCapacity = destCapacity; int32_t labelLen = 0, labelReqLength = 0; @@ -782,9 +782,9 @@ uidna_IDNToUnicode( const char16_t* src, int32_t srcLength, } //initialize pointers - char16_t *delimiter = (char16_t*)src; - char16_t *labelStart = (char16_t*)src; - char16_t *currentDest = (char16_t*) dest; + char16_t* delimiter = const_cast(src); + char16_t* labelStart = const_cast(src); + char16_t* currentDest = dest; int32_t remainingLen = srcLength; int32_t remainingDestCapacity = destCapacity; int32_t labelLen = 0, labelReqLength = 0; diff --git a/icu4c/source/common/uloc.cpp b/icu4c/source/common/uloc.cpp index 88fe7eaadce8..3a4d3b595417 100644 --- a/icu4c/source/common/uloc.cpp +++ b/icu4c/source/common/uloc.cpp @@ -580,8 +580,8 @@ typedef struct { int32_t U_CALLCONV compareKeywordStructs(const void * /*context*/, const void *left, const void *right) { - const char* leftString = ((const KeywordStruct *)left)->keyword; - const char* rightString = ((const KeywordStruct *)right)->keyword; + const char* leftString = static_cast(left)->keyword; + const char* rightString = static_cast(right)->keyword; return uprv_strcmp(leftString, rightString); } @@ -686,10 +686,10 @@ ulocimp_getKeywords(const char* localeID, while(*(pos - i - 1) == ' ') { i++; } - keywordList[numKeywords].valueLen = (int32_t)(pos - equalSign - i); + keywordList[numKeywords].valueLen = static_cast(pos - equalSign - i); pos++; } else { - i = (int32_t)uprv_strlen(equalSign); + i = static_cast(uprv_strlen(equalSign)); while(i && equalSign[i-1] == ' ') { i--; } @@ -1091,7 +1091,7 @@ ulocimp_setKeywordValue(const char* keywords, /* if input key/value specified removal of a keyword not present in locale, or * there was an error in CharString.append, leave original locale alone. */ U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING); - return (int32_t)uprv_strlen(keywords); + return static_cast(uprv_strlen(keywords)); } needLen = updatedKeysAndValues.length(); @@ -1155,7 +1155,7 @@ std::optional _findIndex(const char* const* list, const char* key) while (pass++ < 2) { while (*list) { if (uprv_strcmp(key, *list) == 0) { - return (int16_t)(list - anchor); + return static_cast(list - anchor); } list++; } @@ -1241,7 +1241,7 @@ _getLanguage(const char* localeID, std::optional offset = _findIndex(LANGUAGES_3, buffer); if (offset.has_value()) { const char* const alias = LANGUAGES[*offset]; - sink->Append(alias, (int32_t)uprv_strlen(alias)); + sink->Append(alias, static_cast(uprv_strlen(alias))); return; } } @@ -1322,7 +1322,7 @@ _getRegion(const char* localeID, std::optional offset = _findIndex(COUNTRIES_3, buffer); if (offset.has_value()) { const char* const alias = COUNTRIES[*offset]; - sink->Append(alias, (int32_t)uprv_strlen(alias)); + sink->Append(alias, static_cast(uprv_strlen(alias))); return; } } @@ -1370,7 +1370,7 @@ _getVariant(const char* localeID, needSeparator = false; } if (sink != nullptr) { - char c = (char)uprv_toupper(localeID[index]); + char c = uprv_toupper(localeID[index]); if (c == '-') c = '_'; sink->Append(&c, 1); } @@ -1399,7 +1399,7 @@ _getVariant(const char* localeID, needSeparator = false; } if (sink != nullptr) { - char c = (char)uprv_toupper(localeID[index]); + char c = uprv_toupper(localeID[index]); if (c == '-' || c == ',') c = '_'; sink->Append(&c, 1); } @@ -1955,7 +1955,7 @@ ulocimp_getParent(const char* localeID, lastUnderscore=uprv_strrchr(localeID, '_'); if(lastUnderscore!=nullptr) { - i=(int32_t)(lastUnderscore-localeID); + i = static_cast(lastUnderscore - localeID); } else { i=0; } diff --git a/icu4c/source/common/uloc_keytype.cpp b/icu4c/source/common/uloc_keytype.cpp index 38694d4a185d..e374da450b5c 100644 --- a/icu4c/source/common/uloc_keytype.cpp +++ b/icu4c/source/common/uloc_keytype.cpp @@ -428,7 +428,7 @@ ulocimp_toBcpKey(const char* key) { return nullptr; } - LocExtKeyData* keyData = (LocExtKeyData*)uhash_get(gLocExtKeyMap, key); + LocExtKeyData* keyData = static_cast(uhash_get(gLocExtKeyMap, key)); if (keyData != nullptr) { return keyData->bcpId; } @@ -441,7 +441,7 @@ ulocimp_toLegacyKey(const char* key) { return nullptr; } - LocExtKeyData* keyData = (LocExtKeyData*)uhash_get(gLocExtKeyMap, key); + LocExtKeyData* keyData = static_cast(uhash_get(gLocExtKeyMap, key)); if (keyData != nullptr) { return keyData->legacyId; } @@ -461,12 +461,12 @@ ulocimp_toBcpType(const char* key, const char* type, bool* isKnownKey, bool* isS return nullptr; } - LocExtKeyData* keyData = (LocExtKeyData*)uhash_get(gLocExtKeyMap, key); + LocExtKeyData* keyData = static_cast(uhash_get(gLocExtKeyMap, key)); if (keyData != nullptr) { if (isKnownKey != nullptr) { *isKnownKey = true; } - LocExtType* t = (LocExtType*)uhash_get(keyData->typeMap.getAlias(), type); + LocExtType* t = static_cast(uhash_get(keyData->typeMap.getAlias(), type)); if (t != nullptr) { return t->bcpId; } @@ -506,12 +506,12 @@ ulocimp_toLegacyType(const char* key, const char* type, bool* isKnownKey, bool* return nullptr; } - LocExtKeyData* keyData = (LocExtKeyData*)uhash_get(gLocExtKeyMap, key); + LocExtKeyData* keyData = static_cast(uhash_get(gLocExtKeyMap, key)); if (keyData != nullptr) { if (isKnownKey != nullptr) { *isKnownKey = true; } - LocExtType* t = (LocExtType*)uhash_get(keyData->typeMap.getAlias(), type); + LocExtType* t = static_cast(uhash_get(keyData->typeMap.getAlias(), type)); if (t != nullptr) { return t->legacyId; } diff --git a/icu4c/source/common/uloc_tag.cpp b/icu4c/source/common/uloc_tag.cpp index f5ab0c36a627..45c57ec84d86 100644 --- a/icu4c/source/common/uloc_tag.cpp +++ b/icu4c/source/common/uloc_tag.cpp @@ -415,7 +415,7 @@ _isAlphaNumericString(const char* s, int32_t len) { bool _isAlphaNumericStringLimitedLength(const char* s, int32_t len, int32_t min, int32_t max) { if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len >= min && len <= max && _isAlphaNumericString(s, len)) { return true; @@ -433,7 +433,7 @@ ultag_isLanguageSubtag(const char* s, int32_t len) { * See ICU-20372 */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len >= 2 && len <= 8 && _isAlphaString(s, len)) { return true; @@ -450,7 +450,7 @@ _isExtlangSubtag(const char* s, int32_t len) { * *2("-" 3ALPHA) ; permanently reserved */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 3 && _isAlphaString(s, len)) { return true; @@ -466,7 +466,7 @@ ultag_isScriptSubtag(const char* s, int32_t len) { * script = 4ALPHA ; ISO 15924 code */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 4 && _isAlphaString(s, len)) { return true; @@ -481,7 +481,7 @@ ultag_isRegionSubtag(const char* s, int32_t len) { * / 3DIGIT ; UN M.49 code */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 2 && _isAlphaString(s, len)) { return true; @@ -501,7 +501,7 @@ _isVariantSubtag(const char* s, int32_t len) { * / (DIGIT 3alphanum) */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (_isAlphaNumericStringLimitedLength(s, len, 5, 8)) { return true; @@ -518,7 +518,7 @@ _isSepListOf(bool (*test)(const char*, int32_t), const char* s, int32_t len) { const char *pSubtag = nullptr; if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } while ((p - s) < len) { @@ -526,7 +526,7 @@ _isSepListOf(bool (*test)(const char*, int32_t), const char* s, int32_t len) { if (pSubtag == nullptr) { return false; } - if (!test(pSubtag, (int32_t)(p - pSubtag))) { + if (!test(pSubtag, static_cast(p - pSubtag))) { return false; } pSubtag = nullptr; @@ -538,7 +538,7 @@ _isSepListOf(bool (*test)(const char*, int32_t), const char* s, int32_t len) { if (pSubtag == nullptr) { return false; } - return test(pSubtag, (int32_t)(p - pSubtag)); + return test(pSubtag, static_cast(p - pSubtag)); } } // namespace @@ -572,7 +572,7 @@ _isExtensionSingleton(const char* s, int32_t len) { * / %x79-7A ; y - z */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 1 && (ISALPHA(*s) || ISNUMERIC(*s)) && (uprv_tolower(*s) != PRIVATEUSE)) { return true; @@ -631,7 +631,7 @@ ultag_isUnicodeLocaleKey(const char* s, int32_t len) { * key = alphanum alpha ; */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 2 && (ISALPHA(*s) || ISNUMERIC(*s)) && ISALPHA(s[1])) { return true; @@ -664,7 +664,7 @@ _isTKey(const char* s, int32_t len) * tkey = alpha digit ; */ if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } if (len == 2 && ISALPHA(*s) && ISNUMERIC(*(s + 1))) { return true; @@ -718,7 +718,7 @@ _isTransformedExtensionSubtag(int32_t& state, const char* s, int32_t len) if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } switch (state) { case kStart: @@ -822,7 +822,7 @@ _isStatefulSepListOf(bool (*test)(int32_t&, const char*, int32_t), const char* s int32_t subtagLen = 0; if (len < 0) { - len = (int32_t)uprv_strlen(s); + len = static_cast(uprv_strlen(s)); } for (p = s; len > 0; p++, len--) { @@ -966,8 +966,8 @@ _addExtensionToList(ExtensionListEntry **first, ExtensionListEntry *ext, bool lo /* special handling for locale to bcp conversion */ int32_t len, curlen; - len = (int32_t)uprv_strlen(ext->key); - curlen = (int32_t)uprv_strlen(cur->key); + len = static_cast(uprv_strlen(ext->key)); + curlen = static_cast(uprv_strlen(cur->key)); if (len == 1 && curlen == 1) { if (*(ext->key) == *(cur->key)) { @@ -1074,10 +1074,10 @@ _appendLanguageToLanguageTag(const char* localeID, icu::ByteSink& sink, bool str // ones in DEPRECATEDLANGS[]. Get out of loop on coming // across the 1st 3-letter subtag, if the input is a 2-letter code. // to avoid continuing to try when there's no match. - if (buf.length() < (int32_t)uprv_strlen(DEPRECATEDLANGS[i])) break; + if (buf.length() < static_cast(uprv_strlen(DEPRECATEDLANGS[i]))) break; if (uprv_compareInvCharsAsAscii(buf.data(), DEPRECATEDLANGS[i]) == 0) { const char* const resolved = DEPRECATEDLANGS[i + 1]; - sink.Append(resolved, (int32_t)uprv_strlen(resolved)); + sink.Append(resolved, static_cast(uprv_strlen(resolved))); return; } } @@ -1144,7 +1144,7 @@ _appendRegionToLanguageTag(const char* localeID, icu::ByteSink& sink, bool stric for (int32_t i = 0; i < UPRV_LENGTHOF(DEPRECATEDREGIONS); i += 2) { if (uprv_compareInvCharsAsAscii(buf.data(), DEPRECATEDREGIONS[i]) == 0) { const char* const resolved = DEPRECATEDREGIONS[i + 1]; - sink.Append(resolved, (int32_t)uprv_strlen(resolved)); + sink.Append(resolved, static_cast(uprv_strlen(resolved))); return; } } @@ -1208,7 +1208,7 @@ _appendVariantsToLanguageTag(const char* localeID, icu::ByteSink& sink, bool str /* validate */ if (_isVariantSubtag(pVar, -1)) { - if (uprv_strcmp(pVar,POSIX_VALUE) || buf.length() != (int32_t)uprv_strlen(POSIX_VALUE)) { + if (uprv_strcmp(pVar, POSIX_VALUE) || buf.length() != static_cast(uprv_strlen(POSIX_VALUE))) { /* emit the variant to the list */ icu::LocalPointer var(new VariantListEntry, status); if (U_FAILURE(status)) { @@ -1254,7 +1254,7 @@ _appendVariantsToLanguageTag(const char* localeID, icu::ByteSink& sink, bool str VariantListEntry* var = varFirst; while (var != nullptr) { sink.Append("-", 1); - varLen = (int32_t)uprv_strlen(var->variant); + varLen = static_cast(uprv_strlen(var->variant)); sink.Append(var->variant, varLen); var = var->next; } @@ -1323,7 +1323,7 @@ _appendKeywordsToLanguageTag(const char* localeID, icu::ByteSink& sink, bool str continue; } - keylen = (int32_t)uprv_strlen(key); + keylen = static_cast(uprv_strlen(key)); isBcpUExt = (keylen > 1); /* special keyword used for representing Unicode locale attributes */ @@ -1673,7 +1673,7 @@ _appendLDMLExtensionAsKeywords(const char* ldmlext, ExtensionListEntry** appendT U_ASSERT(pBcpKey != nullptr); - if (bcpKeyLen >= (int32_t)sizeof(bcpKeyBuf)) { + if (bcpKeyLen >= static_cast(sizeof(bcpKeyBuf))) { /* the BCP key is invalid */ status = U_ILLEGAL_ARGUMENT_ERROR; return; @@ -1822,7 +1822,7 @@ _appendKeywords(ULanguageTag* langtag, icu::ByteSink& sink, UErrorCode& status) if (U_SUCCESS(status)) { type = ultag_getPrivateUse(langtag); - if ((int32_t)uprv_strlen(type) > 0) { + if (static_cast(uprv_strlen(type)) > 0) { /* add private use as a keyword */ kwd = extPool.create(); if (kwd == nullptr) { @@ -1840,7 +1840,7 @@ _appendKeywords(ULanguageTag* langtag, icu::ByteSink& sink, UErrorCode& status) /* If a POSIX variant was in the extensions, write it out before writing the keywords. */ if (U_SUCCESS(status) && posixVariant) { - len = (int32_t) uprv_strlen(_POSIX); + len = static_cast(uprv_strlen(_POSIX)); sink.Append(_POSIX, len); } @@ -1857,12 +1857,12 @@ _appendKeywords(ULanguageTag* langtag, icu::ByteSink& sink, UErrorCode& status) } /* key */ - len = (int32_t)uprv_strlen(kwd->key); + len = static_cast(uprv_strlen(kwd->key)); sink.Append(kwd->key, len); sink.Append("=", 1); /* type */ - len = (int32_t)uprv_strlen(kwd->value); + len = static_cast(uprv_strlen(kwd->value)); sink.Append(kwd->value, len); kwd = kwd->next; @@ -1932,7 +1932,7 @@ _appendPrivateuseToLanguageTag(const char* localeID, icu::ByteSink& sink, bool s firstValue = false; } - int32_t len = (int32_t)uprv_strlen(pPriv); + int32_t len = static_cast(uprv_strlen(pPriv)); sink.Append(pPriv, len); } } @@ -1994,11 +1994,11 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta } if (tagLen < 0) { - tagLen = (int32_t)uprv_strlen(tag); + tagLen = static_cast(uprv_strlen(tag)); } /* copy the entire string */ - tagBuf = (char*)uprv_malloc(tagLen + 1); + tagBuf = static_cast(uprv_malloc(tagLen + 1)); if (tagBuf == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -2011,7 +2011,7 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta /* create a ULanguageTag */ icu::LocalULanguageTagPointer t( - (ULanguageTag*)uprv_malloc(sizeof(ULanguageTag))); + static_cast(uprv_malloc(sizeof(ULanguageTag)))); if (t.isNull()) { uprv_free(tagBuf); status = U_MEMORY_ALLOCATION_ERROR; @@ -2050,7 +2050,7 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta uprv_free(tagBuf); // Change t->buf after the free and before return to avoid the second double free in // the destructor of t when t is out of scope. - t->buf = tagBuf = (char*)uprv_malloc(newTagLength + 1); + t->buf = tagBuf = static_cast(uprv_malloc(newTagLength + 1)); if (tagBuf == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -2133,7 +2133,7 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta } else { pNext = pSep + 1; } - subtagLen = (int32_t)(pSep - pSubtag); + subtagLen = static_cast(pSep - pSubtag); if (next & LANG) { if (ultag_isLanguageSubtag(pSubtag, subtagLen)) { @@ -2321,7 +2321,7 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta } else { pNext = pSep + 1; } - subtagLen = (int32_t)(pSep - pSubtag); + subtagLen = static_cast(pSep - pSubtag); if (uprv_strncmp(pSubtag, PRIVUSE_VARIANT_PREFIX, uprv_strlen(PRIVUSE_VARIANT_PREFIX)) == 0) { *pSep = 0; @@ -2373,7 +2373,7 @@ ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& sta } if (parsedLen != nullptr) { - *parsedLen = (int32_t)(pLastGoodPosition - t->buf + parsedLenDelta); + *parsedLen = static_cast(pLastGoodPosition - t->buf + parsedLenDelta); } return t.orphan(); @@ -2698,7 +2698,7 @@ ulocimp_forLanguageTag(const char* langtag, /* language */ subtag = ultag_getExtlangSize(lt.getAlias()) > 0 ? ultag_getExtlang(lt.getAlias(), 0) : ultag_getLanguage(lt.getAlias()); if (uprv_compareInvCharsAsAscii(subtag, LANG_UND) != 0) { - len = (int32_t)uprv_strlen(subtag); + len = static_cast(uprv_strlen(subtag)); if (len > 0) { sink.Append(subtag, len); isEmpty = false; @@ -2707,7 +2707,7 @@ ulocimp_forLanguageTag(const char* langtag, /* script */ subtag = ultag_getScript(lt.getAlias()); - len = (int32_t)uprv_strlen(subtag); + len = static_cast(uprv_strlen(subtag)); if (len > 0) { sink.Append("_", 1); isEmpty = false; @@ -2720,7 +2720,7 @@ ulocimp_forLanguageTag(const char* langtag, /* region */ subtag = ultag_getRegion(lt.getAlias()); - len = (int32_t)uprv_strlen(subtag); + len = static_cast(uprv_strlen(subtag)); if (len > 0) { sink.Append("_", 1); isEmpty = false; diff --git a/icu4c/source/common/ulocbuilder.cpp b/icu4c/source/common/ulocbuilder.cpp index 3b466473624f..b8b6ce8c1869 100644 --- a/icu4c/source/common/ulocbuilder.cpp +++ b/icu4c/source/common/ulocbuilder.cpp @@ -119,7 +119,7 @@ int32_t ulocbld_buildLocaleID(ULocaleBuilder* builder, } icu::Locale l = INTERNAL(builder)->build(*err); if (U_FAILURE(*err)) { return 0; } - int32_t length = (int32_t)(uprv_strlen(l.getName())); + int32_t length = static_cast(uprv_strlen(l.getName())); if (0 < length && length <= bufferCapacity) { uprv_memcpy(buffer, l.getName(), length); } diff --git a/icu4c/source/common/umutablecptrie.cpp b/icu4c/source/common/umutablecptrie.cpp index cdbe27080b49..40ea57f14919 100644 --- a/icu4c/source/common/umutablecptrie.cpp +++ b/icu4c/source/common/umutablecptrie.cpp @@ -45,10 +45,10 @@ constexpr uint8_t MIXED = 1; constexpr uint8_t SAME_AS = 2; /** Start with allocation of 16k data entries. */ -constexpr int32_t INITIAL_DATA_LENGTH = ((int32_t)1 << 14); +constexpr int32_t INITIAL_DATA_LENGTH = static_cast(1) << 14; /** Grow about 8x each time. */ -constexpr int32_t MEDIUM_DATA_LENGTH = ((int32_t)1 << 17); +constexpr int32_t MEDIUM_DATA_LENGTH = static_cast(1) << 17; /** * Maximum length of the build-time data array. @@ -135,8 +135,8 @@ MutableCodePointTrie::MutableCodePointTrie(uint32_t iniValue, uint32_t errValue, #endif { if (U_FAILURE(errorCode)) { return; } - index = (uint32_t *)uprv_malloc(BMP_I_LIMIT * 4); - data = (uint32_t *)uprv_malloc(INITIAL_DATA_LENGTH * 4); + index = static_cast(uprv_malloc(BMP_I_LIMIT * 4)); + data = static_cast(uprv_malloc(INITIAL_DATA_LENGTH * 4)); if (index == nullptr || data == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; @@ -157,8 +157,8 @@ MutableCodePointTrie::MutableCodePointTrie(const MutableCodePointTrie &other, UE { if (U_FAILURE(errorCode)) { return; } int32_t iCapacity = highStart <= BMP_LIMIT ? BMP_I_LIMIT : I_LIMIT; - index = (uint32_t *)uprv_malloc(iCapacity * 4); - data = (uint32_t *)uprv_malloc(other.dataCapacity * 4); + index = static_cast(uprv_malloc(iCapacity * 4)); + data = static_cast(uprv_malloc(other.dataCapacity * 4)); if (index == nullptr || data == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; @@ -268,7 +268,7 @@ void MutableCodePointTrie::clear() { } uint32_t MutableCodePointTrie::get(UChar32 c) const { - if ((uint32_t)c > MAX_UNICODE) { + if (static_cast(c) > MAX_UNICODE) { return errorValue; } if (c >= highStart) { @@ -295,7 +295,7 @@ inline uint32_t maybeFilterValue(uint32_t value, uint32_t initialValue, uint32_t UChar32 MutableCodePointTrie::getRange( UChar32 start, UCPMapValueFilter *filter, const void *context, uint32_t *pValue) const { - if ((uint32_t)start > MAX_UNICODE) { + if (static_cast(start) > MAX_UNICODE) { return U_SENTINEL; } if (start >= highStart) { @@ -387,7 +387,7 @@ bool MutableCodePointTrie::ensureHighStart(UChar32 c) { int32_t i = highStart >> UCPTRIE_SHIFT_3; int32_t iLimit = c >> UCPTRIE_SHIFT_3; if (iLimit > indexCapacity) { - uint32_t *newIndex = (uint32_t *)uprv_malloc(I_LIMIT * 4); + uint32_t* newIndex = static_cast(uprv_malloc(I_LIMIT * 4)); if (newIndex == nullptr) { return false; } uprv_memcpy(newIndex, index, i * 4); uprv_free(index); @@ -418,7 +418,7 @@ int32_t MutableCodePointTrie::allocDataBlock(int32_t blockLength) { // or the code writes more values than should be possible. return -1; } - uint32_t *newData = (uint32_t *)uprv_malloc(capacity * 4); + uint32_t* newData = static_cast(uprv_malloc(capacity * 4)); if (newData == nullptr) { return -1; } @@ -468,7 +468,7 @@ void MutableCodePointTrie::set(UChar32 c, uint32_t value, UErrorCode &errorCode) if (U_FAILURE(errorCode)) { return; } - if ((uint32_t)c > MAX_UNICODE) { + if (static_cast(c) > MAX_UNICODE) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return; } @@ -495,7 +495,7 @@ void MutableCodePointTrie::setRange(UChar32 start, UChar32 end, uint32_t value, if (U_FAILURE(errorCode)) { return; } - if ((uint32_t)start > MAX_UNICODE || (uint32_t)end > MAX_UNICODE || start > end) { + if (static_cast(start) > MAX_UNICODE || static_cast(end) > MAX_UNICODE || start > end) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return; } @@ -792,7 +792,7 @@ class MixedBlocks { } if (newLength > capacity) { uprv_free(table); - table = (uint32_t *)uprv_malloc(newLength * 4); + table = static_cast(uprv_malloc(newLength * 4)); if (table == nullptr) { return false; } @@ -1207,8 +1207,8 @@ int32_t MutableCodePointTrie::compactIndex(int32_t fastILimit, MixedBlocks &mixe int32_t i3FirstNull = -1; for (int32_t i = 0, j = 0; i < fastILimit; ++j) { uint32_t i3 = index[i]; - fastIndex[j] = (uint16_t)i3; - if (i3 == (uint32_t)dataNullOffset) { + fastIndex[j] = static_cast(i3); + if (i3 == static_cast(dataNullOffset)) { if (i3FirstNull < 0) { i3FirstNull = j; } else if (index3NullOffset < 0 && @@ -1257,7 +1257,7 @@ int32_t MutableCodePointTrie::compactIndex(int32_t fastILimit, MixedBlocks &mixe do { uint32_t i3 = index[j]; oredI3 |= i3; - if (i3 != (uint32_t)dataNullOffset) { + if (i3 != static_cast(dataNullOffset)) { isNull = false; } } while (++j < jLimit); @@ -1299,7 +1299,7 @@ int32_t MutableCodePointTrie::compactIndex(int32_t fastILimit, MixedBlocks &mixe // Index table: Fast index, index-1, index-3, index-2. // +1 for possible index table padding. int32_t index16Capacity = fastIndexLength + index1Length + index3Capacity + index2Capacity + 1; - index16 = (uint16_t *)uprv_malloc(index16Capacity * 2); + index16 = static_cast(uprv_malloc(index16Capacity * 2)); if (index16 == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; return 0; @@ -1531,7 +1531,7 @@ int32_t MutableCodePointTrie::compactTrie(int32_t fastILimit, UErrorCode &errorC errorCode = U_MEMORY_ALLOCATION_ERROR; return 0; } - uint32_t *newData = (uint32_t *)uprv_malloc(newDataCapacity * 4); + uint32_t* newData = static_cast(uprv_malloc(newDataCapacity * 4)); if (newData == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; return 0; @@ -1654,7 +1654,7 @@ UCPTrie *MutableCodePointTrie::build(UCPTrieType type, UCPTrieValueWidth valueWi length += sizeof(UCPTrie); U_ASSERT((length & 3) == 0); - uint8_t *bytes = (uint8_t *)uprv_malloc(length); + uint8_t* bytes = static_cast(uprv_malloc(length)); if (bytes == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; clear(); @@ -1679,13 +1679,13 @@ UCPTrie *MutableCodePointTrie::build(UCPTrieType type, UCPTrieValueWidth valueWi bytes += sizeof(UCPTrie); // Fill the index and data arrays. - uint16_t *dest16 = (uint16_t *)bytes; + uint16_t* dest16 = reinterpret_cast(bytes); trie->index = dest16; if (highStart <= fastLimit) { // Condense only the fast index from the mutable-trie index. for (int32_t i = 0, j = 0; j < indexLength; i += SMALL_DATA_BLOCKS_PER_BMP_BLOCK, ++j) { - *dest16++ = (uint16_t)index[i]; // dest16[j] + *dest16++ = static_cast(index[i]); // dest16[j] } } else { uprv_memcpy(dest16, index16, indexLength * 2); @@ -1700,19 +1700,19 @@ UCPTrie *MutableCodePointTrie::build(UCPTrieType type, UCPTrieValueWidth valueWi // Write 16-bit data values. trie->data.ptr16 = dest16; for (int32_t i = dataLength; i > 0; --i) { - *dest16++ = (uint16_t)*p++; + *dest16++ = static_cast(*p++); } break; case UCPTRIE_VALUE_BITS_32: // Write 32-bit data values. - trie->data.ptr32 = (uint32_t *)bytes; + trie->data.ptr32 = reinterpret_cast(bytes); uprv_memcpy(bytes, p, (size_t)dataLength * 4); break; case UCPTRIE_VALUE_BITS_8: // Write 8-bit data values. trie->data.ptr8 = bytes; for (int32_t i = dataLength; i > 0; --i) { - *bytes++ = (uint8_t)*p++; + *bytes++ = static_cast(*p++); } break; default: diff --git a/icu4c/source/common/unames.cpp b/icu4c/source/common/unames.cpp index 1b3192bf25ef..89dbcc88286a 100644 --- a/icu4c/source/common/unames.cpp +++ b/icu4c/source/common/unames.cpp @@ -180,7 +180,7 @@ static UBool U_CALLCONV isAcceptable(void * /*context*/, const char * /*type*/, const char * /*name*/, const UDataInfo *pInfo) { - return (UBool)( + return static_cast( pInfo->size>=20 && pInfo->isBigEndian==U_IS_BIG_ENDIAN && pInfo->charsetFamily==U_CHARSET_FAMILY && @@ -238,9 +238,9 @@ static uint16_t expandName(UCharNames *names, const uint8_t *name, uint16_t nameLength, UCharNameChoice nameChoice, char *buffer, uint16_t bufferLength) { - uint16_t *tokens=(uint16_t *)names+8; + uint16_t* tokens = reinterpret_cast(names) + 8; uint16_t token, tokenCount=*tokens++, bufferPos=0; - uint8_t *tokenStrings=(uint8_t *)names+names->tokenStringOffset; + uint8_t* tokenStrings = reinterpret_cast(names) + names->tokenStringOffset; uint8_t c; if(nameChoice!=U_UNICODE_CHAR_NAME && nameChoice!=U_EXTENDED_CHAR_NAME) { @@ -248,7 +248,7 @@ expandName(UCharNames *names, * skip the modern name if it is not requested _and_ * if the semicolon byte value is a character, not a token number */ - if((uint8_t)';'>=tokenCount || tokens[(uint8_t)';']==(uint16_t)(-1)) { + if (static_cast(';') >= tokenCount || tokens[static_cast(';')] == static_cast(-1)) { int fieldIndex= nameChoice==U_ISO_COMMENT ? 2 : nameChoice; do { while(nameLength>0) { @@ -283,12 +283,12 @@ expandName(UCharNames *names, } } else { token=tokens[c]; - if(token==(uint16_t)(-2)) { + if (token == static_cast(-2)) { /* this is a lead byte for a double-byte token */ token=tokens[c<<8|*name++]; --nameLength; } - if(token==(uint16_t)(-1)) { + if (token == static_cast(-1)) { if(c!=';') { /* explicit letter */ WRITE_CHAR(buffer, bufferLength, bufferPos, c); @@ -297,7 +297,7 @@ expandName(UCharNames *names, extended names and there was no 2.0 name but there is a 1.0 name. */ if(!bufferPos && nameChoice == U_EXTENDED_CHAR_NAME) { - if ((uint8_t)';'>=tokenCount || tokens[(uint8_t)';']==(uint16_t)(-1)) { + if (static_cast(';') >= tokenCount || tokens[static_cast(';')] == static_cast(-1)) { continue; } } @@ -331,9 +331,9 @@ static UBool compareName(UCharNames *names, const uint8_t *name, uint16_t nameLength, UCharNameChoice nameChoice, const char *otherName) { - uint16_t *tokens=(uint16_t *)names+8; + uint16_t* tokens = reinterpret_cast(names) + 8; uint16_t token, tokenCount=*tokens++; - uint8_t *tokenStrings=(uint8_t *)names+names->tokenStringOffset; + uint8_t* tokenStrings = reinterpret_cast(names) + names->tokenStringOffset; uint8_t c; const char *origOtherName = otherName; @@ -342,7 +342,7 @@ compareName(UCharNames *names, * skip the modern name if it is not requested _and_ * if the semicolon byte value is a character, not a token number */ - if((uint8_t)';'>=tokenCount || tokens[(uint8_t)';']==(uint16_t)(-1)) { + if (static_cast(';') >= tokenCount || tokens[static_cast(';')] == static_cast(-1)) { int fieldIndex= nameChoice==U_ISO_COMMENT ? 2 : nameChoice; do { while(nameLength>0) { @@ -370,7 +370,7 @@ compareName(UCharNames *names, if(c>=tokenCount) { if(c!=';') { /* implicit letter */ - if((char)c!=*otherName++) { + if (static_cast(c) != *otherName++) { return false; } } else { @@ -379,15 +379,15 @@ compareName(UCharNames *names, } } else { token=tokens[c]; - if(token==(uint16_t)(-2)) { + if (token == static_cast(-2)) { /* this is a lead byte for a double-byte token */ token=tokens[c<<8|*name++]; --nameLength; } - if(token==(uint16_t)(-1)) { + if (token == static_cast(-1)) { if(c!=';') { /* explicit letter */ - if((char)c!=*otherName++) { + if (static_cast(c) != *otherName++) { return false; } } else { @@ -395,7 +395,7 @@ compareName(UCharNames *names, extended names and there was no 2.0 name but there is a 1.0 name. */ if(otherName == origOtherName && nameChoice == U_EXTENDED_CHAR_NAME) { - if ((uint8_t)';'>=tokenCount || tokens[(uint8_t)';']==(uint16_t)(-1)) { + if (static_cast(';') >= tokenCount || tokens[static_cast(';')] == static_cast(-1)) { continue; } } @@ -406,7 +406,7 @@ compareName(UCharNames *names, /* write token word */ uint8_t *tokenString=tokenStrings+token; while((c=*tokenString++)!=0) { - if((char)c!=*otherName++) { + if (static_cast(c) != *otherName++) { return false; } } @@ -415,7 +415,7 @@ compareName(UCharNames *names, } /* complete match? */ - return (UBool)(*otherName==0); + return static_cast(*otherName == 0); } static uint8_t getCharCat(UChar32 cp) { @@ -462,7 +462,7 @@ static uint16_t getExtName(uint32_t code, char *buffer, uint16_t bufferLength) { if (ndigits < 4) ndigits = 4; for (cp = code, i = ndigits; (cp || i > 0) && bufferLength; cp >>= 4, bufferLength--) { - uint8_t v = (uint8_t)(cp & 0xf); + uint8_t v = static_cast(cp & 0xf); buffer[--i] = (v < 10 ? '0' + v : 'A' + v - 10); } buffer += ndigits; @@ -482,14 +482,14 @@ static uint16_t getExtName(uint32_t code, char *buffer, uint16_t bufferLength) { static const uint16_t * getGroup(UCharNames *names, uint32_t code) { const uint16_t *groups=GET_GROUPS(names); - uint16_t groupMSB=(uint16_t)(code>>GROUP_SHIFT), + uint16_t groupMSB = static_cast(code >> GROUP_SHIFT), start=0, limit=*groups++, number; /* binary search for the group of names that contains the one for code */ while(start((start + limit) / 2); if(groupMSB=12) { /* double-nibble length spread across two bytes */ - length=(uint16_t)(((length&0x3)<<4|lengthByte>>4)+12); + length = static_cast(((length & 0x3) << 4 | lengthByte >> 4) + 12); lengthByte&=0xf; } else if((lengthByte /* &0xf0 */)>=0xc0) { /* double-nibble length spread across this one byte */ - length=(uint16_t)((lengthByte&0x3f)+12); + length = static_cast((lengthByte & 0x3f) + 12); } else { /* single-nibble length in MSBs */ - length=(uint16_t)(lengthByte>>4); + length = static_cast(lengthByte >> 4); lengthByte&=0xf; } @@ -568,7 +568,7 @@ expandGroupName(UCharNames *names, const uint16_t *group, uint16_t lineNumber, UCharNameChoice nameChoice, char *buffer, uint16_t bufferLength) { uint16_t offsets[LINES_PER_GROUP+2], lengths[LINES_PER_GROUP+2]; - const uint8_t *s=(uint8_t *)names+names->groupStringOffset+GET_GROUP_OFFSET(group); + const uint8_t* s = reinterpret_cast(names) + names->groupStringOffset + GET_GROUP_OFFSET(group); s=expandGroupLengths(s, offsets, lengths); return expandName(names, s+offsets[lineNumber], lengths[lineNumber], nameChoice, buffer, bufferLength); @@ -578,8 +578,8 @@ static uint16_t getName(UCharNames *names, uint32_t code, UCharNameChoice nameChoice, char *buffer, uint16_t bufferLength) { const uint16_t *group=getGroup(names, code); - if((uint16_t)(code>>GROUP_SHIFT)==group[GROUP_MSB]) { - return expandGroupName(names, group, (uint16_t)(code&GROUP_MASK), nameChoice, + if (static_cast(code >> GROUP_SHIFT) == group[GROUP_MSB]) { + return expandGroupName(names, group, static_cast(code & GROUP_MASK), nameChoice, buffer, bufferLength); } else { /* group not found */ @@ -601,7 +601,7 @@ enumGroupNames(UCharNames *names, const uint16_t *group, UEnumCharNamesFn *fn, void *context, UCharNameChoice nameChoice) { uint16_t offsets[LINES_PER_GROUP+2], lengths[LINES_PER_GROUP+2]; - const uint8_t *s=(uint8_t *)names+names->groupStringOffset+GET_GROUP_OFFSET(group); + const uint8_t* s = reinterpret_cast(names) + names->groupStringOffset + GET_GROUP_OFFSET(group); s=expandGroupLengths(s, offsets, lengths); if(fn!=DO_FIND_NAME) { @@ -622,10 +622,10 @@ enumGroupNames(UCharNames *names, const uint16_t *group, ++start; } } else { - const char *otherName=((FindName *)context)->otherName; + const char* otherName = static_cast(context)->otherName; while(start<=end) { if(compareName(names, s+offsets[start&GROUP_MASK], lengths[start&GROUP_MASK], nameChoice, otherName)) { - ((FindName *)context)->code=start; + static_cast(context)->code = start; return false; } ++start; @@ -671,15 +671,15 @@ enumNames(UCharNames *names, uint16_t startGroupMSB, endGroupMSB, groupCount; const uint16_t *group, *groupLimit; - startGroupMSB=(uint16_t)(start>>GROUP_SHIFT); - endGroupMSB=(uint16_t)((limit-1)>>GROUP_SHIFT); + startGroupMSB = static_cast(start >> GROUP_SHIFT); + endGroupMSB = static_cast((limit - 1) >> GROUP_SHIFT); /* find the group that contains start, or the highest before it */ group=getGroup(names, start); if(startGroupMSB(group[GROUP_MSB]) << GROUP_SHIFT; if(extLimit>limit) { extLimit=limit; } @@ -703,7 +703,7 @@ enumNames(UCharNames *names, /* enumerate characters in the partial start group */ if((start&GROUP_MASK)!=0) { if(!enumGroupNames(names, group, - start, ((UChar32)startGroupMSB<(startGroupMSB) << GROUP_SHIFT) + LINES_PER_GROUP - 1, fn, context, nameChoice)) { return false; } @@ -727,7 +727,7 @@ enumNames(UCharNames *names, /* enumerate entire groups between the start- and end-groups */ while(group(group[GROUP_MSB]) << GROUP_SHIFT; if(!enumGroupNames(names, group, start, start+LINES_PER_GROUP-1, fn, context, nameChoice)) { return false; } @@ -790,14 +790,14 @@ writeFactorSuffix(const uint16_t *factors, uint16_t count, --count; for(i=count; i>0; --i) { factor=factors[i]; - indexes[i]=(uint16_t)(code%factor); + indexes[i] = static_cast(code % factor); code/=factor; } /* * we don't need to calculate the last modulus because start<=code<=end * guarantees here that code<=factors[0] */ - indexes[0]=(uint16_t)code; + indexes[0] = static_cast(code); /* write each element */ for(;;) { @@ -826,7 +826,7 @@ writeFactorSuffix(const uint16_t *factors, uint16_t count, } /* skip the rest of the strings for this factors[i] */ - factor=(uint16_t)(factors[i]-indexes[i]-1); + factor = static_cast(factors[i] - indexes[i] - 1); while(factor>0) { while(*s++!=0) {} --factor; @@ -865,7 +865,7 @@ getAlgName(AlgorithmicRange *range, uint32_t code, UCharNameChoice nameChoice, switch(range->type) { case 0: { /* name = prefix hex-digits */ - const char *s=(const char *)(range+1); + const char* s = reinterpret_cast(range + 1); char c; uint16_t i, count; @@ -885,7 +885,7 @@ getAlgName(AlgorithmicRange *range, uint32_t code, UCharNameChoice nameChoice, for(i=count; i>0;) { if(--i(code & 0xf); if(c<10) { c+='0'; } else { @@ -902,9 +902,9 @@ getAlgName(AlgorithmicRange *range, uint32_t code, UCharNameChoice nameChoice, case 1: { /* name = prefix factorized-elements */ uint16_t indexes[8]; - const uint16_t *factors=(const uint16_t *)(range+1); + const uint16_t* factors = reinterpret_cast(range + 1); uint16_t count=range->variant; - const char *s=(const char *)(factors+count); + const char* s = reinterpret_cast(factors + count); char c; /* copy prefix */ @@ -950,7 +950,7 @@ enumAlgNames(AlgorithmicRange *range, char c; /* get the full name of the start character */ - length=getAlgName(range, (uint32_t)start, nameChoice, buffer, sizeof(buffer)); + length = getAlgName(range, static_cast(start), nameChoice, buffer, sizeof(buffer)); if(length<=0) { return true; } @@ -973,7 +973,7 @@ enumAlgNames(AlgorithmicRange *range, for (;;) { c=*--s; if(('0'<=c && c<'9') || ('A'<=c && c<'F')) { - *s=(char)(c+1); + *s = static_cast(c + 1); break; } else if(c=='9') { *s='A'; @@ -992,9 +992,9 @@ enumAlgNames(AlgorithmicRange *range, case 1: { uint16_t indexes[8]; const char *elementBases[8], *elements[8]; - const uint16_t *factors=(const uint16_t *)(range+1); + const uint16_t* factors = reinterpret_cast(range + 1); uint16_t count=range->variant; - const char *s=(const char *)(factors+count); + const char* s = reinterpret_cast(factors + count); char *suffix, *t; uint16_t prefixLength, i, idx; @@ -1011,10 +1011,10 @@ enumAlgNames(AlgorithmicRange *range, } /* append the suffix of the start character */ - length=(uint16_t)(prefixLength+writeFactorSuffix(factors, count, - s, (uint32_t)start-range->start, + length = static_cast(prefixLength + writeFactorSuffix(factors, count, + s, static_cast(start) - range->start, indexes, elementBases, elements, - suffix, (uint16_t)(sizeof(buffer)-prefixLength))); + suffix, static_cast(sizeof(buffer) - prefixLength))); /* call the enumerator function with this first character */ if(!fn(context, start, nameChoice, buffer, length)) { @@ -1026,7 +1026,7 @@ enumAlgNames(AlgorithmicRange *range, /* increment the indexes in lexical order bound by the factors */ i=count; for (;;) { - idx=(uint16_t)(indexes[--i]+1); + idx = static_cast(indexes[--i] + 1); if(idxtype) { case 0: { /* name = prefix hex-digits */ - const char *s=(const char *)(range+1); + const char* s = reinterpret_cast(range + 1); char c; uint16_t i, count; /* compare prefix */ while((c=*s++)!=0) { - if((char)c!=*otherName++) { + if (c != *otherName++) { return 0xffff; } } @@ -1112,7 +1112,7 @@ findAlgName(AlgorithmicRange *range, UCharNameChoice nameChoice, const char *oth } /* does it fit into the range? */ - if(*otherName==0 && range->start<=(uint32_t)code && (uint32_t)code<=range->end) { + if (*otherName == 0 && range->start <= static_cast(code) && static_cast(code) <= range->end) { return code; } break; @@ -1121,9 +1121,9 @@ findAlgName(AlgorithmicRange *range, UCharNameChoice nameChoice, const char *oth char buffer[64]; uint16_t indexes[8]; const char *elementBases[8], *elements[8]; - const uint16_t *factors=(const uint16_t *)(range+1); + const uint16_t* factors = reinterpret_cast(range + 1); uint16_t count=range->variant; - const char *s=(const char *)(factors+count), *t; + const char *s = reinterpret_cast(factors + count), *t; UChar32 start, limit; uint16_t i, idx; @@ -1133,13 +1133,13 @@ findAlgName(AlgorithmicRange *range, UCharNameChoice nameChoice, const char *oth /* compare prefix */ while((c=*s++)!=0) { - if((char)c!=*otherName++) { + if (c != *otherName++) { return 0xffff; } } - start=(UChar32)range->start; - limit=(UChar32)(range->end+1); + start = static_cast(range->start); + limit = static_cast(range->end + 1); /* initialize the suffix elements for enumeration; indexes should all be set to 0 */ writeFactorSuffix(factors, count, s, 0, @@ -1155,7 +1155,7 @@ findAlgName(AlgorithmicRange *range, UCharNameChoice nameChoice, const char *oth /* increment the indexes in lexical order bound by the factors */ i=count; for (;;) { - idx=(uint16_t)(indexes[--i]+1); + idx = static_cast(indexes[--i] + 1); if(idxalgNamesOffset); + p = reinterpret_cast(reinterpret_cast(uCharNames) + uCharNames->algNamesOffset); rangeCount=*p; - range=(AlgorithmicRange *)(p+1); + range = reinterpret_cast(p + 1); while(rangeCount>0) { switch(range->type) { case 0: /* name = prefix + (range->variant times) hex-digits */ /* prefix */ - length=calcStringSetLength(gNameSet, (const char *)(range+1))+range->variant; + length = calcStringSetLength(gNameSet, reinterpret_cast(range + 1)) + range->variant; if(length>maxNameLength) { maxNameLength=length; } break; case 1: { /* name = prefix factorized-elements */ - const uint16_t *factors=(const uint16_t *)(range+1); + const uint16_t* factors = reinterpret_cast(range + 1); const char *s; int32_t i, count=range->variant, factor, factorLength, maxFactorLength; /* prefix length */ - s=(const char *)(factors+count); + s = reinterpret_cast(factors + count); length=calcStringSetLength(gNameSet, s); s+=length+1; /* start of factor suffixes */ @@ -1267,7 +1267,7 @@ calcAlgNameSetsLengths(int32_t maxNameLength) { break; } - range=(AlgorithmicRange *)((uint8_t *)range+range->size); + range = reinterpret_cast(reinterpret_cast(range) + range->size); --rangeCount; } return maxNameLength; @@ -1301,19 +1301,19 @@ calcNameSetLength(const uint16_t *tokens, uint16_t tokenCount, const uint8_t *to int32_t length=0, tokenLength; uint16_t c, token; - while(line!=lineLimit && (c=*line++)!=(uint8_t)';') { + while (line != lineLimit && (c = *line++) != static_cast(';')) { if(c>=tokenCount) { /* implicit letter */ SET_ADD(set, c); ++length; } else { token=tokens[c]; - if(token==(uint16_t)(-2)) { + if (token == static_cast(-2)) { /* this is a lead byte for a double-byte token */ c=c<<8|*line++; token=tokens[c]; } - if(token==(uint16_t)(-1)) { + if (token == static_cast(-1)) { /* explicit letter */ SET_ADD(set, c); ++length; @@ -1323,11 +1323,11 @@ calcNameSetLength(const uint16_t *tokens, uint16_t tokenCount, const uint8_t *to /* use cached token length */ tokenLength=tokenLengths[c]; if(tokenLength==0) { - tokenLength=calcStringSetLength(set, (const char *)tokenStrings+token); - tokenLengths[c]=(int8_t)tokenLength; + tokenLength = calcStringSetLength(set, reinterpret_cast(tokenStrings) + token); + tokenLengths[c] = static_cast(tokenLength); } } else { - tokenLength=calcStringSetLength(set, (const char *)tokenStrings+token); + tokenLength = calcStringSetLength(set, reinterpret_cast(tokenStrings) + token); } length+=tokenLength; } @@ -1342,9 +1342,9 @@ static void calcGroupNameSetsLengths(int32_t maxNameLength) { uint16_t offsets[LINES_PER_GROUP+2], lengths[LINES_PER_GROUP+2]; - uint16_t *tokens=(uint16_t *)uCharNames+8; + uint16_t* tokens = reinterpret_cast(uCharNames) + 8; uint16_t tokenCount=*tokens++; - uint8_t *tokenStrings=(uint8_t *)uCharNames+uCharNames->tokenStringOffset; + uint8_t* tokenStrings = reinterpret_cast(uCharNames) + uCharNames->tokenStringOffset; int8_t *tokenLengths; @@ -1353,7 +1353,7 @@ calcGroupNameSetsLengths(int32_t maxNameLength) { int32_t groupCount, lineNumber, length; - tokenLengths=(int8_t *)uprv_malloc(tokenCount); + tokenLengths = static_cast(uprv_malloc(tokenCount)); if(tokenLengths!=nullptr) { uprv_memset(tokenLengths, 0, tokenCount); } @@ -1363,7 +1363,7 @@ calcGroupNameSetsLengths(int32_t maxNameLength) { /* enumerate all groups */ while(groupCount>0) { - s=(uint8_t *)uCharNames+uCharNames->groupStringOffset+GET_GROUP_OFFSET(group); + s = reinterpret_cast(uCharNames) + uCharNames->groupStringOffset + GET_GROUP_OFFSET(group); s=expandGroupLengths(s, offsets, lengths); /* enumerate all lines in each group */ @@ -1424,7 +1424,7 @@ calcNameSetsLengths(UErrorCode *pErrorCode) { } /* set hex digits, used in various names, and <>-, used in extended names */ - for(i=0; i<(int32_t)sizeof(extChars)-1; ++i) { + for (i = 0; i < static_cast(sizeof(extChars)) - 1; ++i) { SET_ADD(gNameSet, extChars[i]); } @@ -1732,7 +1732,7 @@ charSetToUSet(uint32_t cset[8], const USetAdder *sa) { length=0; for(i=0; i<256; ++i) { if(SET_CONTAINS(cset, i)) { - cs[length++]=(char)i; + cs[length++] = static_cast(i); } } @@ -1785,7 +1785,7 @@ makeTokenMap(const UDataSwapper *ds, if(ds->inCharset==ds->outCharset) { /* Same charset family: identity permutation */ for(i=0; i<256; ++i) { - map[i]=(uint8_t)i; + map[i] = static_cast(i); } } else { uprv_memset(map, 0, 256); @@ -1799,7 +1799,7 @@ makeTokenMap(const UDataSwapper *ds, for(i=1; i(i); ds->swapInvChars(ds, &c1, 1, &c2, pErrorCode); if(U_FAILURE(*pErrorCode)) { udata_printError(ds, "unames/makeTokenMap() finds variant character 0x%02x used (input charset family %d)\n", @@ -1821,7 +1821,7 @@ makeTokenMap(const UDataSwapper *ds, while(usedOutChar[j]) { ++j; } - map[i]=(uint8_t)j++; + map[i] = static_cast(j++); } } diff --git a/icu4c/source/common/unicode/brkiter.h b/icu4c/source/common/unicode/brkiter.h index bd96629285bc..30c59c4a94ac 100644 --- a/icu4c/source/common/unicode/brkiter.h +++ b/icu4c/source/common/unicode/brkiter.h @@ -219,7 +219,7 @@ class U_COMMON_API BreakIterator : public UObject { * boundaries have been returned. * @stable ICU 2.0 */ - DONE = (int32_t)-1 + DONE = static_cast(-1) }; /** diff --git a/icu4c/source/common/unicode/bytestream.h b/icu4c/source/common/unicode/bytestream.h index 997746e42804..bea41461bc64 100644 --- a/icu4c/source/common/unicode/bytestream.h +++ b/icu4c/source/common/unicode/bytestream.h @@ -281,7 +281,7 @@ class StringByteSink : public ByteSink { */ StringByteSink(StringClass* dest, int32_t initialAppendCapacity) : dest_(dest) { if (initialAppendCapacity > 0 && - (uint32_t)initialAppendCapacity > (dest->capacity() - dest->length())) { + static_cast(initialAppendCapacity) > dest->capacity() - dest->length()) { dest->reserve(dest->length() + initialAppendCapacity); } } diff --git a/icu4c/source/common/unicode/bytestrie.h b/icu4c/source/common/unicode/bytestrie.h index 1719a6bb83ed..c07dfada941e 100644 --- a/icu4c/source/common/unicode/bytestrie.h +++ b/icu4c/source/common/unicode/bytestrie.h @@ -109,7 +109,7 @@ class U_COMMON_API BytesTrie : public UMemory { */ uint64_t getState64() const { return (static_cast(remainingMatchLength_ + 2) << kState64RemainingShift) | - (uint64_t)(pos_ - bytes_); + static_cast(pos_ - bytes_); } /** @@ -439,7 +439,7 @@ class U_COMMON_API BytesTrie : public UMemory { } static inline UStringTrieResult valueResult(int32_t node) { - return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node&kValueIsFinal)); + return static_cast(USTRINGTRIE_INTERMEDIATE_VALUE - (node & kValueIsFinal)); } // Handles a branch node for both next(byte) and next(string). diff --git a/icu4c/source/common/unicode/edits.h b/icu4c/source/common/unicode/edits.h index dda9d3ca759c..bc3c9438222d 100644 --- a/icu4c/source/common/unicode/edits.h +++ b/icu4c/source/common/unicode/edits.h @@ -508,7 +508,7 @@ class U_COMMON_API Edits final : public UMemory { Edits ©Array(const Edits &other); Edits &moveArray(Edits &src) noexcept; - void setLastUnit(int32_t last) { array[length - 1] = (uint16_t)last; } + void setLastUnit(int32_t last) { array[length - 1] = static_cast(last); } int32_t lastUnit() const { return length > 0 ? array[length - 1] : 0xffff; } void append(int32_t r); diff --git a/icu4c/source/common/unicode/messagepattern.h b/icu4c/source/common/unicode/messagepattern.h index daa7b62389a3..db36ede7274c 100644 --- a/icu4c/source/common/unicode/messagepattern.h +++ b/icu4c/source/common/unicode/messagepattern.h @@ -775,7 +775,7 @@ class U_COMMON_API MessagePattern : public UObject { UMessagePatternArgType getArgType() const { UMessagePatternPartType msgType=getType(); if(msgType ==UMSGPAT_PART_TYPE_ARG_START || msgType ==UMSGPAT_PART_TYPE_ARG_LIMIT) { - return (UMessagePatternArgType)value; + return static_cast(value); } else { return UMSGPAT_ARG_TYPE_NONE; } diff --git a/icu4c/source/common/unicode/simpleformatter.h b/icu4c/source/common/unicode/simpleformatter.h index 33bdd6d48fc8..62c75d08bbc0 100644 --- a/icu4c/source/common/unicode/simpleformatter.h +++ b/icu4c/source/common/unicode/simpleformatter.h @@ -63,7 +63,7 @@ class U_COMMON_API SimpleFormatter final : public UMemory { * Default constructor. * @stable ICU 57 */ - SimpleFormatter() : compiledPattern((char16_t)0) {} + SimpleFormatter() : compiledPattern(static_cast(0)) {} /** * Constructs a formatter from the pattern string. diff --git a/icu4c/source/common/unicode/stringtriebuilder.h b/icu4c/source/common/unicode/stringtriebuilder.h index 429d7883f15c..62108dfe3ea1 100644 --- a/icu4c/source/common/unicode/stringtriebuilder.h +++ b/icu4c/source/common/unicode/stringtriebuilder.h @@ -346,7 +346,7 @@ class U_COMMON_API StringTrieBuilder : public UObject { virtual void write(StringTrieBuilder &builder) override; // Adds a unit with a final value. void add(int32_t c, int32_t value) { - units[length]=(char16_t)c; + units[length] = static_cast(c); equal[length]=nullptr; values[length]=value; ++length; @@ -354,7 +354,7 @@ class U_COMMON_API StringTrieBuilder : public UObject { } // Adds a unit which leads to another match node. void add(int32_t c, Node *node) { - units[length]=(char16_t)c; + units[length] = static_cast(c); equal[length]=node; values[length]=0; ++length; diff --git a/icu4c/source/common/unicode/ucharstrie.h b/icu4c/source/common/unicode/ucharstrie.h index fa1b55616c65..ca4b46947045 100644 --- a/icu4c/source/common/unicode/ucharstrie.h +++ b/icu4c/source/common/unicode/ucharstrie.h @@ -107,7 +107,7 @@ class U_COMMON_API UCharsTrie : public UMemory { */ uint64_t getState64() const { return (static_cast(remainingMatchLength_ + 2) << kState64RemainingShift) | - (uint64_t)(pos_ - uchars_); + static_cast(pos_ - uchars_); } /** @@ -493,7 +493,7 @@ class U_COMMON_API UCharsTrie : public UMemory { } static inline UStringTrieResult valueResult(int32_t node) { - return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node>>15)); + return static_cast(USTRINGTRIE_INTERMEDIATE_VALUE - (node >> 15)); } // Handles a branch node for both next(uchar) and next(string). diff --git a/icu4c/source/common/unicode/uniset.h b/icu4c/source/common/unicode/uniset.h index 127e4ce063b3..de385d18f31e 100644 --- a/icu4c/source/common/unicode/uniset.h +++ b/icu4c/source/common/unicode/uniset.h @@ -1731,7 +1731,7 @@ inline bool UnicodeSet::operator!=(const UnicodeSet& o) const { } inline UBool UnicodeSet::isFrozen() const { - return (UBool)(bmpSet!=nullptr || stringSpan!=nullptr); + return static_cast(bmpSet != nullptr || stringSpan != nullptr); } inline UBool UnicodeSet::containsSome(UChar32 start, UChar32 end) const { @@ -1747,7 +1747,7 @@ inline UBool UnicodeSet::containsSome(const UnicodeString& s) const { } inline UBool UnicodeSet::isBogus() const { - return (UBool)(fFlags & kIsBogus); + return static_cast(fFlags & kIsBogus); } inline UnicodeSet *UnicodeSet::fromUSet(USet *uset) { diff --git a/icu4c/source/common/unicode/unistr.h b/icu4c/source/common/unicode/unistr.h index a41e6358facd..52f0fdbaf049 100644 --- a/icu4c/source/common/unicode/unistr.h +++ b/icu4c/source/common/unicode/unistr.h @@ -2556,7 +2556,7 @@ class U_COMMON_API UnicodeString : public Replaceable * @stable ICU 2.0 */ inline UnicodeString& remove(int32_t start, - int32_t length = (int32_t)INT32_MAX); + int32_t length = static_cast(INT32_MAX)); /** * Remove the characters in the range @@ -2567,7 +2567,7 @@ class U_COMMON_API UnicodeString : public Replaceable * @stable ICU 2.0 */ inline UnicodeString& removeBetween(int32_t start, - int32_t limit = (int32_t)INT32_MAX); + int32_t limit = static_cast(INT32_MAX)); /** * Retain only the characters in the range @@ -3711,7 +3711,7 @@ class U_COMMON_API UnicodeString : public Replaceable * Must be at least U16_MAX_LENGTH for the single-code point constructor to work. * @see UNISTR_OBJECT_SIZE */ - US_STACKBUF_SIZE=(int32_t)(UNISTR_OBJECT_SIZE-sizeof(void *)-2)/U_SIZEOF_UCHAR, + US_STACKBUF_SIZE = static_cast(UNISTR_OBJECT_SIZE - sizeof(void*) - 2) / U_SIZEOF_UCHAR, kInvalidUChar=0xffff, // U+FFFF returned by charAt(invalid index) kInvalidHashCode=0, // invalid hash code kEmptyHashCode=1, // hash code for empty string @@ -3914,16 +3914,16 @@ UnicodeString::hashCode() const inline UBool UnicodeString::isBogus() const -{ return (UBool)(fUnion.fFields.fLengthAndFlags & kIsBogus); } +{ return static_cast(fUnion.fFields.fLengthAndFlags & kIsBogus); } inline UBool UnicodeString::isWritable() const -{ return (UBool)!(fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kIsBogus)); } +{ return static_cast(!(fUnion.fFields.fLengthAndFlags & (kOpenGetBuffer | kIsBogus))); } inline UBool UnicodeString::isBufferWritable() const { - return (UBool)( + return static_cast( !(fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kIsBogus|kBufferIsReadonly)) && (!(fUnion.fFields.fLengthAndFlags&kRefCounted) || refCount()==1)); } @@ -3950,7 +3950,7 @@ UnicodeString::doCompare(int32_t start, int32_t srcLength) const { if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise + return static_cast(!isBogus()); // 0 if both are bogus, 1 otherwise } else { srcText.pinIndices(srcStart, srcLength); return doCompare(start, thisLength, srcText.getArrayStart(), srcStart, srcLength); @@ -4057,7 +4057,7 @@ UnicodeString::doCompareCodePointOrder(int32_t start, int32_t srcLength) const { if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise + return static_cast(!isBogus()); // 0 if both are bogus, 1 otherwise } else { srcText.pinIndices(srcStart, srcLength); return doCompareCodePointOrder(start, thisLength, srcText.getArrayStart(), srcStart, srcLength); @@ -4119,7 +4119,7 @@ UnicodeString::doCaseCompare(int32_t start, uint32_t options) const { if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise + return static_cast(!isBogus()); // 0 if both are bogus, 1 otherwise } else { srcText.pinIndices(srcStart, srcLength); return doCaseCompare(start, thisLength, srcText.getArrayStart(), srcStart, srcLength, options); @@ -4531,7 +4531,7 @@ UnicodeString::tempSubStringBetween(int32_t start, int32_t limit) const { inline char16_t UnicodeString::doCharAt(int32_t offset) const { - if((uint32_t)offset < (uint32_t)length()) { + if (static_cast(offset) < static_cast(length())) { return getArrayStart()[offset]; } else { return kInvalidUChar; @@ -4564,7 +4564,7 @@ inline void UnicodeString::setShortLength(int32_t len) { // requires 0 <= len <= kMaxShortLength fUnion.fFields.fLengthAndFlags = - (int16_t)((fUnion.fFields.fLengthAndFlags & kAllStorageFlags) | (len << kLengthShift)); + static_cast((fUnion.fFields.fLengthAndFlags & kAllStorageFlags) | (len << kLengthShift)); } inline void @@ -4758,7 +4758,7 @@ UnicodeString::truncate(int32_t targetLength) // truncate(0) of a bogus string makes the string empty and non-bogus unBogus(); return false; - } else if((uint32_t)targetLength < (uint32_t)length()) { + } else if (static_cast(targetLength) < static_cast(length())) { setLength(targetLength); return true; } else { diff --git a/icu4c/source/common/unicode/utypes.h b/icu4c/source/common/unicode/utypes.h index 6c7cc5134588..f1a89770f1f7 100644 --- a/icu4c/source/common/unicode/utypes.h +++ b/icu4c/source/common/unicode/utypes.h @@ -713,13 +713,13 @@ typedef enum UErrorCode { * @stable ICU 2.0 */ static - inline UBool U_SUCCESS(UErrorCode code) { return (UBool)(code<=U_ZERO_ERROR); } + inline UBool U_SUCCESS(UErrorCode code) { return static_cast(code <= U_ZERO_ERROR); } /** * Does the error code indicate a failure? * @stable ICU 2.0 */ static - inline UBool U_FAILURE(UErrorCode code) { return (UBool)(code>U_ZERO_ERROR); } + inline UBool U_FAILURE(UErrorCode code) { return static_cast(code > U_ZERO_ERROR); } #else /** * Does the error code indicate success? diff --git a/icu4c/source/common/unifiedcache.cpp b/icu4c/source/common/unifiedcache.cpp index 1284c03813eb..ec7d0284695b 100644 --- a/icu4c/source/common/unifiedcache.cpp +++ b/icu4c/source/common/unifiedcache.cpp @@ -47,20 +47,20 @@ U_NAMESPACE_BEGIN int32_t U_EXPORT2 ucache_hashKeys(const UHashTok key) { - const CacheKeyBase *ckey = (const CacheKeyBase *) key.pointer; + const CacheKeyBase* ckey = static_cast(key.pointer); return ckey->hashCode(); } UBool U_EXPORT2 ucache_compareKeys(const UHashTok key1, const UHashTok key2) { - const CacheKeyBase *p1 = (const CacheKeyBase *) key1.pointer; - const CacheKeyBase *p2 = (const CacheKeyBase *) key2.pointer; + const CacheKeyBase* p1 = static_cast(key1.pointer); + const CacheKeyBase* p2 = static_cast(key2.pointer); return *p1 == *p2; } void U_EXPORT2 ucache_deleteKey(void *obj) { - CacheKeyBase *p = (CacheKeyBase *) obj; + CacheKeyBase* p = static_cast(obj); delete p; } @@ -253,7 +253,7 @@ UBool UnifiedCache::_flush(UBool all) const { } if (all || _isEvictable(element)) { const SharedObject *sharedObject = - (const SharedObject *) element->value.pointer; + static_cast(element->value.pointer); U_ASSERT(sharedObject->cachePtr == this); uhash_removeElement(fHashtable, element); removeSoftRef(sharedObject); // Deletes the sharedObject when softRefCount goes to zero. @@ -285,7 +285,7 @@ void UnifiedCache::_runEvictionSlice() const { } if (_isEvictable(element)) { const SharedObject *sharedObject = - (const SharedObject *) element->value.pointer; + static_cast(element->value.pointer); uhash_removeElement(fHashtable, element); removeSoftRef(sharedObject); // Deletes sharedObject when SoftRefCount goes to zero. ++fAutoEvictedCount; @@ -416,8 +416,8 @@ void UnifiedCache::_put( const SharedObject *value, const UErrorCode status) const { U_ASSERT(_inProgress(element)); - const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; - const SharedObject *oldValue = (const SharedObject *) element->value.pointer; + const CacheKeyBase* theKey = static_cast(element->key.pointer); + const SharedObject* oldValue = static_cast(element->value.pointer); theKey->fCreationStatus = status; if (value->softRefCount == 0) { _registerPrimary(theKey, value); @@ -437,7 +437,7 @@ void UnifiedCache::_fetch( const UHashElement *element, const SharedObject *&value, UErrorCode &status) const { - const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; + const CacheKeyBase* theKey = static_cast(element->key.pointer); status = theKey->fCreationStatus; // Since we have the cache lock, calling regular SharedObject add/removeRef @@ -465,9 +465,8 @@ UBool UnifiedCache::_inProgress( UBool UnifiedCache::_isEvictable(const UHashElement *element) const { - const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; - const SharedObject *theValue = - (const SharedObject *) element->value.pointer; + const CacheKeyBase* theKey = static_cast(element->key.pointer); + const SharedObject* theValue = static_cast(element->value.pointer); // Entries that are under construction are never evictable if (_inProgress(theValue, theKey->fCreationStatus)) { diff --git a/icu4c/source/common/uniset.cpp b/icu4c/source/common/uniset.cpp index 71f57fc12d46..6481c8aa1ed9 100644 --- a/icu4c/source/common/uniset.cpp +++ b/icu4c/source/common/uniset.cpp @@ -108,12 +108,12 @@ static inline void _dbgdt(UnicodeSet* set) { //---------------------------------------------------------------- static void U_CALLCONV cloneUnicodeString(UElement *dst, UElement *src) { - dst->pointer = new UnicodeString(*(UnicodeString*)src->pointer); + dst->pointer = new UnicodeString(*static_cast(src->pointer)); } static int32_t U_CALLCONV compareUnicodeString(UElement t1, UElement t2) { - const UnicodeString &a = *(const UnicodeString*)t1.pointer; - const UnicodeString &b = *(const UnicodeString*)t2.pointer; + const UnicodeString& a = *static_cast(t1.pointer); + const UnicodeString& b = *static_cast(t2.pointer); return a.compare(b); } @@ -355,7 +355,7 @@ UBool UnicodeSet::contains(UChar32 c) const { return false; } int32_t i = findCodePoint(c); - return (UBool)(i & 1); // return true if odd + return static_cast(i & 1); // return true if odd } /** @@ -430,7 +430,7 @@ UBool UnicodeSet::contains(const UnicodeString& s) const { if (cp < 0) { return stringsContains(s); } else { - return contains((UChar32) cp); + return contains(static_cast(cp)); } } @@ -460,8 +460,7 @@ UBool UnicodeSet::containsAll(const UnicodeSet& c) const { * @return true if the test condition is met */ UBool UnicodeSet::containsAll(const UnicodeString& s) const { - return (UBool)(span(s.getBuffer(), s.length(), USET_SPAN_CONTAINED) == - s.length()); + return static_cast(span(s.getBuffer(), s.length(), USET_SPAN_CONTAINED) == s.length()); } /** @@ -506,8 +505,7 @@ UBool UnicodeSet::containsNone(const UnicodeSet& c) const { * @return true if the test condition is met */ UBool UnicodeSet::containsNone(const UnicodeString& s) const { - return (UBool)(span(s.getBuffer(), s.length(), USET_SPAN_NOT_CONTAINED) == - s.length()); + return static_cast(span(s.getBuffer(), s.length(), USET_SPAN_NOT_CONTAINED) == s.length()); } /** @@ -539,7 +537,7 @@ UBool UnicodeSet::matchesIndexValue(uint8_t v) const { } if (hasStrings()) { for (i=0; isize(); ++i) { - const UnicodeString& s = *(const UnicodeString*)strings->elementAt(i); + const UnicodeString& s = *static_cast(strings->elementAt(i)); if (s.isEmpty()) { continue; // skip the empty string } @@ -589,7 +587,7 @@ UMatchDegree UnicodeSet::matches(const Replaceable& text, int32_t highWaterLength = 0; for (i=0; isize(); ++i) { - const UnicodeString& trial = *(const UnicodeString*)strings->elementAt(i); + const UnicodeString& trial = *static_cast(strings->elementAt(i)); if (trial.isEmpty()) { continue; // skip the empty string } @@ -731,12 +729,12 @@ UChar32 UnicodeSet::charAt(int32_t index) const { UChar32 start = list[i++]; int32_t count = list[i++] - start; if (index < count) { - return (UChar32)(start + index); + return static_cast(start + index); } index -= count; } } - return (UChar32)-1; + return static_cast(-1); } /** @@ -958,7 +956,7 @@ UnicodeSet& UnicodeSet::add(const UnicodeString& s) { releasePattern(); } } else { - add((UChar32)cp); + add(static_cast(cp)); } return *this; } @@ -1182,7 +1180,7 @@ UnicodeSet& UnicodeSet::remove(const UnicodeString& s) { releasePattern(); } } else { - remove((UChar32)cp, (UChar32)cp); + remove(static_cast(cp), static_cast(cp)); } return *this; } @@ -1256,7 +1254,7 @@ UnicodeSet& UnicodeSet::complement(const UnicodeString& s) { } releasePattern(); } else { - complement((UChar32)cp, (UChar32)cp); + complement(static_cast(cp), static_cast(cp)); } return *this; } @@ -1279,7 +1277,7 @@ UnicodeSet& UnicodeSet::addAll(const UnicodeSet& c) { // Add strings in order if ( c.strings!=nullptr ) { for (int32_t i=0; isize(); ++i) { - const UnicodeString* s = (const UnicodeString*)c.strings->elementAt(i); + const UnicodeString* s = static_cast(c.strings->elementAt(i)); if (!stringsContains(*s)) { _add(*s); } @@ -1350,7 +1348,7 @@ UnicodeSet& UnicodeSet::complementAll(const UnicodeSet& c) { for (int32_t i=0; isize(); ++i) { void* e = c.strings->elementAt(i); if (strings == nullptr || !strings->removeElement(e)) { - _add(*(const UnicodeString*)e); + _add(*static_cast(e)); } } } @@ -1407,7 +1405,7 @@ UChar32 UnicodeSet::getRangeEnd(int32_t index) const { } const UnicodeString* UnicodeSet::getString(int32_t index) const { - return (const UnicodeString*) strings->elementAt(index); + return static_cast(strings->elementAt(index)); } /** @@ -1433,7 +1431,7 @@ UnicodeSet& UnicodeSet::compact() { capacity = INITIAL_CAPACITY; } else if ((len + 7) < capacity) { // If we have more than a little unused capacity, shrink it to len. - UChar32* temp = (UChar32*) uprv_realloc(list, sizeof(UChar32) * len); + UChar32* temp = static_cast(uprv_realloc(list, sizeof(UChar32) * len)); if (temp) { list = temp; capacity = len; @@ -1492,8 +1490,8 @@ UnicodeSet::UnicodeSet(const uint16_t data[], int32_t dataLen, ESerialization se } // copy smp for(i=bmpLength;i(data[headerSize + bmpLength + (i - bmpLength) * 2 + 0]) << 16) + + static_cast(data[headerSize + bmpLength + (i - bmpLength) * 2 + 1]); #ifdef DEBUG_SERIALIZE printf("<<32@%d+[%d] %lX\n", headerSize+bmpLength+i, i, list[i]); #endif @@ -1568,10 +1566,10 @@ int32_t UnicodeSet::serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& #ifdef DEBUG_SERIALIZE printf("writeHdr\n"); #endif - *dest=(uint16_t)length; + *dest = static_cast(length); if (length>bmpLength) { *dest|=0x8000; - *++dest=(uint16_t)bmpLength; + *++dest = static_cast(bmpLength); } ++dest; @@ -1581,7 +1579,7 @@ int32_t UnicodeSet::serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& #ifdef DEBUG_SERIALIZE printf("writebmp: %x\n", (int)*p); #endif - *dest++=(uint16_t)*p++; + *dest++ = static_cast(*p++); } /* write the supplementary part of the array */ @@ -1589,8 +1587,8 @@ int32_t UnicodeSet::serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& #ifdef DEBUG_SERIALIZE printf("write32: %x\n", (int)*p); #endif - *dest++=(uint16_t)(*p>>16); - *dest++=(uint16_t)*p++; + *dest++ = static_cast(*p >> 16); + *dest++ = static_cast(*p++); } } else { ec=U_BUFFER_OVERFLOW_ERROR; @@ -1646,7 +1644,7 @@ bool UnicodeSet::ensureCapacity(int32_t newLen) { return true; } int32_t newCapacity = nextCapacity(newLen); - UChar32* temp = (UChar32*) uprv_malloc(newCapacity * sizeof(UChar32)); + UChar32* temp = static_cast(uprv_malloc(newCapacity * sizeof(UChar32))); if (temp == nullptr) { setToBogus(); // set the object to bogus state if an OOM failure occurred. return false; @@ -1669,7 +1667,7 @@ bool UnicodeSet::ensureBufferCapacity(int32_t newLen) { return true; } int32_t newCapacity = nextCapacity(newLen); - UChar32* temp = (UChar32*) uprv_malloc(newCapacity * sizeof(UChar32)); + UChar32* temp = static_cast(uprv_malloc(newCapacity * sizeof(UChar32))); if (temp == nullptr) { setToBogus(); return false; @@ -2137,7 +2135,7 @@ UnicodeString& UnicodeSet::_generatePattern(UnicodeString& result, for (int32_t i = 0; isize(); ++i) { result.append(u'{'); _appendToPat(result, - *(const UnicodeString*) strings->elementAt(i), + *static_cast(strings->elementAt(i)), escapeUnprintable); result.append(u'}'); } @@ -2161,7 +2159,7 @@ void UnicodeSet::releasePattern() { */ void UnicodeSet::setPattern(const char16_t *newPat, int32_t newPatLen) { releasePattern(); - pat = (char16_t *)uprv_malloc((newPatLen + 1) * sizeof(char16_t)); + pat = static_cast(uprv_malloc((newPatLen + 1) * sizeof(char16_t))); if (pat) { patLen = newPatLen; u_memcpy(pat, newPat, patLen); @@ -2204,7 +2202,7 @@ UnicodeSet *UnicodeSet::freeze() { int32_t UnicodeSet::span(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const { if(length>0 && bmpSet!=nullptr) { - return (int32_t)(bmpSet->span(s, s+length, spanCondition)-s); + return static_cast(bmpSet->span(s, s + length, spanCondition) - s); } if(length<0) { length=u_strlen(s); @@ -2241,7 +2239,7 @@ int32_t UnicodeSet::span(const char16_t *s, int32_t length, USetSpanCondition sp int32_t UnicodeSet::spanBack(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const { if(length>0 && bmpSet!=nullptr) { - return (int32_t)(bmpSet->spanBack(s, s+length, spanCondition)-s); + return static_cast(bmpSet->spanBack(s, s + length, spanCondition) - s); } if(length<0) { length=u_strlen(s); @@ -2278,24 +2276,24 @@ int32_t UnicodeSet::spanBack(const char16_t *s, int32_t length, USetSpanConditio int32_t UnicodeSet::spanUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const { if(length>0 && bmpSet!=nullptr) { - const uint8_t *s0=(const uint8_t *)s; - return (int32_t)(bmpSet->spanUTF8(s0, length, spanCondition)-s0); + const uint8_t* s0 = reinterpret_cast(s); + return static_cast(bmpSet->spanUTF8(s0, length, spanCondition) - s0); } if(length<0) { - length=(int32_t)uprv_strlen(s); + length = static_cast(uprv_strlen(s)); } if(length==0) { return 0; } if(stringSpan!=nullptr) { - return stringSpan->spanUTF8((const uint8_t *)s, length, spanCondition); + return stringSpan->spanUTF8(reinterpret_cast(s), length, spanCondition); } else if(hasStrings()) { uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ? UnicodeSetStringSpan::FWD_UTF8_NOT_CONTAINED : UnicodeSetStringSpan::FWD_UTF8_CONTAINED; UnicodeSetStringSpan strSpan(*this, *strings, which); if(strSpan.needsStringSpanUTF8()) { - return strSpan.spanUTF8((const uint8_t *)s, length, spanCondition); + return strSpan.spanUTF8(reinterpret_cast(s), length, spanCondition); } } @@ -2316,24 +2314,24 @@ int32_t UnicodeSet::spanUTF8(const char *s, int32_t length, USetSpanCondition sp int32_t UnicodeSet::spanBackUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const { if(length>0 && bmpSet!=nullptr) { - const uint8_t *s0=(const uint8_t *)s; + const uint8_t* s0 = reinterpret_cast(s); return bmpSet->spanBackUTF8(s0, length, spanCondition); } if(length<0) { - length=(int32_t)uprv_strlen(s); + length = static_cast(uprv_strlen(s)); } if(length==0) { return 0; } if(stringSpan!=nullptr) { - return stringSpan->spanBackUTF8((const uint8_t *)s, length, spanCondition); + return stringSpan->spanBackUTF8(reinterpret_cast(s), length, spanCondition); } else if(hasStrings()) { uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ? UnicodeSetStringSpan::BACK_UTF8_NOT_CONTAINED : UnicodeSetStringSpan::BACK_UTF8_CONTAINED; UnicodeSetStringSpan strSpan(*this, *strings, which); if(strSpan.needsStringSpanUTF8()) { - return strSpan.spanBackUTF8((const uint8_t *)s, length, spanCondition); + return strSpan.spanBackUTF8(reinterpret_cast(s), length, spanCondition); } } diff --git a/icu4c/source/common/uniset_closure.cpp b/icu4c/source/common/uniset_closure.cpp index 173a5cbaaef6..061ae35717ae 100644 --- a/icu4c/source/common/uniset_closure.cpp +++ b/icu4c/source/common/uniset_closure.cpp @@ -116,17 +116,17 @@ UnicodeSet& UnicodeSet::applyPattern(const UnicodeString& pattern, // Does not use uset.h to reduce code dependencies static void U_CALLCONV _set_add(USet *set, UChar32 c) { - ((UnicodeSet *)set)->add(c); + reinterpret_cast(set)->add(c); } static void U_CALLCONV _set_addRange(USet *set, UChar32 start, UChar32 end) { - ((UnicodeSet *)set)->add(start, end); + reinterpret_cast(set)->add(start, end); } static void U_CALLCONV _set_addString(USet *set, const char16_t *str, int32_t length) { - ((UnicodeSet *)set)->add(UnicodeString((UBool)(length<0), str, length)); + reinterpret_cast(set)->add(UnicodeString(static_cast(length < 0), str, length)); } //---------------------------------------------------------------- @@ -143,7 +143,7 @@ addCaseMapping(UnicodeSet &set, int32_t result, const char16_t *full, UnicodeStr set.add(result); } else { // add a string case mapping from full with length result - str.setTo((UBool)false, full, result); + str.setTo(static_cast(false), full, result); set.add(str); } } @@ -277,7 +277,7 @@ void UnicodeSet::closeOverCaseInsensitive(bool simple) { if (hasStrings()) { UnicodeString str; for (int32_t j=0; jsize(); ++j) { - const UnicodeString *pStr = (const UnicodeString *) strings->elementAt(j); + const UnicodeString* pStr = static_cast(strings->elementAt(j)); if (simple) { if (scfString(*pStr, str)) { foldSet.remove(*pStr).add(str); @@ -335,7 +335,7 @@ void UnicodeSet::closeOverAddCaseMappings() { if (U_SUCCESS(status)) { #endif for (int32_t j=0; jsize(); ++j) { - const UnicodeString *pStr = (const UnicodeString *) strings->elementAt(j); + const UnicodeString* pStr = static_cast(strings->elementAt(j)); (str = *pStr).toLower(root); foldSet.add(str); #if !UCONFIG_NO_BREAK_ITERATION diff --git a/icu4c/source/common/uniset_props.cpp b/icu4c/source/common/uniset_props.cpp index e6f880c9f261..c572a1fa4391 100644 --- a/icu4c/source/common/uniset_props.cpp +++ b/icu4c/source/common/uniset_props.cpp @@ -209,7 +209,7 @@ UnicodeSet::applyPatternIgnoreSpace(const UnicodeString& pattern, */ UBool UnicodeSet::resemblesPattern(const UnicodeString& pattern, int32_t pos) { return ((pos+1) < pattern.length() && - pattern.charAt(pos) == (char16_t)91/*[*/) || + pattern.charAt(pos) == static_cast(91)/*[*/) || resemblesPropertyPattern(pattern, pos); } @@ -471,7 +471,7 @@ void UnicodeSet::applyPattern(RuleCharacterIterator& chars, case u'-': if (op == 0) { if (lastItem != 0) { - op = (char16_t) c; + op = static_cast(c); continue; } else { // Treat final trailing '-' as a literal @@ -490,7 +490,7 @@ void UnicodeSet::applyPattern(RuleCharacterIterator& chars, return; case u'&': if (lastItem == 2 && op == 0) { - op = (char16_t) c; + op = static_cast(c); continue; } // syntaxError(chars, "'&' not after set"); @@ -561,7 +561,7 @@ void UnicodeSet::applyPattern(RuleCharacterIterator& chars, } add(U_ETHER); usePat = true; - patLocal.append((char16_t) SymbolTable::SYMBOL_REF); + patLocal.append(static_cast(SymbolTable::SYMBOL_REF)); patLocal.append(u']'); mode = 2; continue; @@ -658,11 +658,11 @@ void UnicodeSet::applyPattern(RuleCharacterIterator& chars, namespace { UBool numericValueFilter(UChar32 ch, void* context) { - return u_getNumericValue(ch) == *(double*)context; + return u_getNumericValue(ch) == *static_cast(context); } UBool generalCategoryMaskFilter(UChar32 ch, void* context) { - int32_t value = *(int32_t*)context; + int32_t value = *static_cast(context); return (U_GET_GC_MASK((UChar32) ch) & value) != 0; } @@ -670,7 +670,7 @@ UBool versionFilter(UChar32 ch, void* context) { static const UVersionInfo none = { 0, 0, 0, 0 }; UVersionInfo v; u_charAge(ch, v); - UVersionInfo* version = (UVersionInfo*)context; + UVersionInfo* version = static_cast(context); return uprv_memcmp(&v, &none, sizeof(v)) > 0 && uprv_memcmp(&v, version, sizeof(v)) <= 0; } @@ -680,16 +680,16 @@ typedef struct { } IntPropertyContext; UBool intPropertyFilter(UChar32 ch, void* context) { - IntPropertyContext* c = (IntPropertyContext*)context; - return u_getIntPropertyValue((UChar32) ch, c->prop) == c->value; + IntPropertyContext* c = static_cast(context); + return u_getIntPropertyValue(ch, c->prop) == c->value; } UBool scriptExtensionsFilter(UChar32 ch, void* context) { - return uscript_hasScript(ch, *(UScriptCode*)context); + return uscript_hasScript(ch, *static_cast(context)); } UBool idTypeFilter(UChar32 ch, void* context) { - return u_hasIDType(ch, *(UIdentifierType*)context); + return u_hasIDType(ch, *static_cast(context)); } } // namespace @@ -738,7 +738,7 @@ void UnicodeSet::applyFilter(UnicodeSet::Filter filter, } } if (startHasProperty >= 0) { - add((UChar32)startHasProperty, (UChar32)0x10FFFF); + add(startHasProperty, static_cast(0x10FFFF)); } if (isBogus() && U_SUCCESS(status)) { // We likely ran out of memory. AHHH! @@ -784,11 +784,11 @@ UnicodeSet::applyIntPropertyValue(UProperty prop, int32_t value, UErrorCode& ec) applyFilter(generalCategoryMaskFilter, &value, inclusions, ec); } else if (prop == UCHAR_SCRIPT_EXTENSIONS) { const UnicodeSet* inclusions = CharacterProperties::getInclusionsForProperty(prop, ec); - UScriptCode script = (UScriptCode)value; + UScriptCode script = static_cast(value); applyFilter(scriptExtensionsFilter, &script, inclusions, ec); } else if (prop == UCHAR_IDENTIFIER_TYPE) { const UnicodeSet* inclusions = CharacterProperties::getInclusionsForProperty(prop, ec); - UIdentifierType idType = (UIdentifierType)value; + UIdentifierType idType = static_cast(value); applyFilter(idTypeFilter, &idType, inclusions, ec); } else if (0 <= prop && prop < UCHAR_BINARY_LIMIT) { if (value == 0 || value == 1) { @@ -862,7 +862,7 @@ UnicodeSet::applyPropertyAlias(const UnicodeString& prop, // We catch NaN here because comparing it with both 0 and 255 will be false // (as are all comparisons with NaN). if (*end != 0 || !(0 <= val && val <= 255) || - (v = (int32_t)val) != val) { + (v = static_cast(val)) != val) { // non-integral value or outside 0..255, or trailing junk FAIL(ec); } diff --git a/icu4c/source/common/unisetspan.cpp b/icu4c/source/common/unisetspan.cpp index b7256d8fd164..dc4e89e5ca4a 100644 --- a/icu4c/source/common/unisetspan.cpp +++ b/icu4c/source/common/unisetspan.cpp @@ -66,10 +66,10 @@ class OffsetList { // Only ever stack-allocated, does not need to inherit UMemo // Call exactly once if the list is to be used. void setMaxLength(int32_t maxLength) { - if(maxLength<=(int32_t)sizeof(staticList)) { - capacity=(int32_t)sizeof(staticList); + if (maxLength <= static_cast(sizeof(staticList))) { + capacity = static_cast(sizeof(staticList)); } else { - UBool *l=(UBool *)uprv_malloc(maxLength); + UBool* l = static_cast(uprv_malloc(maxLength)); if(l!=nullptr) { list=l; capacity=maxLength; @@ -84,7 +84,7 @@ class OffsetList { // Only ever stack-allocated, does not need to inherit UMemo } UBool isEmpty() const { - return (UBool)(length==0); + return static_cast(length == 0); } // Reduce all stored offsets by delta, used when the current position @@ -183,7 +183,7 @@ static int32_t appendUTF8(const char16_t *s, int32_t length, uint8_t *t, int32_t capacity) { UErrorCode errorCode=U_ZERO_ERROR; int32_t length8=0; - u_strToUTF8((char *)t, capacity, &length8, s, length, &errorCode); + u_strToUTF8(reinterpret_cast(t), capacity, &length8, s, length, &errorCode); if(U_SUCCESS(errorCode)) { return length8; } else { @@ -196,7 +196,7 @@ appendUTF8(const char16_t *s, int32_t length, uint8_t *t, int32_t capacity) { static inline uint8_t makeSpanLengthByte(int32_t spanLength) { // 0xfe==UnicodeSetStringSpan::LONG_SPAN - return spanLength<0xfe ? (uint8_t)spanLength : (uint8_t)0xfe; + return spanLength < 0xfe ? static_cast(spanLength) : static_cast(0xfe); } // Construct for all variants of span(), or only for any one variant. @@ -208,7 +208,7 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, utf8Lengths(nullptr), spanLengths(nullptr), utf8(nullptr), utf8Length(0), maxLength16(0), maxLength8(0), - all((UBool)(which==ALL)) { + all(static_cast(which == ALL)) { spanSet.retainAll(set); if(which&NOT_CONTAINED) { // Default to the same sets. @@ -228,7 +228,7 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, int32_t i, spanLength; UBool someRelevant=false; for(i=0; i(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); if (length16==0) { @@ -279,10 +279,10 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, allocSize+=stringsLength*4+utf8Length; } } - if(allocSize<=(int32_t)sizeof(staticLengths)) { + if (allocSize <= static_cast(sizeof(staticLengths))) { utf8Lengths=staticLengths; } else { - utf8Lengths=(int32_t *)uprv_malloc(allocSize); + utf8Lengths = static_cast(uprv_malloc(allocSize)); if(utf8Lengths==nullptr) { maxLength16=maxLength8=0; // Prevent usage by making needsStringSpanUTF16/8() return false. return; // Out of memory. @@ -291,7 +291,7 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, if(all) { // Store span lengths for all span() variants. - spanLengths=(uint8_t *)(utf8Lengths+stringsLength); + spanLengths = reinterpret_cast(utf8Lengths + stringsLength); spanBackLengths=spanLengths+stringsLength; spanUTF8Lengths=spanBackLengths+stringsLength; spanBackUTF8Lengths=spanUTF8Lengths+stringsLength; @@ -299,10 +299,10 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, } else { // Store span lengths for only one span() variant. if(which&UTF8) { - spanLengths=(uint8_t *)(utf8Lengths+stringsLength); + spanLengths = reinterpret_cast(utf8Lengths + stringsLength); utf8=spanLengths+stringsLength; } else { - spanLengths=(uint8_t *)utf8Lengths; + spanLengths = reinterpret_cast(utf8Lengths); } spanBackLengths=spanUTF8Lengths=spanBackUTF8Lengths=spanLengths; } @@ -311,7 +311,7 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, int32_t utf8Count=0; // Count UTF-8 bytes written so far. for(i=0; i(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); spanLength=spanSet.span(s16, length16, USET_SPAN_CONTAINED); @@ -334,15 +334,15 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, int32_t length8=appendUTF8(s16, length16, s8, utf8Length-utf8Count); utf8Count+=utf8Lengths[i]=length8; if(length8==0) { // Irrelevant for UTF-8 because not representable in UTF-8. - spanUTF8Lengths[i]=spanBackUTF8Lengths[i]=(uint8_t)ALL_CP_CONTAINED; + spanUTF8Lengths[i] = spanBackUTF8Lengths[i] = static_cast(ALL_CP_CONTAINED); } else { // Relevant for UTF-8. if(which&CONTAINED) { if(which&FWD) { - spanLength=spanSet.spanUTF8((const char *)s8, length8, USET_SPAN_CONTAINED); + spanLength = spanSet.spanUTF8(reinterpret_cast(s8), length8, USET_SPAN_CONTAINED); spanUTF8Lengths[i]=makeSpanLengthByte(spanLength); } if(which&BACK) { - spanLength=length8-spanSet.spanBackUTF8((const char *)s8, length8, USET_SPAN_CONTAINED); + spanLength = length8 - spanSet.spanBackUTF8(reinterpret_cast(s8), length8, USET_SPAN_CONTAINED); spanBackUTF8Lengths[i]=makeSpanLengthByte(spanLength); } } else /* not CONTAINED, not all, but NOT_CONTAINED */ { @@ -378,10 +378,10 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSet &set, if(all) { spanLengths[i]=spanBackLengths[i]= spanUTF8Lengths[i]=spanBackUTF8Lengths[i]= - (uint8_t)ALL_CP_CONTAINED; + static_cast(ALL_CP_CONTAINED); } else { // All spanXYZLengths pointers contain the same address. - spanLengths[i]=(uint8_t)ALL_CP_CONTAINED; + spanLengths[i] = static_cast(ALL_CP_CONTAINED); } } } @@ -410,17 +410,17 @@ UnicodeSetStringSpan::UnicodeSetStringSpan(const UnicodeSetStringSpan &otherStri // UTF-8 lengths, 4 sets of span lengths, UTF-8 strings. int32_t stringsLength=strings.size(); int32_t allocSize=stringsLength*(4+1+1+1+1)+utf8Length; - if(allocSize<=(int32_t)sizeof(staticLengths)) { + if (allocSize <= static_cast(sizeof(staticLengths))) { utf8Lengths=staticLengths; } else { - utf8Lengths=(int32_t *)uprv_malloc(allocSize); + utf8Lengths = static_cast(uprv_malloc(allocSize)); if(utf8Lengths==nullptr) { maxLength16=maxLength8=0; // Prevent usage by making needsStringSpanUTF16/8() return false. return; // Out of memory. } } - spanLengths=(uint8_t *)(utf8Lengths+stringsLength); + spanLengths = reinterpret_cast(utf8Lengths + stringsLength); utf8=spanLengths+stringsLength*4; uprv_memcpy(utf8Lengths, otherStringSpan.utf8Lengths, allocSize); } @@ -658,7 +658,7 @@ int32_t UnicodeSetStringSpan::span(const char16_t *s, int32_t length, USetSpanCo if(overlap==ALL_CP_CONTAINED) { continue; // Irrelevant string. (Also the empty string.) } - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); U_ASSERT(length>0); @@ -698,7 +698,7 @@ int32_t UnicodeSetStringSpan::span(const char16_t *s, int32_t length, USetSpanCo // For longest match, we do need to try to match even an all-contained string // to find the match from the earliest start. - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); if (length16==0) { @@ -826,7 +826,7 @@ int32_t UnicodeSetStringSpan::spanBack(const char16_t *s, int32_t length, USetSp if(overlap==ALL_CP_CONTAINED) { continue; // Irrelevant string. (Also the empty string.) } - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); U_ASSERT(length>0); @@ -868,7 +868,7 @@ int32_t UnicodeSetStringSpan::spanBack(const char16_t *s, int32_t length, USetSp // For longest match, we do need to try to match even an all-contained string // to find the match from the latest end. - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); if (length16==0) { @@ -968,7 +968,7 @@ int32_t UnicodeSetStringSpan::spanUTF8(const uint8_t *s, int32_t length, USetSpa if(spanCondition==USET_SPAN_NOT_CONTAINED) { return spanNotUTF8(s, length); } - int32_t spanLength=spanSet.spanUTF8((const char *)s, length, USET_SPAN_CONTAINED); + int32_t spanLength = spanSet.spanUTF8(reinterpret_cast(s), length, USET_SPAN_CONTAINED); if(spanLength==length) { return length; } @@ -1104,7 +1104,7 @@ int32_t UnicodeSetStringSpan::spanUTF8(const uint8_t *s, int32_t length, USetSpa if(offsets.isEmpty()) { // No more strings matched after a previous string match. // Try another code point span from after the last string match. - spanLength=spanSet.spanUTF8((const char *)s+pos, rest, USET_SPAN_CONTAINED); + spanLength = spanSet.spanUTF8(reinterpret_cast(s) + pos, rest, USET_SPAN_CONTAINED); if( spanLength==rest || // Reached the end of the string, or spanLength==0 // neither strings nor span progressed. ) { @@ -1145,7 +1145,7 @@ int32_t UnicodeSetStringSpan::spanBackUTF8(const uint8_t *s, int32_t length, USe if(spanCondition==USET_SPAN_NOT_CONTAINED) { return spanNotBackUTF8(s, length); } - int32_t pos=spanSet.spanBackUTF8((const char *)s, length, USET_SPAN_CONTAINED); + int32_t pos = spanSet.spanBackUTF8(reinterpret_cast(s), length, USET_SPAN_CONTAINED); if(pos==0) { return 0; } @@ -1284,7 +1284,7 @@ int32_t UnicodeSetStringSpan::spanBackUTF8(const uint8_t *s, int32_t length, USe // No more strings matched before a previous string match. // Try another code point span from before the last string match. int32_t oldPos=pos; - pos=spanSet.spanBackUTF8((const char *)s, oldPos, USET_SPAN_CONTAINED); + pos = spanSet.spanBackUTF8(reinterpret_cast(s), oldPos, USET_SPAN_CONTAINED); spanLength=oldPos-pos; if( pos==0 || // Reached the start of the string, or spanLength==0 // neither strings nor span progressed. @@ -1371,7 +1371,7 @@ int32_t UnicodeSetStringSpan::spanNot(const char16_t *s, int32_t length) const { if(spanLengths[i]==ALL_CP_CONTAINED) { continue; // Irrelevant string. (Also the empty string.) } - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); U_ASSERT(length>0); @@ -1415,7 +1415,7 @@ int32_t UnicodeSetStringSpan::spanNotBack(const char16_t *s, int32_t length) con if(spanLengths[i]==ALL_CP_CONTAINED) { continue; // Irrelevant string. (Also the empty string.) } - const UnicodeString &string=*(const UnicodeString *)strings.elementAt(i); + const UnicodeString& string = *static_cast(strings.elementAt(i)); const char16_t *s16=string.getBuffer(); int32_t length16=string.length(); U_ASSERT(length>0); @@ -1442,7 +1442,7 @@ int32_t UnicodeSetStringSpan::spanNotUTF8(const uint8_t *s, int32_t length) cons do { // Span until we find a code point from the set, // or a code point that starts or ends some string. - i=pSpanNotSet->spanUTF8((const char *)s+pos, rest, USET_SPAN_NOT_CONTAINED); + i = pSpanNotSet->spanUTF8(reinterpret_cast(s) + pos, rest, USET_SPAN_NOT_CONTAINED); if(i==rest) { return length; // Reached the end of the string. } @@ -1487,7 +1487,7 @@ int32_t UnicodeSetStringSpan::spanNotBackUTF8(const uint8_t *s, int32_t length) do { // Span until we find a code point from the set, // or a code point that starts or ends some string. - pos=pSpanNotSet->spanBackUTF8((const char *)s, pos, USET_SPAN_NOT_CONTAINED); + pos = pSpanNotSet->spanBackUTF8(reinterpret_cast(s), pos, USET_SPAN_NOT_CONTAINED); if(pos==0) { return 0; // Reached the start of the string. } diff --git a/icu4c/source/common/unisetspan.h b/icu4c/source/common/unisetspan.h index f1dc8e6f743a..ecf8a9b00ffc 100644 --- a/icu4c/source/common/unisetspan.h +++ b/icu4c/source/common/unisetspan.h @@ -141,11 +141,11 @@ class UnicodeSetStringSpan : public UMemory { }; UBool UnicodeSetStringSpan::needsStringSpanUTF16() { - return (UBool)(maxLength16!=0); + return static_cast(maxLength16 != 0); } UBool UnicodeSetStringSpan::needsStringSpanUTF8() { - return (UBool)(maxLength8!=0); + return static_cast(maxLength8 != 0); } UBool UnicodeSetStringSpan::contains(UChar32 c) const { diff --git a/icu4c/source/common/unistr.cpp b/icu4c/source/common/unistr.cpp index ce81138c2ca3..d6dcfc5ca446 100644 --- a/icu4c/source/common/unistr.cpp +++ b/icu4c/source/common/unistr.cpp @@ -108,7 +108,7 @@ UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString) UnicodeString U_EXPORT2 operator+ (const UnicodeString &s1, const UnicodeString &s2) { return - UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0). + UnicodeString(s1.length() + s2.length() + 1, static_cast(0), 0). append(s1). append(s2); } @@ -120,23 +120,23 @@ operator+ (const UnicodeString &s1, const UnicodeString &s2) { void UnicodeString::addRef() { - umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1); + umtx_atomic_inc(reinterpret_cast(fUnion.fFields.fArray) - 1); } int32_t UnicodeString::removeRef() { - return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1); + return umtx_atomic_dec(reinterpret_cast(fUnion.fFields.fArray) - 1); } int32_t UnicodeString::refCount() const { - return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1)); + return umtx_loadAcquire(*(reinterpret_cast(fUnion.fFields.fArray) - 1)); } void UnicodeString::releaseArray() { if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) { - uprv_free((int32_t *)fUnion.fFields.fArray - 1); + uprv_free(reinterpret_cast(fUnion.fFields.fArray) - 1); } } @@ -150,7 +150,7 @@ UnicodeString::releaseArray() { UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { fUnion.fFields.fLengthAndFlags = 0; - if(count <= 0 || (uint32_t)c > 0x10ffff) { + if (count <= 0 || static_cast(c) > 0x10ffff) { // just allocate and do not do anything else allocate(capacity); } else if(c <= 0xffff) { @@ -160,7 +160,7 @@ UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { } if(allocate(capacity)) { char16_t *array = getArrayStart(); - char16_t unit = (char16_t)c; + char16_t unit = static_cast(c); for(int32_t i = 0; i < length; ++i) { array[i] = unit; } @@ -256,7 +256,7 @@ UnicodeString::UnicodeString(char16_t *buff, while(p != limit && *p != 0) { ++p; } - buffLength = (int32_t)(p - buff); + buffLength = static_cast(p - buff); } setArray(buff, buffLength, buffCapacity); } @@ -268,7 +268,7 @@ UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) { // treat as an empty string } else { if(length<0) { - length=(int32_t)uprv_strlen(src); + length = static_cast(uprv_strlen(src)); } if(cloneArrayIfNeeded(length, length, false)) { u_charsToUChars(src, getArrayStart(), length); @@ -295,7 +295,7 @@ UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) { return; } if(dataLength == -1) { - dataLength = (int32_t)uprv_strlen(codepageData); + dataLength = static_cast(uprv_strlen(codepageData)); } setToUTF8(StringPiece(codepageData, dataLength)); } @@ -376,18 +376,18 @@ UnicodeString::allocate(int32_t capacity) { ++capacity; // for the NUL // Switch to size_t which is unsigned so that we can allocate up to 4GB. // Reference counter + UChars. - size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR; + size_t numBytes = sizeof(int32_t) + static_cast(capacity) * U_SIZEOF_UCHAR; // Round up to a multiple of 16. numBytes = (numBytes + 15) & ~15; - int32_t *array = (int32_t *) uprv_malloc(numBytes); + int32_t* array = static_cast(uprv_malloc(numBytes)); if(array != nullptr) { // set initial refCount and point behind the refCount *array++ = 1; numBytes -= sizeof(int32_t); // have fArray point to the first char16_t - fUnion.fFields.fArray = (char16_t *)array; - fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR); + fUnion.fFields.fArray = reinterpret_cast(array); + fUnion.fFields.fCapacity = static_cast(numBytes / U_SIZEOF_UCHAR); fUnion.fFields.fLengthAndFlags = kLongString; return true; } @@ -622,7 +622,7 @@ void UnicodeString::swap(UnicodeString &other) noexcept { //======================================== UnicodeString UnicodeString::unescape() const { - UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity + UnicodeString result(length(), static_cast(0), static_cast(0)); // construct with capacity if (result.isBogus()) { return result; } @@ -772,9 +772,9 @@ UnicodeString::doCompare( int32_t start, # else // little-endian: compare char16_t units do { - result = ((int32_t)*(chars++) - (int32_t)*(srcChars++)); + result = static_cast(*(chars++)) - static_cast(*(srcChars++)); if(result != 0) { - return (int8_t)(result >> 15 | 1); + return static_cast(result >> 15 | 1); } } while(--minLength > 0); # endif @@ -806,7 +806,7 @@ UnicodeString::doCompareCodePointOrder(int32_t start, int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=nullptr)?(srcChars + srcStart):nullptr, srcLength, false, true); /* translate the 32-bit result into an 8-bit one */ if(diff!=0) { - return (int8_t)(diff >> 15 | 1); + return static_cast(diff >> 15 | 1); } else { return 0; } @@ -831,7 +831,7 @@ UChar32 UnicodeString::char32At(int32_t offset) const { int32_t len = length(); - if((uint32_t)offset < (uint32_t)len) { + if (static_cast(offset) < static_cast(len)) { const char16_t *array = getArrayStart(); UChar32 c; U16_GET(array, 0, offset, len, c); @@ -843,7 +843,7 @@ UnicodeString::char32At(int32_t offset) const int32_t UnicodeString::getChar32Start(int32_t offset) const { - if((uint32_t)offset < (uint32_t)length()) { + if (static_cast(offset) < static_cast(length())) { const char16_t *array = getArrayStart(); U16_SET_CP_START(array, 0, offset); return offset; @@ -855,7 +855,7 @@ UnicodeString::getChar32Start(int32_t offset) const { int32_t UnicodeString::getChar32Limit(int32_t offset) const { int32_t len = length(); - if((uint32_t)offset < (uint32_t)len) { + if (static_cast(offset) < static_cast(len)) { const char16_t *array = getArrayStart(); U16_SET_CP_LIMIT(array, 0, offset, len); return offset; @@ -989,7 +989,7 @@ UnicodeString::extract(int32_t start, int32_t len, if (/*dstSize < 0 || */(dstSize > 0 && target == nullptr)) { return 0; } - return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff); + return toUTF8(start, len, target, dstSize <= 0x7fffffff ? static_cast(dstSize) : 0x7fffffff); } // else see unistr_cnv.cpp @@ -1013,7 +1013,7 @@ UnicodeString::toUTF8(ByteSink &sink) const { int32_t length16 = length(); if(length16 != 0) { char stackBuffer[1024]; - int32_t capacity = (int32_t)sizeof(stackBuffer); + int32_t capacity = static_cast(sizeof(stackBuffer)); UBool utf8IsOwned = false; char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity, 3*length16, @@ -1027,7 +1027,7 @@ UnicodeString::toUTF8(ByteSink &sink) const { nullptr, // Don't care about number of substitutions. &errorCode); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { - utf8 = (char *)uprv_malloc(length8); + utf8 = static_cast(uprv_malloc(length8)); if(utf8 != nullptr) { utf8IsOwned = true; errorCode = U_ZERO_ERROR; @@ -1089,7 +1089,7 @@ UnicodeString::indexOf(const char16_t *srcChars, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1107,7 +1107,7 @@ UnicodeString::doIndexOf(char16_t c, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1124,7 +1124,7 @@ UnicodeString::doIndexOf(UChar32 c, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1153,7 +1153,7 @@ UnicodeString::lastIndexOf(const char16_t *srcChars, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1175,7 +1175,7 @@ UnicodeString::doLastIndexOf(char16_t c, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1192,7 +1192,7 @@ UnicodeString::doLastIndexOf(UChar32 c, if(match == nullptr) { return -1; } else { - return (int32_t)(match - array); + return static_cast(match - array); } } @@ -1329,7 +1329,7 @@ UnicodeString::setTo(UBool isTerminated, textLength = u_strlen(text); } fUnion.fFields.fLengthAndFlags = kReadonlyAlias; - setArray((char16_t *)text, textLength, isTerminated ? textLength + 1 : textLength); + setArray(const_cast(text), textLength, isTerminated ? textLength + 1 : textLength); return *this; } @@ -1359,7 +1359,7 @@ UnicodeString::setTo(char16_t *buffer, while(p != limit && *p != 0) { ++p; } - buffLength = (int32_t)(p - buffer); + buffLength = static_cast(p - buffer); } releaseArray(); @@ -1680,7 +1680,7 @@ UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) { if (limit <= start) { return; // Nothing to do; avoid bogus malloc call } - char16_t* text = (char16_t*) uprv_malloc( sizeof(char16_t) * (limit - start) ); + char16_t* text = static_cast(uprv_malloc(sizeof(char16_t) * (limit - start))); // Check to make sure text is not null. if (text != nullptr) { extractBetween(start, limit, text, 0); @@ -1725,13 +1725,13 @@ UnicodeString::doReverse(int32_t start, int32_t length) { // Before the loop we know left=2. do { - hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left); - hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right); + hasSupplementary |= static_cast(U16_IS_LEAD(swap = *left)); + hasSupplementary |= static_cast(U16_IS_LEAD(*left++ = *right)); *right-- = swap; } while(left < right); // Make sure to test the middle code unit of an odd-length string. // Redundant if the length is even. - hasSupplementary |= (UBool)U16_IS_LEAD(*left); + hasSupplementary |= static_cast(U16_IS_LEAD(*left)); /* if there are supplementary code points in the reversed range, then re-swap their surrogates */ if(hasSupplementary) { @@ -1834,7 +1834,7 @@ UnicodeString::releaseBuffer(int32_t newLength) { while(p(p - array); } else if(newLength>capacity) { newLength=capacity; } @@ -1928,7 +1928,7 @@ UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, // release the old array if(flags & kRefCounted) { // the array is refCounted; decrement and release if 0 - u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1); + u_atomic_int32_t* pRefCount = reinterpret_cast(oldArray) - 1; if(umtx_atomic_dec(pRefCount) == 0) { if (pBufferToDelete == nullptr) { // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t @@ -1937,7 +1937,7 @@ UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, uprv_free((void *)pRefCount); } else { // the caller requested to delete it himself - *pBufferToDelete = (int32_t *)pRefCount; + *pBufferToDelete = reinterpret_cast(pRefCount); } } } diff --git a/icu4c/source/common/unistr_case.cpp b/icu4c/source/common/unistr_case.cpp index b04d957bdcc9..40ea6b2f4d6e 100644 --- a/icu4c/source/common/unistr_case.cpp +++ b/icu4c/source/common/unistr_case.cpp @@ -72,7 +72,7 @@ UnicodeString::doCaseCompare(int32_t start, int32_t result=u_strcmpFold(chars, length, srcChars, srcLength, options|U_COMPARE_IGNORE_CASE, &errorCode); if(result!=0) { - return (int8_t)(result >> 24 | 1); + return static_cast(result >> 24 | 1); } } else { // get the srcLength if necessary @@ -80,7 +80,7 @@ UnicodeString::doCaseCompare(int32_t start, srcLength = u_strlen(srcChars + srcStart); } if(length != srcLength) { - return (int8_t)((length - srcLength) >> 24 | 1); + return static_cast((length - srcLength) >> 24 | 1); } } return 0; diff --git a/icu4c/source/common/unistr_cnv.cpp b/icu4c/source/common/unistr_cnv.cpp index e300a79ce517..bf52dd511884 100644 --- a/icu4c/source/common/unistr_cnv.cpp +++ b/icu4c/source/common/unistr_cnv.cpp @@ -63,7 +63,7 @@ UnicodeString::UnicodeString(const char *codepageData, const char *codepage) { fUnion.fFields.fLengthAndFlags = kShortString; if (codepageData != nullptr) { - doCodepageCreate(codepageData, (int32_t)uprv_strlen(codepageData), codepage); + doCodepageCreate(codepageData, static_cast(uprv_strlen(codepageData)), codepage); } } @@ -89,7 +89,7 @@ UnicodeString::UnicodeString(const char *src, int32_t srcLength, } else { // get input length if(srcLength==-1) { - srcLength=(int32_t)uprv_strlen(src); + srcLength = static_cast(uprv_strlen(src)); } if(srcLength>0) { if (cnv != nullptr) { @@ -151,13 +151,13 @@ UnicodeString::extract(int32_t start, int32_t capacity; if(dstSize < 0x7fffffff) { // Assume that the capacity is real and a limit pointer won't wrap around. - capacity = (int32_t)dstSize; + capacity = static_cast(dstSize); } else { // Pin the capacity so that a limit pointer does not wrap around. - char *targetLimit = (char *)U_MAX_PTR(target); + char* targetLimit = static_cast(U_MAX_PTR(target)); // U_MAX_PTR(target) returns a targetLimit that is at most 0x7fffffff // greater than target and does not wrap around the top of the address space. - capacity = (int32_t)(targetLimit - target); + capacity = static_cast(targetLimit - target); } // create the converter @@ -267,7 +267,7 @@ UnicodeString::doExtract(int32_t start, int32_t length, destLimit=dest=nullptr; } else if(destCapacity==-1) { // Pin the limit to U_MAX_PTR if the "magic" destCapacity is used. - destLimit=(char*)U_MAX_PTR(dest); + destLimit = static_cast(U_MAX_PTR(dest)); // for NUL-termination, translate into highest int32_t destCapacity=0x7fffffff; } else { @@ -276,7 +276,7 @@ UnicodeString::doExtract(int32_t start, int32_t length, // perform the conversion ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, nullptr, true, &errorCode); - length=(int32_t)(dest-originalDest); + length = static_cast(dest - originalDest); // if an overflow occurs, then get the preflighting length if(errorCode==U_BUFFER_OVERFLOW_ERROR) { @@ -287,7 +287,7 @@ UnicodeString::doExtract(int32_t start, int32_t length, dest=buffer; errorCode=U_ZERO_ERROR; ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, nullptr, true, &errorCode); - length+=(int32_t)(dest-buffer); + length += static_cast(dest - buffer); } while(errorCode==U_BUFFER_OVERFLOW_ERROR); } @@ -304,7 +304,7 @@ UnicodeString::doCodepageCreate(const char *codepageData, return; } if(dataLength == -1) { - dataLength = (int32_t)uprv_strlen(codepageData); + dataLength = static_cast(uprv_strlen(codepageData)); } UErrorCode status = U_ZERO_ERROR; @@ -393,7 +393,7 @@ UnicodeString::doCodepageCreate(const char *codepageData, &mySource, mySourceEnd, nullptr, true, &status); // update the conversion parameters - setLength((int32_t)(myTarget - array)); + setLength(static_cast(myTarget - array)); // allocate more space and copy data, if needed if(status == U_BUFFER_OVERFLOW_ERROR) { @@ -405,7 +405,7 @@ UnicodeString::doCodepageCreate(const char *codepageData, // estimate the new size needed, larger than before // try 2 char16_t's per remaining source byte - arraySize = (int32_t)(length() + 2 * (mySourceEnd - mySource)); + arraySize = static_cast(length() + 2 * (mySourceEnd - mySource)); } else { break; } diff --git a/icu4c/source/common/unormcmp.cpp b/icu4c/source/common/unormcmp.cpp index 028b28643c66..fa8b85cea047 100644 --- a/icu4c/source/common/unormcmp.cpp +++ b/icu4c/source/common/unormcmp.cpp @@ -313,7 +313,7 @@ unorm_cmpEquivFold(const char16_t *s1, int32_t length1, */ if( level1==0 && (options&U_COMPARE_IGNORE_CASE) && - (length=ucase_toFullFolding((UChar32)cp1, &p, options))>=0 + (length = ucase_toFullFolding(cp1, &p, options)) >= 0 ) { /* cp1 case-folds to the code point "length" or to p[length] */ if(U_IS_SURROGATE(c1)) { @@ -358,7 +358,7 @@ unorm_cmpEquivFold(const char16_t *s1, int32_t length1, } if( level2==0 && (options&U_COMPARE_IGNORE_CASE) && - (length=ucase_toFullFolding((UChar32)cp2, &p, options))>=0 + (length = ucase_toFullFolding(cp2, &p, options)) >= 0 ) { /* cp2 case-folds to the code point "length" or to p[length] */ if(U_IS_SURROGATE(c2)) { @@ -403,7 +403,7 @@ unorm_cmpEquivFold(const char16_t *s1, int32_t length1, } if( level1<2 && (options&_COMPARE_EQUIV) && - nullptr != (p = nfcImpl->getDecomposition((UChar32)cp1, decomp1, length)) + nullptr != (p = nfcImpl->getDecomposition(cp1, decomp1, length)) ) { /* cp1 decomposes into p[length] */ if(U_IS_SURROGATE(c1)) { @@ -444,7 +444,7 @@ unorm_cmpEquivFold(const char16_t *s1, int32_t length1, } if( level2<2 && (options&_COMPARE_EQUIV) && - nullptr != (p = nfcImpl->getDecomposition((UChar32)cp2, decomp2, length)) + nullptr != (p = nfcImpl->getDecomposition(cp2, decomp2, length)) ) { /* cp2 decomposes into p[length] */ if(U_IS_SURROGATE(c2)) { diff --git a/icu4c/source/common/uprops.cpp b/icu4c/source/common/uprops.cpp index b79eaff213d5..e68820fcdd8a 100644 --- a/icu4c/source/common/uprops.cpp +++ b/icu4c/source/common/uprops.cpp @@ -100,8 +100,8 @@ void U_CALLCONV ulayout_load(UErrorCode &errorCode) { ulayout_isAcceptable, nullptr, &errorCode); if (U_FAILURE(errorCode)) { return; } - const uint8_t *inBytes = (const uint8_t *)udata_getMemory(gLayoutMemory); - const int32_t *inIndexes = (const int32_t *)inBytes; + const uint8_t* inBytes = static_cast(udata_getMemory(gLayoutMemory)); + const int32_t* inIndexes = reinterpret_cast(inBytes); int32_t indexesLength = inIndexes[ULAYOUT_IX_INDEXES_LENGTH]; if (indexesLength < 12) { errorCode = U_INVALID_FORMAT_ERROR; // Not enough indexes. @@ -208,7 +208,7 @@ static UBool isNormInert(const BinaryProperty &, UChar32, UProperty) { static UBool isNormInert(const BinaryProperty &/*prop*/, UChar32 c, UProperty which) { UErrorCode errorCode=U_ZERO_ERROR; const Normalizer2 *norm2=Normalizer2Factory::getInstance( - (UNormalizationMode)(which-UCHAR_NFD_INERT+UNORM_NFD), errorCode); + static_cast(which - UCHAR_NFD_INERT + UNORM_NFD), errorCode); return U_SUCCESS(errorCode) && norm2->isInert(c); } #endif @@ -242,7 +242,7 @@ static UBool changesWhenCasefolded(const BinaryProperty &/*prop*/, UChar32 c, UP if(c>=0) { /* single code point */ const char16_t *resultString; - return (UBool)(ucase_toFullFolding(c, &resultString, U_FOLD_CASE_DEFAULT)>=0); + return static_cast(ucase_toFullFolding(c, &resultString, U_FOLD_CASE_DEFAULT) >= 0); } else { /* guess some large but stack-friendly capacity */ char16_t dest[2*UCASE_MAX_STRING_LENGTH]; @@ -250,7 +250,7 @@ static UBool changesWhenCasefolded(const BinaryProperty &/*prop*/, UChar32 c, UP destLength=u_strFoldCase(dest, UPRV_LENGTHOF(dest), nfd.getBuffer(), nfd.length(), U_FOLD_CASE_DEFAULT, &errorCode); - return (UBool)(U_SUCCESS(errorCode) && + return static_cast(U_SUCCESS(errorCode) && 0!=u_strCompare(nfd.getBuffer(), nfd.length(), dest, destLength, false)); } @@ -521,7 +521,7 @@ struct IntProperty { static int32_t defaultGetValue(const IntProperty &prop, UChar32 c, UProperty /*which*/) { /* systematic, directly stored properties */ - return (int32_t)(u_getUnicodeProperties(c, prop.column)&prop.mask)>>prop.shift; + return static_cast(u_getUnicodeProperties(c, prop.column) & prop.mask) >> prop.shift; } static int32_t defaultGetMaxValue(const IntProperty &prop, UProperty /*which*/) { @@ -533,11 +533,11 @@ static int32_t getMaxValueFromShift(const IntProperty &prop, UProperty /*which*/ } static int32_t getBiDiClass(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { - return (int32_t)u_charDirection(c); + return static_cast(u_charDirection(c)); } static int32_t getBiDiPairedBracketType(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { - return (int32_t)ubidi_getPairedBracketType(c); + return static_cast(ubidi_getPairedBracketType(c)); } static int32_t biDiGetMaxValue(const IntProperty &/*prop*/, UProperty which) { @@ -545,7 +545,7 @@ static int32_t biDiGetMaxValue(const IntProperty &/*prop*/, UProperty which) { } static int32_t getBlock(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { - return (int32_t)ublock_getCode(c); + return static_cast(ublock_getCode(c)); } static int32_t blockGetMaxValue(const IntProperty &/*prop*/, UProperty /*which*/) { @@ -563,7 +563,7 @@ static int32_t getCombiningClass(const IntProperty &/*prop*/, UChar32 c, UProper #endif static int32_t getGeneralCategory(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { - return (int32_t)u_charType(c); + return static_cast(u_charType(c)); } static int32_t getJoiningGroup(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { @@ -575,13 +575,13 @@ static int32_t getJoiningType(const IntProperty &/*prop*/, UChar32 c, UProperty } static int32_t getNumericType(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { - int32_t ntv=(int32_t)GET_NUMERIC_TYPE_VALUE(u_getMainProperties(c)); + int32_t ntv = static_cast(GET_NUMERIC_TYPE_VALUE(u_getMainProperties(c))); return UPROPS_NTV_GET_TYPE(ntv); } static int32_t getScript(const IntProperty &/*prop*/, UChar32 c, UProperty /*which*/) { UErrorCode errorCode=U_ZERO_ERROR; - return (int32_t)uscript_getScript(c, &errorCode); + return static_cast(uscript_getScript(c, &errorCode)); } static int32_t scriptGetMaxValue(const IntProperty &/*prop*/, UProperty /*which*/) { @@ -620,7 +620,7 @@ static int32_t getHangulSyllableType(const IntProperty &/*prop*/, UChar32 c, UPr return U_HST_NOT_APPLICABLE; } /* see comments on gcbToHst[] above */ - int32_t gcb=(int32_t)(u_getUnicodeProperties(c, 2)&UPROPS_GCB_MASK)>>UPROPS_GCB_SHIFT; + int32_t gcb = static_cast(u_getUnicodeProperties(c, 2) & UPROPS_GCB_MASK) >> UPROPS_GCB_SHIFT; if(gcb(unorm_getQuickCheck(c, static_cast(which - UCHAR_NFD_QUICK_CHECK + UNORM_NFD))); } #endif @@ -703,21 +703,21 @@ static const IntProperty intProps[UCHAR_INT_LIMIT-UCHAR_INT_START]={ { UPROPS_SRC_NFC, 0, 0xff, getCombiningClass, getMaxValueFromShift }, { 2, UPROPS_DT_MASK, 0, defaultGetValue, defaultGetMaxValue }, { 0, UPROPS_EA_MASK, UPROPS_EA_SHIFT, defaultGetValue, defaultGetMaxValue }, - { UPROPS_SRC_CHAR, 0, (int32_t)U_CHAR_CATEGORY_COUNT-1,getGeneralCategory, getMaxValueFromShift }, + { UPROPS_SRC_CHAR, 0, static_cast(U_CHAR_CATEGORY_COUNT) - 1, getGeneralCategory, getMaxValueFromShift }, { UPROPS_SRC_BIDI, 0, 0, getJoiningGroup, biDiGetMaxValue }, { UPROPS_SRC_BIDI, 0, 0, getJoiningType, biDiGetMaxValue }, { 2, UPROPS_LB_MASK, UPROPS_LB_SHIFT, defaultGetValue, defaultGetMaxValue }, - { UPROPS_SRC_CHAR, 0, (int32_t)U_NT_COUNT-1, getNumericType, getMaxValueFromShift }, + { UPROPS_SRC_CHAR, 0, static_cast(U_NT_COUNT) - 1, getNumericType, getMaxValueFromShift }, { UPROPS_SRC_PROPSVEC, 0, 0, getScript, scriptGetMaxValue }, - { UPROPS_SRC_PROPSVEC, 0, (int32_t)U_HST_COUNT-1, getHangulSyllableType, getMaxValueFromShift }, + { UPROPS_SRC_PROPSVEC, 0, static_cast(U_HST_COUNT) - 1, getHangulSyllableType, getMaxValueFromShift }, // UCHAR_NFD_QUICK_CHECK: max=1=YES -- never "maybe", only "no" or "yes" - { UPROPS_SRC_NFC, 0, (int32_t)UNORM_YES, getNormQuickCheck, getMaxValueFromShift }, + { UPROPS_SRC_NFC, 0, static_cast(UNORM_YES), getNormQuickCheck, getMaxValueFromShift }, // UCHAR_NFKD_QUICK_CHECK: max=1=YES -- never "maybe", only "no" or "yes" - { UPROPS_SRC_NFKC, 0, (int32_t)UNORM_YES, getNormQuickCheck, getMaxValueFromShift }, + { UPROPS_SRC_NFKC, 0, static_cast(UNORM_YES), getNormQuickCheck, getMaxValueFromShift }, // UCHAR_NFC_QUICK_CHECK: max=2=MAYBE - { UPROPS_SRC_NFC, 0, (int32_t)UNORM_MAYBE, getNormQuickCheck, getMaxValueFromShift }, + { UPROPS_SRC_NFC, 0, static_cast(UNORM_MAYBE), getNormQuickCheck, getMaxValueFromShift }, // UCHAR_NFKC_QUICK_CHECK: max=2=MAYBE - { UPROPS_SRC_NFKC, 0, (int32_t)UNORM_MAYBE, getNormQuickCheck, getMaxValueFromShift }, + { UPROPS_SRC_NFKC, 0, static_cast(UNORM_MAYBE), getNormQuickCheck, getMaxValueFromShift }, { UPROPS_SRC_NFC, 0, 0xff, getLeadCombiningClass, getMaxValueFromShift }, { UPROPS_SRC_NFC, 0, 0xff, getTrailCombiningClass, getMaxValueFromShift }, { 2, UPROPS_GCB_MASK, UPROPS_GCB_SHIFT, defaultGetValue, defaultGetMaxValue }, @@ -727,7 +727,7 @@ static const IntProperty intProps[UCHAR_INT_LIMIT-UCHAR_INT_START]={ { UPROPS_SRC_INPC, 0, 0, getInPC, layoutGetMaxValue }, { UPROPS_SRC_INSC, 0, 0, getInSC, layoutGetMaxValue }, { UPROPS_SRC_VO, 0, 0, getVo, layoutGetMaxValue }, - { UPROPS_SRC_PROPSVEC, 0, (int32_t)U_ID_STATUS_ALLOWED, getIDStatusValue, getMaxValueFromShift }, + { UPROPS_SRC_PROPSVEC, 0, static_cast(U_ID_STATUS_ALLOWED), getIDStatusValue, getMaxValueFromShift }, }; U_CAPI int32_t U_EXPORT2 diff --git a/icu4c/source/common/uresbund.cpp b/icu4c/source/common/uresbund.cpp index ea4327b31489..59b08688319c 100644 --- a/icu4c/source/common/uresbund.cpp +++ b/icu4c/source/common/uresbund.cpp @@ -56,7 +56,7 @@ static UMutex resbMutex; /* INTERNAL: hashes an entry */ static int32_t U_CALLCONV hashEntry(const UHashTok parm) { - UResourceDataEntry *b = (UResourceDataEntry *)parm.pointer; + UResourceDataEntry* b = static_cast(parm.pointer); UHashTok namekey, pathkey; namekey.pointer = b->fName; pathkey.pointer = b->fPath; @@ -65,14 +65,14 @@ static int32_t U_CALLCONV hashEntry(const UHashTok parm) { /* INTERNAL: compares two entries */ static UBool U_CALLCONV compareEntries(const UHashTok p1, const UHashTok p2) { - UResourceDataEntry *b1 = (UResourceDataEntry *)p1.pointer; - UResourceDataEntry *b2 = (UResourceDataEntry *)p2.pointer; + UResourceDataEntry* b1 = static_cast(p1.pointer); + UResourceDataEntry* b2 = static_cast(p2.pointer); UHashTok name1, name2, path1, path2; name1.pointer = b1->fName; name2.pointer = b2->fName; path1.pointer = b1->fPath; path2.pointer = b2->fPath; - return (UBool)(uhash_compareChars(name1, name2) && + return static_cast(uhash_compareChars(name1, name2) && uhash_compareChars(path1, path2)); } @@ -403,7 +403,7 @@ static int32_t ures_flushCache() pos = UHASH_FIRST; while ((e = uhash_nextElement(cache, &pos)) != nullptr) { - resB = (UResourceDataEntry *) e->value.pointer; + resB = static_cast(e->value.pointer); /* Deletes only if reference counter == 0 * Don't worry about the children of this node. * Those will eventually get deleted too, if not already. @@ -488,15 +488,15 @@ static void initCache(UErrorCode *status) { /** INTERNAL: sets the name (locale) of the resource bundle to given name */ static void setEntryName(UResourceDataEntry *res, const char *name, UErrorCode *status) { - int32_t len = (int32_t)uprv_strlen(name); + int32_t len = static_cast(uprv_strlen(name)); if(res->fName != nullptr && res->fName != res->fNameBuffer) { uprv_free(res->fName); } - if (len < (int32_t)sizeof(res->fNameBuffer)) { + if (len < static_cast(sizeof(res->fNameBuffer))) { res->fName = res->fNameBuffer; } else { - res->fName = (char *)uprv_malloc(len+1); + res->fName = static_cast(uprv_malloc(len + 1)); } if(res->fName == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; @@ -535,18 +535,18 @@ static UResourceDataEntry *init_entry(const char *localeID, const char *path, UE name = localeID; } - find.fName = (char *)name; - find.fPath = (char *)path; + find.fName = const_cast(name); + find.fPath = const_cast(path); /* calculate the hash value of the entry */ /*hashkey.pointer = (void *)&find;*/ /*hashValue = hashEntry(hashkey);*/ /* check to see if we already have this entry */ - r = (UResourceDataEntry *)uhash_get(cache, &find); + r = static_cast(uhash_get(cache, &find)); if(r == nullptr) { /* if the entry is not yet in the hash table, we'll try to construct a new one */ - r = (UResourceDataEntry *) uprv_malloc(sizeof(UResourceDataEntry)); + r = static_cast(uprv_malloc(sizeof(UResourceDataEntry))); if(r == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -562,7 +562,7 @@ static UResourceDataEntry *init_entry(const char *localeID, const char *path, UE } if(path != nullptr) { - r->fPath = (char *)uprv_strdup(path); + r->fPath = uprv_strdup(path); if(r->fPath == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; uprv_free(r); @@ -589,7 +589,7 @@ static UResourceDataEntry *init_entry(const char *localeID, const char *path, UE if (U_SUCCESS(*status)) { const int32_t *poolIndexes = r->fPool->fData.pRoot + 1; if(r->fData.pRoot[1 + URES_INDEX_POOL_CHECKSUM] == poolIndexes[URES_INDEX_POOL_CHECKSUM]) { - r->fData.poolBundleKeys = (const char *)(poolIndexes + (poolIndexes[URES_INDEX_LENGTH] & 0xff)); + r->fData.poolBundleKeys = reinterpret_cast(poolIndexes + (poolIndexes[URES_INDEX_LENGTH] & 0xff)); r->fData.poolBundleStrings = r->fPool->fData.p16BitUnits; } else { r->fBogus = *status = U_INVALID_FORMAT_ERROR; @@ -615,7 +615,7 @@ static UResourceDataEntry *init_entry(const char *localeID, const char *path, UE { UResourceDataEntry *oldR = nullptr; - if((oldR = (UResourceDataEntry *)uhash_get(cache, r)) == nullptr) { /* if the data is not cached */ + if ((oldR = static_cast(uhash_get(cache, r))) == nullptr) { /* if the data is not cached */ /* just insert it in the cache */ UErrorCode cacheStatus = U_ZERO_ERROR; uhash_put(cache, (void *)r, r, &cacheStatus); @@ -676,8 +676,8 @@ findFirstExisting(const char* path, char* name, const char* defaultLocale, UResO if (U_FAILURE(*status)) { return nullptr; } - *isDefault = (UBool)(uprv_strncmp(name, defaultLocale, uprv_strlen(name)) == 0); - hasRealData = (UBool)(r->fBogus == U_ZERO_ERROR); + *isDefault = static_cast(uprv_strncmp(name, defaultLocale, uprv_strlen(name)) == 0); + hasRealData = static_cast(r->fBogus == U_ZERO_ERROR); if(!hasRealData) { /* this entry is not real. We will discard it. */ /* However, the parent line for this entry is */ @@ -692,7 +692,7 @@ findFirstExisting(const char* path, char* name, const char* defaultLocale, UResO uprv_strcpy(name, r->fName); /* this is needed for supporting aliases */ } - *isRoot = (UBool)(uprv_strcmp(name, kRootLocaleName) == 0); + *isRoot = static_cast(uprv_strcmp(name, kRootLocaleName) == 0); /*Fallback data stuff*/ if (!hasRealData) { @@ -1091,7 +1091,7 @@ static void ures_appendResPath(UResourceBundle *resB, const char* toAdd, int32_t resB->fResPathLen += lenToAdd; if(RES_BUFSIZE <= resB->fResPathLen+1) { if(resB->fResPath == resB->fResBuf) { - resB->fResPath = (char *)uprv_malloc((resB->fResPathLen+1)*sizeof(char)); + resB->fResPath = static_cast(uprv_malloc((resB->fResPathLen + 1) * sizeof(char))); /* Check that memory was allocated correctly. */ if (resB->fResPath == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; @@ -1099,7 +1099,7 @@ static void ures_appendResPath(UResourceBundle *resB, const char* toAdd, int32_t } uprv_strcpy(resB->fResPath, resB->fResBuf); } else { - char *temp = (char *)uprv_realloc(resB->fResPath, (resB->fResPathLen+1)*sizeof(char)); + char* temp = static_cast(uprv_realloc(resB->fResPath, (resB->fResPathLen + 1) * sizeof(char))); /* Check that memory was reallocated correctly. */ if (temp == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; @@ -1348,7 +1348,7 @@ UResourceBundle *getAliasTargetAsResourceBundle( // if the key path wasn't just a single resource ID, clear out // the bundle's key path and re-set it to be equal to keyPath. ures_freeResPath(resB); - ures_appendResPath(resB, keyPath, (int32_t)uprv_strlen(keyPath), status); + ures_appendResPath(resB, keyPath, static_cast(uprv_strlen(keyPath)), status); if(resB->fResPath[resB->fResPathLen-1] != RES_PATH_SEPARATOR) { ures_appendResPath(resB, RES_PATH_SEPARATOR_S, 1, status); } @@ -1407,7 +1407,7 @@ UResourceBundle *init_resb_result( validLocaleDataEntry, containerResPath, recursionDepth, resB, status); } if(resB == nullptr) { - resB = (UResourceBundle *)uprv_malloc(sizeof(UResourceBundle)); + resB = static_cast(uprv_malloc(sizeof(UResourceBundle))); if (resB == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -1449,7 +1449,7 @@ UResourceBundle *init_resb_result( resB, containerResPath, static_cast(uprv_strlen(containerResPath)), status); } if(key != nullptr) { - ures_appendResPath(resB, key, (int32_t)uprv_strlen(key), status); + ures_appendResPath(resB, key, static_cast(uprv_strlen(key)), status); if(resB->fResPath[resB->fResPathLen-1] != RES_PATH_SEPARATOR) { ures_appendResPath(resB, RES_PATH_SEPARATOR_S, 1, status); } @@ -1494,7 +1494,7 @@ UResourceBundle *ures_copyResb(UResourceBundle *r, const UResourceBundle *origin if(original != nullptr) { if(r == nullptr) { isStackObject = false; - r = (UResourceBundle *)uprv_malloc(sizeof(UResourceBundle)); + r = static_cast(uprv_malloc(sizeof(UResourceBundle))); /* test for nullptr */ if (r == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; @@ -2064,7 +2064,7 @@ static Resource getTableItemByKeyPath(const ResourceData *pResData, Resource tab path.append(key, errorCode); if (U_FAILURE(errorCode)) { return RES_BOGUS; } char *pathPart = path.data(); /* Path from current resource to desired resource */ - UResType type = (UResType)RES_GET_TYPE(resource); /* the current resource type */ + UResType type = static_cast(RES_GET_TYPE(resource)); /* the current resource type */ while (*pathPart && resource != RES_BOGUS && URES_IS_CONTAINER(type)) { char *nextPathPart = uprv_strchr(pathPart, RES_PATH_SEPARATOR); if (nextPathPart != nullptr) { @@ -2076,7 +2076,7 @@ static Resource getTableItemByKeyPath(const ResourceData *pResData, Resource tab int32_t t; const char *pathP = pathPart; resource = res_getTableItemByKey(pResData, resource, &t, &pathP); - type = (UResType)RES_GET_TYPE(resource); + type = static_cast(RES_GET_TYPE(resource)); pathPart = nextPathPart; } if (*pathPart) { @@ -2737,7 +2737,7 @@ ures_openWithType(UResourceBundle *r, const char* path, const char* localeID, UBool isStackObject; if(r == nullptr) { - r = (UResourceBundle *)uprv_malloc(sizeof(UResourceBundle)); + r = static_cast(uprv_malloc(sizeof(UResourceBundle))); if(r == nullptr) { entryClose(entry); *status = U_MEMORY_ALLOCATION_ERROR; @@ -2924,7 +2924,7 @@ typedef struct ULocalesContext { static void U_CALLCONV ures_loc_closeLocales(UEnumeration *enumerator) { - ULocalesContext *ctx = (ULocalesContext *)enumerator->context; + ULocalesContext* ctx = static_cast(enumerator->context); ures_close(&ctx->curr); ures_close(&ctx->installed); uprv_free(ctx); @@ -2933,7 +2933,7 @@ ures_loc_closeLocales(UEnumeration *enumerator) { static int32_t U_CALLCONV ures_loc_countLocales(UEnumeration *en, UErrorCode * /*status*/) { - ULocalesContext *ctx = (ULocalesContext *)en->context; + ULocalesContext* ctx = static_cast(en->context); return ures_getSize(&ctx->installed); } diff --git a/icu4c/source/common/uresdata.cpp b/icu4c/source/common/uresdata.cpp index c716dd9b0f0c..a6b540a22571 100644 --- a/icu4c/source/common/uresdata.cpp +++ b/icu4c/source/common/uresdata.cpp @@ -140,7 +140,7 @@ isAcceptable(void *context, const char * /*type*/, const char * /*name*/, const UDataInfo *pInfo) { uprv_memcpy(context, pInfo->formatVersion, 4); - return (UBool)( + return static_cast( pInfo->size>=20 && pInfo->isBigEndian==U_IS_BIG_ENDIAN && pInfo->charsetFamily==U_CHARSET_FAMILY && @@ -161,8 +161,8 @@ res_init(ResourceData *pResData, UResType rootType; /* get the root resource */ - pResData->pRoot=(const int32_t *)inBytes; - pResData->rootRes=(Resource)*pResData->pRoot; + pResData->pRoot = static_cast(inBytes); + pResData->rootRes = static_cast(*pResData->pRoot); pResData->p16BitUnits=&gEmpty16; /* formatVersion 1.1 must have a root item and at least 5 indexes */ @@ -173,7 +173,7 @@ res_init(ResourceData *pResData, } /* currently, we accept only resources that have a Table as their roots */ - rootType=(UResType)RES_GET_TYPE(pResData->rootRes); + rootType = static_cast(RES_GET_TYPE(pResData->rootRes)); if(!URES_IS_TABLE(rootType)) { *errorCode=U_INVALID_FORMAT_ERROR; res_unload(pResData); @@ -207,15 +207,15 @@ res_init(ResourceData *pResData, // In version 2, bits 31..8 were reserved and always 0. // In version 3, they contain bits 23..0 of the poolStringIndexLimit. // Bits 27..24 are in indexes[URES_INDEX_ATTRIBUTES] bits 15..12. - pResData->poolStringIndexLimit=(int32_t)((uint32_t)indexes[URES_INDEX_LENGTH]>>8); + pResData->poolStringIndexLimit = static_cast(static_cast(indexes[URES_INDEX_LENGTH]) >> 8); } if(indexLength>URES_INDEX_ATTRIBUTES) { int32_t att=indexes[URES_INDEX_ATTRIBUTES]; - pResData->noFallback=(UBool)(att&URES_ATT_NO_FALLBACK); - pResData->isPoolBundle=(UBool)((att&URES_ATT_IS_POOL_BUNDLE)!=0); - pResData->usesPoolBundle=(UBool)((att&URES_ATT_USES_POOL_BUNDLE)!=0); + pResData->noFallback = static_cast(att & URES_ATT_NO_FALLBACK); + pResData->isPoolBundle = static_cast((att & URES_ATT_IS_POOL_BUNDLE) != 0); + pResData->usesPoolBundle = static_cast((att & URES_ATT_USES_POOL_BUNDLE) != 0); pResData->poolStringIndexLimit|=(att&0xf000)<<12; // bits 15..12 -> 27..24 - pResData->poolStringIndex16Limit=(int32_t)((uint32_t)att>>16); + pResData->poolStringIndex16Limit = static_cast(static_cast(att) >> 16); } if((pResData->isPoolBundle || pResData->usesPoolBundle) && indexLength<=URES_INDEX_POOL_CHECKSUM) { *errorCode=U_INVALID_FORMAT_ERROR; @@ -225,7 +225,7 @@ res_init(ResourceData *pResData, if( indexLength>URES_INDEX_16BIT_TOP && indexes[URES_INDEX_16BIT_TOP]>indexes[URES_INDEX_KEYS_TOP] ) { - pResData->p16BitUnits=(const uint16_t *)(pResData->pRoot+indexes[URES_INDEX_KEYS_TOP]); + pResData->p16BitUnits = reinterpret_cast(pResData->pRoot + indexes[URES_INDEX_KEYS_TOP]); } } @@ -361,14 +361,14 @@ UBool isNoInheritanceMarker(const ResourceData *pResData, Resource res) { } else if (res == offset) { const int32_t *p32=pResData->pRoot+res; int32_t length=*p32; - const char16_t *p=(const char16_t *)p32; + const char16_t* p = reinterpret_cast(p32); return length == 3 && p[2] == 0x2205 && p[3] == 0x2205 && p[4] == 0x2205; } else if (RES_GET_TYPE(res) == URES_STRING_V2) { const char16_t *p; - if((int32_t)offsetpoolStringIndexLimit) { - p=(const char16_t *)pResData->poolBundleStrings+offset; + if (static_cast(offset) < pResData->poolStringIndexLimit) { + p = reinterpret_cast(pResData->poolBundleStrings) + offset; } else { - p=(const char16_t *)pResData->p16BitUnits+(offset-pResData->poolStringIndexLimit); + p = reinterpret_cast(pResData->p16BitUnits) + (offset - pResData->poolStringIndexLimit); } int32_t first=*p; if (first == 0x2205) { // implicit length @@ -580,7 +580,7 @@ ResourceArray ResourceDataValue::getArray(UErrorCode &errorCode) const { switch(RES_GET_TYPE(res)) { case URES_ARRAY: if (offset!=0) { // empty if offset==0 - items32 = (const Resource *)getData().pRoot+offset; + items32 = reinterpret_cast(getData().pRoot) + offset; length = *items32++; } break; @@ -608,9 +608,9 @@ ResourceTable ResourceDataValue::getTable(UErrorCode &errorCode) const { switch(RES_GET_TYPE(res)) { case URES_TABLE: if (offset != 0) { // empty if offset==0 - keys16 = (const uint16_t *)(getData().pRoot+offset); + keys16 = reinterpret_cast(getData().pRoot + offset); length = *keys16++; - items32 = (const Resource *)(keys16+length+(~length&1)); + items32 = reinterpret_cast(keys16 + length + (~length & 1)); } break; case URES_TABLE16: @@ -622,7 +622,7 @@ ResourceTable ResourceDataValue::getTable(UErrorCode &errorCode) const { if (offset != 0) { // empty if offset==0 keys32 = getData().pRoot+offset; length = *keys32++; - items32 = (const Resource *)keys32 + length; + items32 = reinterpret_cast(keys32) + length; } break; default: @@ -1019,9 +1019,9 @@ typedef struct Row { static int32_t U_CALLCONV ures_compareRows(const void *context, const void *left, const void *right) { - const char *keyChars=(const char *)context; - return (int32_t)uprv_strcmp(keyChars+((const Row *)left)->keyIndex, - keyChars+((const Row *)right)->keyIndex); + const char* keyChars = static_cast(context); + return static_cast(uprv_strcmp(keyChars + static_cast(left)->keyIndex, + keyChars + static_cast(right)->keyIndex)); } typedef struct TempTable { @@ -1074,17 +1074,17 @@ ures_swapResource(const UDataSwapper *ds, } /* all other types use an offset to point to their data */ - offset=(int32_t)RES_GET_OFFSET(res); + offset = static_cast(RES_GET_OFFSET(res)); if(offset==0) { /* special offset indicating an empty item */ return; } - if(pTempTable->resFlags[offset>>5]&((uint32_t)1<<(offset&0x1f))) { + if (pTempTable->resFlags[offset >> 5] & (static_cast(1) << (offset & 0x1f))) { /* we already swapped this resource item */ return; } else { /* mark it as swapped now */ - pTempTable->resFlags[offset>>5]|=((uint32_t)1<<(offset&0x1f)); + pTempTable->resFlags[offset >> 5] |= static_cast(1) << (offset & 0x1f); } p=inBundle+offset; @@ -1095,14 +1095,14 @@ ures_swapResource(const UDataSwapper *ds, /* physically same value layout as string, fall through */ U_FALLTHROUGH; case URES_STRING: - count=udata_readInt32(ds, (int32_t)*p); + count = udata_readInt32(ds, static_cast(*p)); /* swap length */ ds->swapArray32(ds, p, 4, q, pErrorCode); /* swap each char16_t (the terminating NUL would not change) */ ds->swapArray16(ds, p+1, 2*count, q+1, pErrorCode); break; case URES_BINARY: - count=udata_readInt32(ds, (int32_t)*p); + count = udata_readInt32(ds, static_cast(*p)); /* swap length */ ds->swapArray32(ds, p, 4, q, pErrorCode); /* no need to swap or copy bytes - ures_swap() copied them all */ @@ -1135,8 +1135,8 @@ ures_swapResource(const UDataSwapper *ds, if(RES_GET_TYPE(res)==URES_TABLE) { /* get table item count */ - pKey16=(const uint16_t *)p; - qKey16=(uint16_t *)q; + pKey16 = reinterpret_cast(p); + qKey16 = reinterpret_cast(q); count=ds->readUInt16(*pKey16); pKey32=qKey32=nullptr; @@ -1147,8 +1147,8 @@ ures_swapResource(const UDataSwapper *ds, offset+=((1+count)+1)/2; } else { /* get table item count */ - pKey32=(const int32_t *)p; - qKey32=(int32_t *)q; + pKey32 = reinterpret_cast(p); + qKey32 = reinterpret_cast(q); count=udata_readInt32(ds, *pKey32); pKey16=qKey16=nullptr; @@ -1172,12 +1172,12 @@ ures_swapResource(const UDataSwapper *ds, if(pKey16!=nullptr) { int32_t keyOffset=ds->readUInt16(pKey16[i]); if(keyOffsetlocalKeyLimit) { - itemKey=(const char *)outBundle+keyOffset; + itemKey = reinterpret_cast(outBundle) + keyOffset; } } else { int32_t keyOffset=udata_readInt32(ds, pKey32[i]); if(keyOffset>=0) { - itemKey=(const char *)outBundle+keyOffset; + itemKey = reinterpret_cast(outBundle) + keyOffset; } } item=ds->readUInt32(p[i]); @@ -1243,7 +1243,7 @@ ures_swapResource(const UDataSwapper *ds, if(pKey16!=qKey16) { rKey16=qKey16; } else { - rKey16=(uint16_t *)pTempTable->resort; + rKey16 = reinterpret_cast(pTempTable->resort); } for(i=0; irows[i].sortIndex; @@ -1277,7 +1277,7 @@ ures_swapResource(const UDataSwapper *ds, if(p!=q) { r=q; } else { - r=(Resource *)pTempTable->resort; + r = reinterpret_cast(pTempTable->resort); } for(i=0; irows[i].sortIndex; @@ -1294,7 +1294,7 @@ ures_swapResource(const UDataSwapper *ds, Resource item; int32_t i; - count=udata_readInt32(ds, (int32_t)*p); + count = udata_readInt32(ds, static_cast(*p)); /* swap length */ ds->swapArray32(ds, p++, 4, q++, pErrorCode); @@ -1314,7 +1314,7 @@ ures_swapResource(const UDataSwapper *ds, } break; case URES_INT_VECTOR: - count=udata_readInt32(ds, (int32_t)*p); + count = udata_readInt32(ds, static_cast(*p)); /* swap length and each integer */ ds->swapArray32(ds, p, 4*(1+count), q, pErrorCode); break; diff --git a/icu4c/source/common/uscript.cpp b/icu4c/source/common/uscript.cpp index 2e9012a982cd..c48a28fd1434 100644 --- a/icu4c/source/common/uscript.cpp +++ b/icu4c/source/common/uscript.cpp @@ -74,7 +74,7 @@ getCodesFromLocale(const char *locale, } // Explicit script code. if (!script.isEmpty()) { - UScriptCode scriptCode = (UScriptCode)u_getPropertyValueEnum(UCHAR_SCRIPT, script.data()); + UScriptCode scriptCode = static_cast(u_getPropertyValueEnum(UCHAR_SCRIPT, script.data())); if(scriptCode != USCRIPT_INVALID_CODE) { if(scriptCode == USCRIPT_SIMPLIFIED_HAN || scriptCode == USCRIPT_TRADITIONAL_HAN) { scriptCode = USCRIPT_HAN; diff --git a/icu4c/source/common/usetiter.cpp b/icu4c/source/common/usetiter.cpp index d24a15ab2df0..703f9d63db63 100644 --- a/icu4c/source/common/usetiter.cpp +++ b/icu4c/source/common/usetiter.cpp @@ -60,8 +60,8 @@ UBool UnicodeSetIterator::next() { } if (nextString >= stringCount) return false; - codepoint = (UChar32)IS_STRING; // signal that value is actually a string - string = (const UnicodeString*) set->strings->elementAt(nextString++); + codepoint = static_cast(IS_STRING); // signal that value is actually a string + string = static_cast(set->strings->elementAt(nextString++)); return true; } @@ -93,8 +93,8 @@ UBool UnicodeSetIterator::nextRange() { } if (nextString >= stringCount) return false; - codepoint = (UChar32)IS_STRING; // signal that value is actually a string - string = (const UnicodeString*) set->strings->elementAt(nextString++); + codepoint = static_cast(IS_STRING); // signal that value is actually a string + string = static_cast(set->strings->elementAt(nextString++)); return true; } @@ -135,12 +135,12 @@ void UnicodeSetIterator::loadRange(int32_t iRange) { const UnicodeString& UnicodeSetIterator::getString() { - if (string==nullptr && codepoint!=(UChar32)IS_STRING) { + if (string == nullptr && codepoint != static_cast(IS_STRING)) { if (cpString == nullptr) { cpString = new UnicodeString(); } if (cpString != nullptr) { - cpString->setTo((UChar32)codepoint); + cpString->setTo(codepoint); } string = cpString; } diff --git a/icu4c/source/common/ushape.cpp b/icu4c/source/common/ushape.cpp index d0ac95e0b234..0843889d2dd4 100644 --- a/icu4c/source/common/ushape.cpp +++ b/icu4c/source/common/ushape.cpp @@ -360,8 +360,8 @@ _shapeToArabicDigitsWithContext(char16_t *s, int32_t length, lastStrongWasAL=true; break; case U_EUROPEAN_NUMBER: /* EN */ - if(lastStrongWasAL && (uint32_t)(c-0x30)<10) { - s[i]=(char16_t)(digitBase+c); /* digitBase+(c-0x30) - digitBase was modified above */ + if (lastStrongWasAL && static_cast(c - 0x30) < 10) { + s[i] = static_cast(digitBase + c); /* digitBase+(c-0x30) - digitBase was modified above */ } break; default : @@ -380,8 +380,8 @@ _shapeToArabicDigitsWithContext(char16_t *s, int32_t length, lastStrongWasAL=true; break; case U_EUROPEAN_NUMBER: /* EN */ - if(lastStrongWasAL && (uint32_t)(c-0x30)<10) { - s[i]=(char16_t)(digitBase+c); /* digitBase+(c-0x30) - digitBase was modified above */ + if (lastStrongWasAL && static_cast(c - 0x30) < 10) { + s[i] = static_cast(digitBase + c); /* digitBase+(c-0x30) - digitBase was modified above */ } break; default : @@ -483,7 +483,7 @@ countSpaces(char16_t *dest, int32_t size, uint32_t /*options*/, int32_t *spacesC */ static inline int32_t isTashkeelChar(char16_t ch) { - return (int32_t)( ch>=0x064B && ch<= 0x0652 ); + return static_cast(ch >= 0x064B && ch <= 0x0652); } /* @@ -492,7 +492,7 @@ isTashkeelChar(char16_t ch) { */ static inline int32_t isTashkeelCharFE(char16_t ch) { - return (int32_t)( ch>=0xFE70 && ch<= 0xFE7F ); + return static_cast(ch >= 0xFE70 && ch <= 0xFE7F); } /* @@ -501,7 +501,7 @@ isTashkeelCharFE(char16_t ch) { */ static inline int32_t isAlefChar(char16_t ch) { - return (int32_t)( (ch==0x0622)||(ch==0x0623)||(ch==0x0625)||(ch==0x0627) ); + return static_cast(ch == 0x0622 || ch == 0x0623 || ch == 0x0625 || ch == 0x0627); } /* @@ -510,7 +510,7 @@ isAlefChar(char16_t ch) { */ static inline int32_t isLamAlefChar(char16_t ch) { - return (int32_t)((ch>=0xFEF5)&&(ch<=0xFEFC) ); + return static_cast(ch >= 0xFEF5 && ch <= 0xFEFC); } /*BIDI @@ -564,7 +564,7 @@ isSeenFamilyChar(char16_t ch){ */ static inline int32_t isAlefMaksouraChar(char16_t ch) { - return (int32_t)( (ch == 0xFEEF) || ( ch == 0xFEF0) || (ch == 0x0649)); + return static_cast(ch == 0xFEEF || ch == 0xFEF0 || ch == 0x0649); } /* @@ -747,7 +747,7 @@ handleGeneratedSpaces(char16_t *dest, int32_t sourceLength, } } - tempbuffer = (char16_t *)uprv_malloc((sourceLength+1)*U_SIZEOF_UCHAR); + tempbuffer = static_cast(uprv_malloc((sourceLength + 1) * U_SIZEOF_UCHAR)); /* Test for nullptr */ if(tempbuffer == nullptr) { *pErrorCode = U_MEMORY_ALLOCATION_ERROR; @@ -905,7 +905,7 @@ expandCompositCharAtBegin(char16_t *dest, int32_t sourceLength, int32_t destSize int32_t countl = 0; char16_t *tempbuffer=nullptr; - tempbuffer = (char16_t *)uprv_malloc((sourceLength+1)*U_SIZEOF_UCHAR); + tempbuffer = static_cast(uprv_malloc((sourceLength + 1) * U_SIZEOF_UCHAR)); /* Test for nullptr */ if(tempbuffer == nullptr) { @@ -967,7 +967,7 @@ expandCompositCharAtEnd(char16_t *dest, int32_t sourceLength, int32_t destSize,U int32_t inpsize = sourceLength; char16_t *tempbuffer=nullptr; - tempbuffer = (char16_t *)uprv_malloc((sourceLength+1)*U_SIZEOF_UCHAR); + tempbuffer = static_cast(uprv_malloc((sourceLength + 1) * U_SIZEOF_UCHAR)); /* Test for nullptr */ if(tempbuffer == nullptr) { @@ -1154,7 +1154,7 @@ expandCompositChar(char16_t *dest, int32_t sourceLength, if (shapingMode == 1){ if ( (options&U_SHAPE_LAMALEF_MASK) == U_SHAPE_LAMALEF_RESIZE){ destSize = calculateSize(dest,sourceLength,destSize,options); - tempbuffer = (char16_t *)uprv_malloc((destSize+1)*U_SIZEOF_UCHAR); + tempbuffer = static_cast(uprv_malloc((destSize + 1) * U_SIZEOF_UCHAR)); /* Test for nullptr */ if(tempbuffer == nullptr) { @@ -1326,9 +1326,9 @@ shapeUnicode(char16_t *dest, int32_t sourceLength, dest[i] = 0xFE70 + IrrelevantPos[(dest[i] - 0x064B)] + static_cast(Shape); } }else if ((currLink & APRESENT) > 0) { - dest[i] = (char16_t)(0xFB50 + (currLink >> 8) + Shape); + dest[i] = static_cast(0xFB50 + (currLink >> 8) + Shape); }else if ((currLink >> 8) > 0 && (currLink & IRRELEVANT) == 0) { - dest[i] = (char16_t)(0xFE70 + (currLink >> 8) + Shape); + dest[i] = static_cast(0xFE70 + (currLink >> 8) + Shape); } } } diff --git a/icu4c/source/common/usprep.cpp b/icu4c/source/common/usprep.cpp index 22ab0c24ebb8..82dd7a4ca0fd 100644 --- a/icu4c/source/common/usprep.cpp +++ b/icu4c/source/common/usprep.cpp @@ -246,8 +246,8 @@ loadData(UStringPrepProfile* profile, return false; } - p=(const int32_t *)udata_getMemory(dataMemory); - pb=(const uint8_t *)(p+_SPREP_INDEX_TOP); + p = static_cast(udata_getMemory(dataMemory)); + pb = reinterpret_cast(p + _SPREP_INDEX_TOP); utrie_unserialize(&_sprepTrie, pb, p[_SPREP_INDEX_TRIE_SIZE], errorCode); _sprepTrie.getFoldingOffset=getSPrepFoldingOffset; @@ -265,11 +265,11 @@ loadData(UStringPrepProfile* profile, uprv_memcpy(&profile->indexes, p, sizeof(profile->indexes)); uprv_memcpy(&profile->sprepTrie, &_sprepTrie, sizeof(UTrie)); } else { - p=(const int32_t *)udata_getMemory(profile->sprepData); + p = static_cast(udata_getMemory(profile->sprepData)); } umtx_unlock(&usprepMutex); /* initialize some variables */ - profile->mappingData=(uint16_t *)((uint8_t *)(p+_SPREP_INDEX_TOP)+profile->indexes[_SPREP_INDEX_TRIE_SIZE]); + profile->mappingData = reinterpret_cast(reinterpret_cast(p + _SPREP_INDEX_TOP) + profile->indexes[_SPREP_INDEX_TRIE_SIZE]); u_getUnicodeVersion(normUnicodeVersion); normUniVer = (normUnicodeVersion[0] << 24) + (normUnicodeVersion[1] << 16) + @@ -320,12 +320,12 @@ usprep_getProfile(const char* path, * we use the passed in pointers for fetching the data from the * hash table which is safe */ - stackKey.name = (char*) name; - stackKey.path = (char*) path; + stackKey.name = const_cast(name); + stackKey.path = const_cast(path); /* fetch the data from the cache */ umtx_lock(&usprepMutex); - profile = (UStringPrepProfile*) (uhash_get(SHARED_DATA_HASHTABLE,&stackKey)); + profile = static_cast(uhash_get(SHARED_DATA_HASHTABLE, &stackKey)); if(profile != nullptr) { profile->refCount++; } @@ -345,8 +345,8 @@ usprep_getProfile(const char* path, } /* get the options */ - newProfile->doNFKC = (UBool)((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_NORMALIZATION_ON) > 0); - newProfile->checkBiDi = (UBool)((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_CHECK_BIDI_ON) > 0); + newProfile->doNFKC = static_cast((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_NORMALIZATION_ON) > 0); + newProfile->checkBiDi = static_cast((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_CHECK_BIDI_ON) > 0); LocalMemory key; LocalMemory keyName; @@ -363,7 +363,7 @@ usprep_getProfile(const char* path, umtx_lock(&usprepMutex); // If another thread already inserted the same key/value, refcount and cleanup our thread data - profile = (UStringPrepProfile*) (uhash_get(SHARED_DATA_HASHTABLE,&stackKey)); + profile = static_cast(uhash_get(SHARED_DATA_HASHTABLE, &stackKey)); if(profile != nullptr) { profile->refCount++; usprep_unload(newProfile.getAlias()); @@ -477,7 +477,7 @@ getValues(uint16_t trieWord, int16_t& value, UBool& isIndex){ isIndex =false; value = 0; }else if(trieWord >= _SPREP_TYPE_THRESHOLD){ - type = (UStringPrepType) (trieWord - _SPREP_TYPE_THRESHOLD); + type = static_cast(trieWord - _SPREP_TYPE_THRESHOLD); isIndex =false; value = 0; }else{ @@ -489,7 +489,7 @@ getValues(uint16_t trieWord, int16_t& value, UBool& isIndex){ value = trieWord >> 2; //mask off the lower 2 bits and shift }else{ isIndex = false; - value = (int16_t)trieWord; + value = static_cast(trieWord); value = (value >> 2); } @@ -514,7 +514,7 @@ usprep_map( const UStringPrepProfile* profile, uint16_t result; int32_t destIndex=0; int32_t srcIndex; - UBool allowUnassigned = (UBool) ((options & USPREP_ALLOW_UNASSIGNED)>0); + UBool allowUnassigned = static_cast((options & USPREP_ALLOW_UNASSIGNED) > 0); UStringPrepType type; int16_t value; UBool isIndex; @@ -581,7 +581,7 @@ usprep_map( const UStringPrepProfile* profile, //copy the code point into destination if(ch <= 0xFFFF){ if(destIndex < destCapacity ){ - dest[destIndex] = (char16_t)ch; + dest[destIndex] = static_cast(ch); } destIndex++; }else{ diff --git a/icu4c/source/common/ustr_titlecase_brkiter.cpp b/icu4c/source/common/ustr_titlecase_brkiter.cpp index 82beaca65b2c..e96af0df878d 100644 --- a/icu4c/source/common/ustr_titlecase_brkiter.cpp +++ b/icu4c/source/common/ustr_titlecase_brkiter.cpp @@ -93,7 +93,7 @@ void WholeStringBreakIterator::setText(UText *text, UErrorCode &errorCode) { if (U_SUCCESS(errorCode)) { int64_t length64 = utext_nativeLength(text); if (length64 <= INT32_MAX) { - length = (int32_t)length64; + length = static_cast(length64); } else { errorCode = U_INDEX_OUTOFBOUNDS_ERROR; } diff --git a/icu4c/source/common/ustrcase.cpp b/icu4c/source/common/ustrcase.cpp index 4c726d47db12..bb63dbe9a15c 100644 --- a/icu4c/source/common/ustrcase.cpp +++ b/icu4c/source/common/ustrcase.cpp @@ -77,7 +77,7 @@ appendResult(char16_t *dest, int32_t destIndex, int32_t destCapacity, } c=~result; if(destIndex(c); return destIndex; } length=cpLength; @@ -86,7 +86,7 @@ appendResult(char16_t *dest, int32_t destIndex, int32_t destCapacity, c=U_SENTINEL; length=result; } else if(destIndex(result); if(edits!=nullptr) { edits->addReplace(cpLength, 1); } @@ -171,7 +171,7 @@ appendUnchanged(char16_t *dest, int32_t destIndex, int32_t destCapacity, UChar32 U_CALLCONV utf16_caseContextIterator(void *context, int8_t dir) { - UCaseContext *csc=(UCaseContext *)context; + UCaseContext* csc = static_cast(context); UChar32 c; if(dir<0) { @@ -1216,7 +1216,7 @@ int32_t toUpper(uint32_t options, } if (change) { - destIndex=appendUChar(dest, destIndex, destCapacity, (char16_t)upper); + destIndex = appendUChar(dest, destIndex, destCapacity, static_cast(upper)); if (destIndex >= 0 && (data & HAS_EITHER_DIALYTIKA) != 0) { destIndex=appendUChar(dest, destIndex, destCapacity, 0x308); // restore or add a dialytika } @@ -1698,7 +1698,7 @@ static int32_t _cmpFold( */ if( level1==0 && - (length=ucase_toFullFolding((UChar32)cp1, &p, options))>=0 + (length = ucase_toFullFolding(cp1, &p, options)) >= 0 ) { /* cp1 case-folds to the code point "length" or to p[length] */ if(U_IS_SURROGATE(c1)) { @@ -1744,7 +1744,7 @@ static int32_t _cmpFold( } if( level2==0 && - (length=ucase_toFullFolding((UChar32)cp2, &p, options))>=0 + (length = ucase_toFullFolding(cp2, &p, options)) >= 0 ) { /* cp2 case-folds to the code point "length" or to p[length] */ if(U_IS_SURROGATE(c2)) { diff --git a/icu4c/source/common/ustrenum.cpp b/icu4c/source/common/ustrenum.cpp index f4fc5906ed71..c42014d617d7 100644 --- a/icu4c/source/common/ustrenum.cpp +++ b/icu4c/source/common/ustrenum.cpp @@ -89,7 +89,7 @@ StringEnumeration::ensureCharsCapacity(int32_t capacity, UErrorCode &status) { if(chars!=charsBuffer) { uprv_free(chars); } - chars=(char *)uprv_malloc(capacity); + chars = static_cast(uprv_malloc(capacity)); if(chars==nullptr) { chars=charsBuffer; charsCapacity=sizeof(charsBuffer); @@ -104,7 +104,7 @@ UnicodeString * StringEnumeration::setChars(const char *s, int32_t length, UErrorCode &status) { if(U_SUCCESS(status) && s!=nullptr) { if(length<0) { - length=(int32_t)uprv_strlen(s); + length = static_cast(uprv_strlen(s)); } char16_t *buffer=unistr.getBuffer(length+1); @@ -307,7 +307,7 @@ ucharstrenum_unext(UEnumeration* en, } const char16_t* result = ((const char16_t**)e->uenum.context)[e->index++]; if (resultLength) { - *resultLength = (int32_t)u_strlen(result); + *resultLength = u_strlen(result); } return result; } diff --git a/icu4c/source/common/ustring.cpp b/icu4c/source/common/ustring.cpp index 4f7443cc886b..8375121e2f45 100644 --- a/icu4c/source/common/ustring.cpp +++ b/icu4c/source/common/ustring.cpp @@ -1356,7 +1356,7 @@ _charPtr_charAt(int32_t offset, void *context) { char16_t c16; /* It would be more efficient to access the invariant tables * directly but there is no API for that. */ - u_charsToUChars(((char*) context) + offset, &c16, 1); + u_charsToUChars(static_cast(context) + offset, &c16, 1); return c16; } @@ -1394,7 +1394,7 @@ u_unescape(const char *src, char16_t *dest, int32_t destCapacity) { i += (int32_t)(src - segment); } ++src; /* advance past '\\' */ - c32 = (UChar32)u_unescapeAt(_charPtr_charAt, &lenParsed, (int32_t)uprv_strlen(src), (void*)src); + c32 = u_unescapeAt(_charPtr_charAt, &lenParsed, (int32_t)uprv_strlen(src), const_cast(src)); if (lenParsed == 0) { goto err; } diff --git a/icu4c/source/common/ustrtrns.cpp b/icu4c/source/common/ustrtrns.cpp index 244c111fc416..d16eabe99fd0 100644 --- a/icu4c/source/common/ustrtrns.cpp +++ b/icu4c/source/common/ustrtrns.cpp @@ -771,19 +771,19 @@ static inline uint8_t * _appendUTF8(uint8_t *pDest, UChar32 c) { /* it is 0<=c<=0x10ffff and not a surrogate if called by a validating function */ if((c)<=0x7f) { - *pDest++=(uint8_t)c; + *pDest++ = static_cast(c); } else if(c<=0x7ff) { - *pDest++=(uint8_t)((c>>6)|0xc0); - *pDest++=(uint8_t)((c&0x3f)|0x80); + *pDest++ = static_cast((c >> 6) | 0xc0); + *pDest++ = static_cast((c & 0x3f) | 0x80); } else if(c<=0xffff) { - *pDest++=(uint8_t)((c>>12)|0xe0); - *pDest++=(uint8_t)(((c>>6)&0x3f)|0x80); - *pDest++=(uint8_t)(((c)&0x3f)|0x80); + *pDest++ = static_cast((c >> 12) | 0xe0); + *pDest++ = static_cast(((c >> 6) & 0x3f) | 0x80); + *pDest++ = static_cast(((c) & 0x3f) | 0x80); } else /* if((uint32_t)(c)<=0x10ffff) */ { - *pDest++=(uint8_t)(((c)>>18)|0xf0); - *pDest++=(uint8_t)((((c)>>12)&0x3f)|0x80); - *pDest++=(uint8_t)((((c)>>6)&0x3f)|0x80); - *pDest++=(uint8_t)(((c)&0x3f)|0x80); + *pDest++ = static_cast(((c) >> 18) | 0xf0); + *pDest++ = static_cast((((c) >> 12) & 0x3f) | 0x80); + *pDest++ = static_cast((((c) >> 6) & 0x3f) | 0x80); + *pDest++ = static_cast(((c) & 0x3f) | 0x80); } return pDest; } diff --git a/icu4c/source/common/utext.cpp b/icu4c/source/common/utext.cpp index eb0a6984bd3f..4b09c3714f17 100644 --- a/icu4c/source/common/utext.cpp +++ b/icu4c/source/common/utext.cpp @@ -738,7 +738,7 @@ pinIndex(int64_t &index, int64_t limit) { } else if (index > limit) { index = limit; } - return (int32_t)index; + return static_cast(index); } diff --git a/icu4c/source/common/util.cpp b/icu4c/source/common/util.cpp index f6a13aa445d2..d80ccb50ed0e 100644 --- a/icu4c/source/common/util.cpp +++ b/icu4c/source/common/util.cpp @@ -37,12 +37,12 @@ UnicodeString& ICU_Utility::appendNumber(UnicodeString& result, int32_t n, int32_t radix, int32_t minDigits) { if (radix < 2 || radix > 36) { // Bogus radix - return result.append((char16_t)63/*?*/); + return result.append(static_cast(63)/*?*/); } // Handle negatives if (n < 0) { n = -n; - result.append((char16_t)45/*-*/); + result.append(static_cast(45)/*-*/); } // First determine the number of digits int32_t nn = n; @@ -150,7 +150,7 @@ int32_t ICU_Utility::skipWhitespace(const UnicodeString& str, int32_t& pos, UBool advance) { int32_t p = pos; const char16_t* s = str.getBuffer(); - p = (int32_t)(PatternProps::skipWhiteSpace(s + p, str.length() - p) - s); + p = static_cast(PatternProps::skipWhiteSpace(s + p, str.length() - p) - s); if (advance) { pos = p; } @@ -361,7 +361,7 @@ void ICU_Utility::appendToRule(UnicodeString& rule, rule.append(BACKSLASH).append(APOSTROPHE); } } - if (c != (UChar32)-1) { + if (c != static_cast(-1)) { /* Since spaces are ignored during parsing, they are * emitted only for readability. We emit one here * only if there isn't already one at the end of the diff --git a/icu4c/source/common/util_props.cpp b/icu4c/source/common/util_props.cpp index 366a555eeebd..b1862c24e680 100644 --- a/icu4c/source/common/util_props.cpp +++ b/icu4c/source/common/util_props.cpp @@ -120,7 +120,7 @@ int32_t ICU_Utility::parsePattern(const UnicodeString& rule, int32_t pos, int32_ if (pos >= limit) { return -1; } - c = (char16_t) u_tolower(rule.charAt(pos++)); + c = static_cast(u_tolower(rule.charAt(pos++))); if (c != cpat) { return -1; } diff --git a/icu4c/source/common/utrace.cpp b/icu4c/source/common/utrace.cpp index 1f536d5643df..875bef31a295 100644 --- a/icu4c/source/common/utrace.cpp +++ b/icu4c/source/common/utrace.cpp @@ -138,7 +138,7 @@ static void outputHexBytes(int64_t val, int32_t charsToOutput, static void outputPtrBytes(void *val, char *outBuf, int32_t *outIx, int32_t capacity) { uint32_t i; int32_t incVal = 1; /* +1 for big endian, -1 for little endian */ - char *p = (char *)&val; /* point to current byte to output in the ptr val */ + char* p = reinterpret_cast(&val); /* point to current byte to output in the ptr val */ #if !U_IS_BIG_ENDIAN /* Little Endian. Move p to most significant end of the value */ @@ -233,7 +233,7 @@ utrace_vformat(char *outBuf, int32_t capacity, int32_t indent, const char *fmt, case 'S': /* char16_t * string, with length, len==-1 for NUL terminated. */ ptrArg = va_arg(args, char *); /* Ptr */ - intArg =(int32_t)va_arg(args, int32_t); /* Length */ + intArg = va_arg(args, int32_t); /* Length */ outputUString((const char16_t *)ptrArg, intArg, outBuf, &outIx, capacity, indent); break; @@ -298,7 +298,7 @@ utrace_vformat(char *outBuf, int32_t capacity, int32_t indent, const char *fmt, i32Ptr = (int32_t *)i8Ptr; i64Ptr = (int64_t *)i8Ptr; ptrPtr = (void **)i8Ptr; - vectorLen =(int32_t)va_arg(args, int32_t); + vectorLen = va_arg(args, int32_t); if (ptrPtr == nullptr) { outputString("*NULL* ", outBuf, &outIx, capacity, indent); } else { diff --git a/icu4c/source/common/utrie.cpp b/icu4c/source/common/utrie.cpp index 83be0e340714..88c01a53d2df 100644 --- a/icu4c/source/common/utrie.cpp +++ b/icu4c/source/common/utrie.cpp @@ -40,7 +40,7 @@ equal_uint32(const uint32_t *s, const uint32_t *t, int32_t length) { ++t; --length; } - return (UBool)(length==0); + return static_cast(length == 0); } /* Building a trie ----------------------------------------------------------*/ @@ -730,7 +730,7 @@ defaultGetFoldedValue(UNewTrie *trie, UChar32 start, int32_t offset) { if(inBlockZero) { start+=UTRIE_DATA_BLOCK_LENGTH; } else if(value!=initialValue) { - return (uint32_t)offset; + return static_cast(offset); } else { ++start; } diff --git a/icu4c/source/common/utrie2.cpp b/icu4c/source/common/utrie2.cpp index 2c3488a4cd02..f8ed7cfc70fe 100644 --- a/icu4c/source/common/utrie2.cpp +++ b/icu4c/source/common/utrie2.cpp @@ -552,7 +552,7 @@ enumEitherTrie(const UTrie2 *trie, } for(; i2(idx[i2Block + i2]) << UTRIE2_INDEX_SHIFT; } else { block=trie->newTrie->index2[i2Block+i2]; } diff --git a/icu4c/source/common/utrie2_builder.cpp b/icu4c/source/common/utrie2_builder.cpp index 02a62e3fd4d3..92e9fd733c4f 100644 --- a/icu4c/source/common/utrie2_builder.cpp +++ b/icu4c/source/common/utrie2_builder.cpp @@ -249,12 +249,12 @@ static UNewTrie2 * cloneBuilder(const UNewTrie2 *other) { UNewTrie2 *trie; - trie=(UNewTrie2 *)uprv_malloc(sizeof(UNewTrie2)); + trie = static_cast(uprv_malloc(sizeof(UNewTrie2))); if(trie==nullptr) { return nullptr; } - trie->data=(uint32_t *)uprv_malloc(other->dataCapacity*4); + trie->data = static_cast(uprv_malloc(other->dataCapacity * 4)); if(trie->data==nullptr) { uprv_free(trie); return nullptr; @@ -506,7 +506,7 @@ isInNullBlock(UNewTrie2 *trie, UChar32 c, UBool forLSCP) { ((c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK); } block=trie->index2[i2]; - return (UBool)(block==trie->dataNullOffset); + return static_cast(block == trie->dataNullOffset); } static int32_t @@ -577,7 +577,7 @@ allocDataBlock(UNewTrie2 *trie, int32_t copyBlock) { */ return -1; } - data=(uint32_t *)uprv_malloc(capacity*4); + data = static_cast(uprv_malloc(capacity * 4)); if(data==nullptr) { return -1; } @@ -603,7 +603,7 @@ releaseDataBlock(UNewTrie2 *trie, int32_t block) { static inline UBool isWritableBlock(UNewTrie2 *trie, int32_t block) { - return (UBool)(block!=trie->dataNullOffset && 1==trie->map[block>>UTRIE2_SHIFT_2]); + return static_cast(block != trie->dataNullOffset && 1 == trie->map[block >> UTRIE2_SHIFT_2]); } static inline void @@ -891,7 +891,7 @@ equal_int32(const int32_t *s, const int32_t *t, int32_t length) { ++t; --length; } - return (UBool)(length==0); + return static_cast(length == 0); } static inline UBool @@ -901,7 +901,7 @@ equal_uint32(const uint32_t *s, const uint32_t *t, int32_t length) { ++t; --length; } - return (UBool)(length==0); + return static_cast(length == 0); } static int32_t @@ -1211,7 +1211,7 @@ compactIndex2(UNewTrie2 *trie) { */ while((newStart&((UTRIE2_DATA_GRANULARITY-1)|1))!=0) { /* Arbitrary value: 0x3fffc not possible for real data. */ - trie->index2[newStart++]=(int32_t)0xffff<index2[newStart++] = static_cast(0xffff) << UTRIE2_INDEX_SHIFT; } #ifdef UTRIE2_DEBUG diff --git a/icu4c/source/common/utrie_swap.cpp b/icu4c/source/common/utrie_swap.cpp index 83d183699d10..c61d3af8c319 100644 --- a/icu4c/source/common/utrie_swap.cpp +++ b/icu4c/source/common/utrie_swap.cpp @@ -305,7 +305,7 @@ getVersion(const void *data, int32_t length, UBool anyEndianOk) { if(length<16 || data==nullptr || (U_POINTER_MASK_LSB(data, 3)!=0)) { return 0; } - signature=*(const uint32_t *)data; + signature = *static_cast(data); if(signature==UCPTRIE_SIG) { return 3; } diff --git a/icu4c/source/common/uts46.cpp b/icu4c/source/common/uts46.cpp index f0e1372422da..39cf415b2273 100644 --- a/icu4c/source/common/uts46.cpp +++ b/icu4c/source/common/uts46.cpp @@ -451,10 +451,10 @@ UTS46::processUTF8(StringPiece src, return; } char c=srcArray[i]; - if((int8_t)c<0) { // (uint8_t)c>0x7f + if (static_cast(c) < 0) { // (uint8_t)c>0x7f break; } - int cData=asciiData[(int)c]; // Cast: gcc warns about indexing with a char. + int cData = asciiData[static_cast(c)]; // Cast: gcc warns about indexing with a char. if(cData>0) { destArray[i]=c+0x20; // Lowercase an uppercase ASCII letter. } else if(cData<0 && disallowNonLDHDot) { @@ -796,7 +796,7 @@ UTS46::processLabel(UnicodeString &dest, // in a non-Punycode label or U+FFFD itself in a Punycode label. // We also check for dots which can come from the input to a single-label function. // Ok to cast away const because we own the UnicodeString. - char16_t *s=(char16_t *)label; + char16_t* s = const_cast(label); const char16_t *limit=label+labelLength; char16_t oredChars=0; // If we enforce STD3 rules, then ASCII characters other than LDH and dot are disallowed. @@ -827,7 +827,7 @@ UTS46::processLabel(UnicodeString &dest, U16_NEXT_UNSAFE(label, cpLength, c); if((U_GET_GC_MASK(c)&U_GC_M_MASK)!=0) { info.labelErrors|=UIDNA_ERROR_LEADING_COMBINING_MARK; - labelString->replace(labelStart, cpLength, (char16_t)0xfffd); + labelString->replace(labelStart, cpLength, static_cast(0xfffd)); label=labelString->getBuffer()+labelStart; labelLength+=1-cpLength; if(labelString==&dest) { @@ -947,7 +947,7 @@ UTS46::markBadACELabel(UnicodeString &dest, } } if(onlyLDH) { - dest.insert(labelStart+labelLength, (char16_t)0xfffd); + dest.insert(labelStart + labelLength, static_cast(0xfffd)); if(dest.isBogus()) { errorCode=U_MEMORY_ALLOCATION_ERROR; return 0; diff --git a/icu4c/source/common/uvector.cpp b/icu4c/source/common/uvector.cpp index 85c322cea75a..5eb89c9a56bb 100644 --- a/icu4c/source/common/uvector.cpp +++ b/icu4c/source/common/uvector.cpp @@ -49,10 +49,10 @@ UVector::UVector(UObjectDeleter *d, UElementsAreEqual *c, int32_t initialCapacit return; } // Fix bogus initialCapacity values; avoid malloc(0) and integer overflow - if ((initialCapacity < 1) || (initialCapacity > (int32_t)(INT32_MAX / sizeof(UElement)))) { + if ((initialCapacity < 1) || (initialCapacity > static_cast(INT32_MAX / sizeof(UElement)))) { initialCapacity = DEFAULT_CAPACITY; } - elements = (UElement *)uprv_malloc(sizeof(UElement)*initialCapacity); + elements = static_cast(uprv_malloc(sizeof(UElement) * initialCapacity)); if (elements == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { @@ -340,12 +340,12 @@ UBool UVector::ensureCapacity(int32_t minimumCapacity, UErrorCode &status) { if (newCap < minimumCapacity) { newCap = minimumCapacity; } - if (newCap > (int32_t)(INT32_MAX / sizeof(UElement))) { // integer overflow check + if (newCap > static_cast(INT32_MAX / sizeof(UElement))) { // integer overflow check // We keep the original memory contents on bad minimumCapacity. status = U_ILLEGAL_ARGUMENT_ERROR; return false; } - UElement* newElems = (UElement *)uprv_realloc(elements, sizeof(UElement)*newCap); + UElement* newElems = static_cast(uprv_realloc(elements, sizeof(UElement) * newCap)); if (newElems == nullptr) { // We keep the original contents on the memory failure on realloc or bad minimumCapacity. status = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/common/uvectr32.cpp b/icu4c/source/common/uvectr32.cpp index a2dc1bdbc983..7389b3f06d02 100644 --- a/icu4c/source/common/uvectr32.cpp +++ b/icu4c/source/common/uvectr32.cpp @@ -54,10 +54,10 @@ void UVector32::_init(int32_t initialCapacity, UErrorCode &status) { if (maxCapacity>0 && maxCapacity (int32_t)(INT32_MAX / sizeof(int32_t))) { + if (initialCapacity > static_cast(INT32_MAX / sizeof(int32_t))) { initialCapacity = uprv_min(DEFAULT_CAPACITY, maxCapacity); } - elements = (int32_t *)uprv_malloc(sizeof(int32_t)*initialCapacity); + elements = static_cast(uprv_malloc(sizeof(int32_t) * initialCapacity)); if (elements == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { @@ -223,12 +223,12 @@ UBool UVector32::expandCapacity(int32_t minimumCapacity, UErrorCode &status) { if (maxCapacity > 0 && newCap > maxCapacity) { newCap = maxCapacity; } - if (newCap > (int32_t)(INT32_MAX / sizeof(int32_t))) { // integer overflow check + if (newCap > static_cast(INT32_MAX / sizeof(int32_t))) { // integer overflow check // We keep the original memory contents on bad minimumCapacity/maxCapacity. status = U_ILLEGAL_ARGUMENT_ERROR; return false; } - int32_t* newElems = (int32_t *)uprv_realloc(elements, sizeof(int32_t)*newCap); + int32_t* newElems = static_cast(uprv_realloc(elements, sizeof(int32_t) * newCap)); if (newElems == nullptr) { // We keep the original contents on the memory failure on realloc. status = U_MEMORY_ALLOCATION_ERROR; @@ -244,7 +244,7 @@ void UVector32::setMaxCapacity(int32_t limit) { if (limit < 0) { limit = 0; } - if (limit > (int32_t)(INT32_MAX / sizeof(int32_t))) { // integer overflow check for realloc + if (limit > static_cast(INT32_MAX / sizeof(int32_t))) { // integer overflow check for realloc // Something is very wrong, don't realloc, leave capacity and maxCapacity unchanged return; } @@ -256,7 +256,7 @@ void UVector32::setMaxCapacity(int32_t limit) { // New maximum capacity is smaller than the current size. // Realloc the storage to the new, smaller size. - int32_t* newElems = (int32_t *)uprv_realloc(elements, sizeof(int32_t)*maxCapacity); + int32_t* newElems = static_cast(uprv_realloc(elements, sizeof(int32_t) * maxCapacity)); if (newElems == nullptr) { // Realloc to smaller failed. // Just keep what we had. No need to call it a failure. diff --git a/icu4c/source/common/uvectr64.cpp b/icu4c/source/common/uvectr64.cpp index 58b0b1f8b86a..81c923f4f8f8 100644 --- a/icu4c/source/common/uvectr64.cpp +++ b/icu4c/source/common/uvectr64.cpp @@ -51,10 +51,10 @@ void UVector64::_init(int32_t initialCapacity, UErrorCode &status) { if (maxCapacity>0 && maxCapacity (int32_t)(INT32_MAX / sizeof(int64_t))) { + if (initialCapacity > static_cast(INT32_MAX / sizeof(int64_t))) { initialCapacity = uprv_min(DEFAULT_CAPACITY, maxCapacity); } - elements = (int64_t *)uprv_malloc(sizeof(int64_t)*initialCapacity); + elements = static_cast(uprv_malloc(sizeof(int64_t) * initialCapacity)); if (elements == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { @@ -141,12 +141,12 @@ UBool UVector64::expandCapacity(int32_t minimumCapacity, UErrorCode &status) { if (maxCapacity > 0 && newCap > maxCapacity) { newCap = maxCapacity; } - if (newCap > (int32_t)(INT32_MAX / sizeof(int64_t))) { // integer overflow check + if (newCap > static_cast(INT32_MAX / sizeof(int64_t))) { // integer overflow check // We keep the original memory contents on bad minimumCapacity/maxCapacity. status = U_ILLEGAL_ARGUMENT_ERROR; return false; } - int64_t* newElems = (int64_t *)uprv_realloc(elements, sizeof(int64_t)*newCap); + int64_t* newElems = static_cast(uprv_realloc(elements, sizeof(int64_t) * newCap)); if (newElems == nullptr) { // We keep the original contents on the memory failure on realloc. status = U_MEMORY_ALLOCATION_ERROR; @@ -162,7 +162,7 @@ void UVector64::setMaxCapacity(int32_t limit) { if (limit < 0) { limit = 0; } - if (limit > (int32_t)(INT32_MAX / sizeof(int64_t))) { // integer overflow check for realloc + if (limit > static_cast(INT32_MAX / sizeof(int64_t))) { // integer overflow check for realloc // Something is very wrong, don't realloc, leave capacity and maxCapacity unchanged return; } @@ -174,7 +174,7 @@ void UVector64::setMaxCapacity(int32_t limit) { // New maximum capacity is smaller than the current size. // Realloc the storage to the new, smaller size. - int64_t* newElems = (int64_t *)uprv_realloc(elements, sizeof(int64_t)*maxCapacity); + int64_t* newElems = static_cast(uprv_realloc(elements, sizeof(int64_t) * maxCapacity)); if (newElems == nullptr) { // Realloc to smaller failed. // Just keep what we had. No need to call it a failure. diff --git a/icu4c/source/extra/uconv/uconv.cpp b/icu4c/source/extra/uconv/uconv.cpp index 20ad13fe0f52..9f802a597822 100644 --- a/icu4c/source/extra/uconv/uconv.cpp +++ b/icu4c/source/extra/uconv/uconv.cpp @@ -243,7 +243,7 @@ static int printConverters(const char *pname, const char *lookfor, } num_stds = ucnv_countStandards(); - stds = (const char **) uprv_malloc(num_stds * sizeof(*stds)); + stds = static_cast(uprv_malloc(num_stds * sizeof(*stds))); if (!stds) { u_wmsg(stderr, "cantGetTag", u_wmsg_errorName(U_MEMORY_ALLOCATION_ERROR)); return -1; @@ -463,7 +463,7 @@ getChunkLimit(const UnicodeString &prev, const UnicodeString &s) { ++u; // include the LF in this chunk } } - return (int32_t)(u - s.getBuffer()); + return static_cast(u - s.getBuffer()); } } @@ -481,8 +481,8 @@ nibbleToHex(uint8_t n) { n &= 0xf; return n <= 9 ? - (char16_t)(0x30 + n) : - (char16_t)((0x61 - 10) + n); + static_cast(0x30 + n) : + static_cast((0x61 - 10) + n); } // check the converter's Unicode signature properties; @@ -521,7 +521,7 @@ cnvSigType(UConverter *cnv) { nullptr, true, &err); ucnv_resetFromUnicode(cnv); - if (nullptr != ucnv_detectUnicodeSignature(buffer, (int32_t)(out - buffer), nullptr, &err) && + if (nullptr != ucnv_detectUnicodeSignature(buffer, static_cast(out - buffer), nullptr, &err) && U_SUCCESS(err) ) { result = CNV_ADDS_FEFF; @@ -623,9 +623,9 @@ ConvertFile::convertFile(const char *pname, infile = fopen(infilestr, "rb"); if (infile == nullptr) { UnicodeString str1(infilestr, ""); - str1.append((UChar32) 0); + str1.append(static_cast(0)); UnicodeString str2(strerror(errno), ""); - str2.append((UChar32) 0); + str2.append(static_cast(0)); initMsg(pname); u_wmsg(stderr, "cantOpenInputF", str1.getBuffer(), str2.getBuffer()); return false; @@ -665,7 +665,7 @@ ConvertFile::convertFile(const char *pname, } if (U_FAILURE(err)) { - str.append((UChar32) 0); + str.append(static_cast(0)); initMsg(pname); if (parse.line >= 0) { @@ -758,21 +758,21 @@ ConvertFile::convertFile(const char *pname, // that characters on hold also will be written. cbufp = buf; - flush = (UBool)(rd != bufsz); + flush = static_cast(rd != bufsz); // convert until the input is consumed do { // remember the start of the current byte-to-Unicode conversion prevbufp = cbufp; - unibuf = unibufp = u.getBuffer((int32_t)bufsz); + unibuf = unibufp = u.getBuffer(static_cast(bufsz)); // Use bufsz instead of u.getCapacity() for the targetLimit // so that we don't overflow fromoffsets[]. ucnv_toUnicode(convfrom, &unibufp, unibuf + bufsz, &cbufp, buf + rd, useOffsets ? fromoffsets : nullptr, flush, &err); - ulen = (int32_t)(unibufp - unibuf); + ulen = static_cast(unibufp - unibuf); u.releaseBuffer(U_SUCCESS(err) ? ulen : 0); // fromSawEndOfBytes indicates that ucnv_toUnicode() is done @@ -784,7 +784,7 @@ ConvertFile::convertFile(const char *pname, // - the source is consumed // That is, if the error code does not indicate a failure, // not even an overflow, then the source must be consumed entirely. - fromSawEndOfBytes = (UBool)U_SUCCESS(err); + fromSawEndOfBytes = U_SUCCESS(err); if (err == U_BUFFER_OVERFLOW_ERROR) { err = U_ZERO_ERROR; @@ -793,7 +793,7 @@ ConvertFile::convertFile(const char *pname, int8_t i, length, errorLength; UErrorCode localError = U_ZERO_ERROR; - errorLength = (int8_t)sizeof(errorBytes); + errorLength = static_cast(sizeof(errorBytes)); ucnv_getInvalidChars(convfrom, errorBytes, &errorLength, &localError); if (U_FAILURE(localError) || errorLength == 0) { errorLength = 1; @@ -804,17 +804,17 @@ ConvertFile::convertFile(const char *pname, // length of the just consumed bytes - // length of the error bytes length = - (int8_t)snprintf(pos, sizeof(pos), "%d", - (int)(infoffset + (cbufp - buf) - errorLength)); + static_cast(snprintf(pos, sizeof(pos), "%d", + static_cast(infoffset + (cbufp - buf) - errorLength))); // output the bytes that caused the error UnicodeString str; for (i = 0; i < errorLength; ++i) { if (i > 0) { - str.append((char16_t)uSP); + str.append(static_cast(uSP)); } - str.append(nibbleToHex((uint8_t)errorBytes[i] >> 4)); - str.append(nibbleToHex((uint8_t)errorBytes[i])); + str.append(nibbleToHex(static_cast(errorBytes[i]) >> 4)); + str.append(nibbleToHex(static_cast(errorBytes[i]))); } initMsg(pname); @@ -897,7 +897,7 @@ ConvertFile::convertFile(const char *pname, // and possible/necessary if (sig > 0) { if (u.charAt(0) != uSig && cnvSigType(convto) == CNV_WITH_FEFF) { - u.insert(0, (char16_t)uSig); + u.insert(0, static_cast(uSig)); if (useOffsets) { // insert a pseudo-offset into fromoffsets[] as well @@ -929,12 +929,12 @@ ConvertFile::convertFile(const char *pname, ucnv_fromUnicode(convto, &bufp, outbuf + bufsz, &unibufbp, unibuf + ulen, - nullptr, (UBool)(flush && fromSawEndOfBytes), &err); + nullptr, static_cast(flush && fromSawEndOfBytes), &err); // toSawEndOfUnicode indicates that ucnv_fromUnicode() is done // converting all of the intermediate UChars. // See comment for fromSawEndOfBytes. - toSawEndOfUnicode = (UBool)U_SUCCESS(err); + toSawEndOfUnicode = U_SUCCESS(err); if (err == U_BUFFER_OVERFLOW_ERROR) { err = U_ZERO_ERROR; @@ -957,7 +957,7 @@ ConvertFile::convertFile(const char *pname, if (useOffsets) { // Unicode buffer offset of the start of the error UChars - ferroffset = (int32_t)((unibufbp - unibuf) - errorLength); + ferroffset = static_cast((unibufbp - unibuf) - errorLength); if (ferroffset < 0) { // approximation - the character started in the previous Unicode buffer ferroffset = 0; @@ -981,29 +981,29 @@ ConvertFile::convertFile(const char *pname, // be different from what the offsets refer to. // output file offset - ferroffset = (int32_t)(outfoffset + (bufp - outbuf)); + ferroffset = static_cast(outfoffset + (bufp - outbuf)); errtag = "problemCvtFromUOut"; } - length = (int8_t)snprintf(pos, sizeof(pos), "%u", (int)ferroffset); + length = static_cast(snprintf(pos, sizeof(pos), "%u", static_cast(ferroffset))); // output the code points that caused the error UnicodeString str; for (i = 0; i < errorLength;) { if (i > 0) { - str.append((char16_t)uSP); + str.append(static_cast(uSP)); } U16_NEXT(errorUChars, i, errorLength, c); if (c >= 0x100000) { - str.append(nibbleToHex((uint8_t)(c >> 20))); + str.append(nibbleToHex(static_cast(c >> 20))); } if (c >= 0x10000) { - str.append(nibbleToHex((uint8_t)(c >> 16))); + str.append(nibbleToHex(static_cast(c >> 16))); } - str.append(nibbleToHex((uint8_t)(c >> 12))); - str.append(nibbleToHex((uint8_t)(c >> 8))); - str.append(nibbleToHex((uint8_t)(c >> 4))); - str.append(nibbleToHex((uint8_t)c)); + str.append(nibbleToHex(static_cast(c >> 12))); + str.append(nibbleToHex(static_cast(c >> 8))); + str.append(nibbleToHex(static_cast(c >> 4))); + str.append(nibbleToHex(static_cast(c))); } initMsg(pname); @@ -1021,8 +1021,8 @@ ConvertFile::convertFile(const char *pname, // looping until they are; message key "premEnd" now obsolete. // Finally, write the converted buffer to the output file - size_t outlen = (size_t) (bufp - outbuf); - outfoffset += (int32_t)(wr = fwrite(outbuf, 1, outlen, outfile)); + size_t outlen = static_cast(bufp - outbuf); + outfoffset += static_cast(wr = fwrite(outbuf, 1, outlen, outfile)); if (wr != outlen) { UnicodeString str(strerror(errno)); initMsg(pname); @@ -1072,7 +1072,7 @@ static void usage(const char *pname, int ecode) { msg = ures_getStringByKey(gBundle, ecode ? "lcUsageWord" : "ucUsageWord", &msgLen, &err); - UnicodeString upname(pname, (int32_t)(uprv_strlen(pname) + 1)); + UnicodeString upname(pname, static_cast(uprv_strlen(pname) + 1)); UnicodeString mname(msg, msgLen + 1); res = u_wmsg(fp, "usage", mname.getBuffer(), upname.getBuffer()); @@ -1180,7 +1180,7 @@ main(int argc, char **argv) iter++; if (iter != end) { bufsz = atoi(*iter); - if ((int) bufsz <= 0) { + if (static_cast(bufsz) <= 0) { initMsg(pname); UnicodeString str(*iter); initMsg(pname); diff --git a/icu4c/source/i18n/alphaindex.cpp b/icu4c/source/i18n/alphaindex.cpp index 1b49d3b54434..e220e60e95e9 100644 --- a/icu4c/source/i18n/alphaindex.cpp +++ b/icu4c/source/i18n/alphaindex.cpp @@ -379,16 +379,16 @@ const UnicodeString &fixLabel(const UnicodeString ¤t, UnicodeString &temp) char16_t rest = current.charAt(BASE_LENGTH); if (0x2800 < rest && rest <= 0x28FF) { // stroke count int32_t count = rest-0x2800; - temp.setTo((char16_t)(0x30 + count % 10)); + temp.setTo(static_cast(0x30 + count % 10)); if (count >= 10) { count /= 10; - temp.insert(0, (char16_t)(0x30 + count % 10)); + temp.insert(0, static_cast(0x30 + count % 10)); if (count >= 10) { count /= 10; - temp.insert(0, (char16_t)(0x30 + count)); + temp.insert(0, static_cast(0x30 + count)); } } - return temp.append((char16_t)0x5283); + return temp.append(static_cast(0x5283)); } return temp.setTo(current, BASE_LENGTH); } @@ -402,7 +402,7 @@ UBool hasMultiplePrimaryWeights( UBool seenPrimary = false; for (int32_t i = 0; i < ces.size(); ++i) { int64_t ce = ces.elementAti(i); - uint32_t p = (uint32_t)(ce >> 32); + uint32_t p = static_cast(ce >> 32); if (p > variableTop) { // not primary ignorable if (seenPrimary) { @@ -494,10 +494,10 @@ BucketList *AlphabeticIndex::createBucketList(UErrorCode &errorCode) const { // Remember ASCII and Pinyin buckets for Pinyin redirects. char16_t c; if (current.length() == 1 && 0x41 <= (c = current.charAt(0)) && c <= 0x5A) { // A-Z - asciiBuckets[c - 0x41] = (Bucket *)bucketList->lastElement(); + asciiBuckets[c - 0x41] = static_cast(bucketList->lastElement()); } else if (current.length() == BASE_LENGTH + 1 && current.startsWith(BASE, BASE_LENGTH) && 0x41 <= (c = current.charAt(BASE_LENGTH)) && c <= 0x5A) { - pinyinBuckets[c - 0x41] = (Bucket *)bucketList->lastElement(); + pinyinBuckets[c - 0x41] = static_cast(bucketList->lastElement()); hasPinyin = true; } // Check for multiple primary weights. @@ -522,7 +522,7 @@ BucketList *AlphabeticIndex::createBucketList(UErrorCode &errorCode) const { // For example, after ... Q R S Sch we add Sch\uFFFF->S // and after ... Q R S Sch Sch\uFFFF St we add St\uFFFF->S. bucket.adoptInsteadAndCheckErrorCode(new Bucket(emptyString_, - UnicodeString(current).append((char16_t)0xFFFF), + UnicodeString(current).append(static_cast(0xFFFF)), U_ALPHAINDEX_NORMAL), errorCode); if (U_FAILURE(errorCode)) { @@ -880,7 +880,7 @@ void AlphabeticIndex::init(const Locale *locale, UErrorCode &status) { return; } - inflowLabel_.setTo((char16_t)0x2026); // Ellipsis + inflowLabel_.setTo(static_cast(0x2026)); // Ellipsis overflowLabel_ = inflowLabel_; underflowLabel_ = inflowLabel_; diff --git a/icu4c/source/i18n/anytrans.cpp b/icu4c/source/i18n/anytrans.cpp index 4972b6873332..c558a29d0005 100644 --- a/icu4c/source/i18n/anytrans.cpp +++ b/icu4c/source/i18n/anytrans.cpp @@ -286,7 +286,7 @@ Transliterator* AnyTransliterator::getTransliterator(UScriptCode source) const { Transliterator* t = nullptr; { Mutex m(nullptr); - t = (Transliterator*) uhash_iget(cache, (int32_t) source); + t = static_cast(uhash_iget(cache, static_cast(source))); } if (t == nullptr) { UErrorCode ec = U_ZERO_ERROR; @@ -312,10 +312,10 @@ Transliterator* AnyTransliterator::getTransliterator(UScriptCode source) const { Transliterator *rt = nullptr; { Mutex m(nullptr); - rt = static_cast (uhash_iget(cache, (int32_t) source)); + rt = static_cast(uhash_iget(cache, static_cast(source))); if (rt == nullptr) { // Common case, no race to cache this new transliterator. - uhash_iput(cache, (int32_t) source, t, &ec); + uhash_iput(cache, static_cast(source), t, &ec); } else { // Race case, some other thread beat us to caching this transliterator. Transliterator *temp = rt; @@ -340,7 +340,7 @@ static UScriptCode scriptNameToCode(const UnicodeString& name) { UBool isInvariant = uprv_isInvariantUString(name.getBuffer(), nameLen); if (isInvariant) { - name.extract(0, nameLen, buf, (int32_t)sizeof(buf), US_INV); + name.extract(0, nameLen, buf, static_cast(sizeof(buf)), US_INV); buf[127] = 0; // Make sure that we nullptr terminate the string. } if (!isInvariant || uscript_getCode(buf, &code, 1, &ec) != 1 || U_FAILURE(ec)) diff --git a/icu4c/source/i18n/astro.cpp b/icu4c/source/i18n/astro.cpp index f91f6fe08978..37a5b77a8771 100644 --- a/icu4c/source/i18n/astro.cpp +++ b/icu4c/source/i18n/astro.cpp @@ -307,7 +307,7 @@ UDate CalendarAstronomer::getTime() { */ double CalendarAstronomer::getJulianDay() { if (isINVALID(julianDay)) { - julianDay = (fTime - (double)JULIAN_EPOCH_MS) / (double)DAY_MS; + julianDay = (fTime - JULIAN_EPOCH_MS) / static_cast(DAY_MS); } return julianDay; } diff --git a/icu4c/source/i18n/basictz.cpp b/icu4c/source/i18n/basictz.cpp index 3674e4de4a4b..a2c1ec7fb914 100644 --- a/icu4c/source/i18n/basictz.cpp +++ b/icu4c/source/i18n/basictz.cpp @@ -370,7 +370,7 @@ BasicTimeZone::getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, // Mark rules which does not need to be processed for (i = 0; i < ruleCount; i++) { - r = (TimeZoneRule*)orgRules->elementAt(i); + r = static_cast(orgRules->elementAt(i)); avail = r->getNextStart(start, res_initial->getRawOffset(), res_initial->getDSTSavings(), false, time); done[i] = !avail; } @@ -393,7 +393,7 @@ BasicTimeZone::getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, const TimeZoneRule *toRule = tzt.getTo(); for (i = 0; i < ruleCount; i++) { - r = (TimeZoneRule*)orgRules->elementAt(i); + r = static_cast(orgRules->elementAt(i)); if (*r == *toRule) { break; } @@ -533,8 +533,8 @@ BasicTimeZone::getOffsetFromLocal(UDate /*date*/, UTimeZoneLocalOption /*nonExis void BasicTimeZone::getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt, int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const { - getOffsetFromLocal(date, (UTimeZoneLocalOption)nonExistingTimeOpt, - (UTimeZoneLocalOption)duplicatedTimeOpt, rawOffset, dstOffset, status); + getOffsetFromLocal(date, static_cast(nonExistingTimeOpt), + static_cast(duplicatedTimeOpt), rawOffset, dstOffset, status); } U_NAMESPACE_END diff --git a/icu4c/source/i18n/bocsu.cpp b/icu4c/source/i18n/bocsu.cpp index 585415643bab..23101696aec9 100644 --- a/icu4c/source/i18n/bocsu.cpp +++ b/icu4c/source/i18n/bocsu.cpp @@ -33,22 +33,22 @@ static uint8_t * u_writeDiff(int32_t diff, uint8_t *p) { if(diff>=SLOPE_REACH_NEG_1) { if(diff<=SLOPE_REACH_POS_1) { - *p++=(uint8_t)(SLOPE_MIDDLE+diff); + *p++ = static_cast(SLOPE_MIDDLE + diff); } else if(diff<=SLOPE_REACH_POS_2) { - *p++=(uint8_t)(SLOPE_START_POS_2+(diff/SLOPE_TAIL_COUNT)); - *p++=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); + *p++ = static_cast(SLOPE_START_POS_2 + (diff / SLOPE_TAIL_COUNT)); + *p++ = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); } else if(diff<=SLOPE_REACH_POS_3) { - p[2]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); + p[2] = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); diff/=SLOPE_TAIL_COUNT; - p[1]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); - *p=(uint8_t)(SLOPE_START_POS_3+(diff/SLOPE_TAIL_COUNT)); + p[1] = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); + *p = static_cast(SLOPE_START_POS_3 + (diff / SLOPE_TAIL_COUNT)); p+=3; } else { - p[3]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); + p[3] = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); diff/=SLOPE_TAIL_COUNT; - p[2]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); + p[2] = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); diff/=SLOPE_TAIL_COUNT; - p[1]=(uint8_t)(SLOPE_MIN+diff%SLOPE_TAIL_COUNT); + p[1] = static_cast(SLOPE_MIN + diff % SLOPE_TAIL_COUNT); *p=SLOPE_MAX; p+=4; } @@ -57,22 +57,22 @@ u_writeDiff(int32_t diff, uint8_t *p) { if(diff>=SLOPE_REACH_NEG_2) { NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - *p++=(uint8_t)(SLOPE_START_NEG_2+diff); - *p++=(uint8_t)(SLOPE_MIN+m); + *p++ = static_cast(SLOPE_START_NEG_2 + diff); + *p++ = static_cast(SLOPE_MIN + m); } else if(diff>=SLOPE_REACH_NEG_3) { NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - p[2]=(uint8_t)(SLOPE_MIN+m); + p[2] = static_cast(SLOPE_MIN + m); NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - p[1]=(uint8_t)(SLOPE_MIN+m); - *p=(uint8_t)(SLOPE_START_NEG_3+diff); + p[1] = static_cast(SLOPE_MIN + m); + *p = static_cast(SLOPE_START_NEG_3 + diff); p+=3; } else { NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - p[3]=(uint8_t)(SLOPE_MIN+m); + p[3] = static_cast(SLOPE_MIN + m); NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - p[2]=(uint8_t)(SLOPE_MIN+m); + p[2] = static_cast(SLOPE_MIN + m); NEGDIVMOD(diff, SLOPE_TAIL_COUNT, m); - p[1]=(uint8_t)(SLOPE_MIN+m); + p[1] = static_cast(SLOPE_MIN + m); *p=SLOPE_MIN; p+=4; } diff --git a/icu4c/source/i18n/calendar.cpp b/icu4c/source/i18n/calendar.cpp index 82936b4d16a4..f74446b43765 100644 --- a/icu4c/source/i18n/calendar.cpp +++ b/icu4c/source/i18n/calendar.cpp @@ -232,7 +232,7 @@ const SharedCalendar *LocaleCacheKey::createObject( static ECalType getCalendarType(const char *s) { for (int i = 0; gCalTypes[i] != nullptr; i++) { if (uprv_stricmp(s, gCalTypes[i]) == 0) { - return (ECalType)i; + return static_cast(i); } } return CALTYPE_UNKNOWN; @@ -407,7 +407,7 @@ class BasicCalendarFactory : public LocaleKeyFactory { { if (U_SUCCESS(status)) { for(int32_t i=0;gCalTypes[i] != nullptr;i++) { - UnicodeString id((char16_t)0x40); /* '@' a variant character */ + UnicodeString id(static_cast(0x40)); /* '@' a variant character */ id.append(UNICODE_STRING_SIMPLE("calendar=")); id.append(UnicodeString(gCalTypes[i], -1, US_INV)); result.put(id, (void*)this, status); @@ -433,7 +433,7 @@ class BasicCalendarFactory : public LocaleKeyFactory { lkey->canonicalLocale(canLoc); char keyword[ULOC_FULLNAME_CAPACITY]; - curLoc.getKeywordValue("calendar", keyword, (int32_t) sizeof(keyword), status); + curLoc.getKeywordValue("calendar", keyword, static_cast(sizeof(keyword)), status); #ifdef U_DEBUG_CALSVC fprintf(stderr, "BasicCalendarFactory::create() - cur %s, can %s\n", (const char*)curLoc.getName(), (const char*)canLoc.getName()); @@ -476,7 +476,7 @@ class DefaultCalendarFactory : public ICUResourceBundleFactory { if (ret == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { - ret->append((char16_t)0x40); // '@' is a variant character + ret->append(static_cast(0x40)); // '@' is a variant character ret->append(UNICODE_STRING("calendar=", 9)); ret->append(UnicodeString(gCalTypes[getCalendarTypeForLocale(loc.getName())], -1, US_INV)); } @@ -700,7 +700,7 @@ fIsTimeSet(false), fAreFieldsSet(false), fAreAllFieldsSet(false), fAreFieldsVirtuallySet(false), -fNextStamp((int32_t)kMinimumUserStamp), +fNextStamp(static_cast(kMinimumUserStamp)), fTime(0), fLenient(true), fZone(nullptr), @@ -728,7 +728,7 @@ fIsTimeSet(false), fAreFieldsSet(false), fAreAllFieldsSet(false), fAreFieldsVirtuallySet(false), -fNextStamp((int32_t)kMinimumUserStamp), +fNextStamp(static_cast(kMinimumUserStamp)), fTime(0), fLenient(true), fZone(nullptr), @@ -763,7 +763,7 @@ fIsTimeSet(false), fAreFieldsSet(false), fAreAllFieldsSet(false), fAreFieldsVirtuallySet(false), -fNextStamp((int32_t)kMinimumUserStamp), +fNextStamp(static_cast(kMinimumUserStamp)), fTime(0), fLenient(true), fZone(nullptr), @@ -1121,7 +1121,7 @@ Calendar::getTimeInMillis(UErrorCode& status) const return 0.0; if ( ! fIsTimeSet) - ((Calendar*)this)->updateTime(status); + const_cast(this)->updateTime(status); /* Test for buffer overflows */ if(U_FAILURE(status)) { @@ -1191,7 +1191,7 @@ Calendar::get(UCalendarDateFields field, UErrorCode& status) const // field values are only computed when actually requested; for more on when computation // of various things happens, see the "data flow in Calendar" description at the top // of this file - if (U_SUCCESS(status)) ((Calendar*)this)->complete(status); // Cast away const + if (U_SUCCESS(status)) const_cast(this)->complete(status); // Cast away const return U_SUCCESS(status) ? fFields[field] : 0; } @@ -1321,7 +1321,7 @@ Calendar::isSet(UCalendarDateFields field) const int32_t Calendar::newestStamp(UCalendarDateFields first, UCalendarDateFields last, int32_t bestStampSoFar) const { int32_t bestStamp = bestStampSoFar; - for (int32_t i=(int32_t)first; i<=(int32_t)last; ++i) { + for (int32_t i = static_cast(first); i <= static_cast(last); ++i) { if (fStamp[i] > bestStamp) { bestStamp = fStamp[i]; } @@ -1532,9 +1532,9 @@ uint8_t Calendar::julianDayToDayOfWeek(int32_t julian) { // If julian is negative, then julian%7 will be negative, so we adjust // accordingly. We add 1 because Julian day 0 is Monday. - int8_t dayOfWeek = (int8_t) ((julian + 1LL) % 7); + int8_t dayOfWeek = static_cast((julian + 1LL) % 7); - uint8_t result = (uint8_t)(dayOfWeek + ((dayOfWeek < 0) ? (7+UCAL_SUNDAY ) : UCAL_SUNDAY)); + uint8_t result = static_cast(dayOfWeek + ((dayOfWeek < 0) ? (7 + UCAL_SUNDAY) : UCAL_SUNDAY)); return result; } @@ -1731,7 +1731,7 @@ void Calendar::handleComputeFields(int32_t /* julianDay */, UErrorCode& status) void Calendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { - roll((UCalendarDateFields)field, amount, status); + roll(static_cast(field), amount, status); } void Calendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) UPRV_NO_SANITIZE_UNDEFINED { @@ -2106,7 +2106,7 @@ void Calendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& statu void Calendar::add(EDateFields field, int32_t amount, UErrorCode& status) { - Calendar::add((UCalendarDateFields)field, amount, status); + Calendar::add(static_cast(field), amount, status); } // ------------------------------------- @@ -2283,7 +2283,7 @@ void Calendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status // to roll over/back the date. For now, this only happens // in Samoa (Pacific/Apia) on Dec 30, 2011. See ticket:9452. int32_t adjAmount = prevOffset - newOffset; - adjAmount = adjAmount >= 0 ? adjAmount % (int32_t)kOneDay : -(-adjAmount % (int32_t)kOneDay); + adjAmount = adjAmount >= 0 ? adjAmount % static_cast(kOneDay) : -(-adjAmount % static_cast(kOneDay)); if (adjAmount != 0) { setTimeInMillis(t + adjAmount, status); newWallTime = get(UCAL_MILLISECONDS_IN_DAY, status); @@ -2319,7 +2319,7 @@ void Calendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status // ------------------------------------- int32_t Calendar::fieldDifference(UDate when, EDateFields field, UErrorCode& status) { - return fieldDifference(when, (UCalendarDateFields) field, status); + return fieldDifference(when, static_cast(field), status); } int32_t Calendar::fieldDifference(UDate targetMs, UCalendarDateFields field, UErrorCode& ec) { @@ -2392,7 +2392,7 @@ int32_t Calendar::fieldDifference(UDate targetMs, UCalendarDateFields field, UEr break; } else { min = max; - max = (int32_t)((uint32_t)(max) << 1); + max = static_cast(static_cast(max) << 1); if (max == 0) { // Field difference too large to fit into int32_t #if defined (U_DEBUG_CAL) @@ -2546,7 +2546,7 @@ Calendar::setFirstDayOfWeek(UCalendarDaysOfWeek value) UPRV_NO_SANITIZE_UNDEFINE Calendar::EDaysOfWeek Calendar::getFirstDayOfWeek() const { - return (Calendar::EDaysOfWeek)fFirstDayOfWeek; + return static_cast(fFirstDayOfWeek); } UCalendarDaysOfWeek @@ -2657,7 +2657,7 @@ UBool Calendar::isWeekend() const { UErrorCode status = U_ZERO_ERROR; - UCalendarDaysOfWeek dayOfWeek = (UCalendarDaysOfWeek)get(UCAL_DAY_OF_WEEK, status); + UCalendarDaysOfWeek dayOfWeek = static_cast(get(UCAL_DAY_OF_WEEK, status)); UCalendarWeekdayType dayType = getDayOfWeekType(dayOfWeek, status); if (U_SUCCESS(status)) { switch (dayType) { @@ -2690,7 +2690,7 @@ Calendar::isWeekend() const int32_t Calendar::getMinimum(EDateFields field) const { - return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MINIMUM); + return getLimit(static_cast(field), UCAL_LIMIT_MINIMUM); } int32_t @@ -2703,7 +2703,7 @@ Calendar::getMinimum(UCalendarDateFields field) const int32_t Calendar::getMaximum(EDateFields field) const { - return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MAXIMUM); + return getLimit(static_cast(field), UCAL_LIMIT_MAXIMUM); } int32_t @@ -2716,7 +2716,7 @@ Calendar::getMaximum(UCalendarDateFields field) const int32_t Calendar::getGreatestMinimum(EDateFields field) const { - return getLimit((UCalendarDateFields)field,UCAL_LIMIT_GREATEST_MINIMUM); + return getLimit(static_cast(field), UCAL_LIMIT_GREATEST_MINIMUM); } int32_t @@ -2729,7 +2729,7 @@ Calendar::getGreatestMinimum(UCalendarDateFields field) const int32_t Calendar::getLeastMaximum(EDateFields field) const { - return getLimit((UCalendarDateFields) field,UCAL_LIMIT_LEAST_MAXIMUM); + return getLimit(static_cast(field), UCAL_LIMIT_LEAST_MAXIMUM); } int32_t @@ -2742,7 +2742,7 @@ Calendar::getLeastMaximum(UCalendarDateFields field) const int32_t Calendar::getActualMinimum(EDateFields field, UErrorCode& status) const { - return getActualMinimum((UCalendarDateFields) field, status); + return getActualMinimum(static_cast(field), status); } int32_t Calendar::getLimit(UCalendarDateFields field, ELimitType limitType) const { @@ -2847,9 +2847,9 @@ Calendar::inDaylightTime(UErrorCode& status) const } // Force an update of the state of the Calendar. - ((Calendar*)this)->complete(status); // cast away const + const_cast(this)->complete(status); // cast away const - return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : false); + return static_cast(U_SUCCESS(status) ? internalGet(UCAL_DST_OFFSET) != 0 : false); } bool @@ -2912,7 +2912,7 @@ void Calendar::validateFields(UErrorCode &status) { } for (int32_t field = 0; U_SUCCESS(status) && (field < UCAL_FIELD_COUNT); field++) { if (fStamp[field] >= kMinimumUserStamp) { - validateField((UCalendarDateFields)field, status); + validateField(static_cast(field), status); } } } @@ -3046,7 +3046,7 @@ UCalendarDateFields Calendar::resolveFields(const UFieldResolutionTable* precede ; } } - return (UCalendarDateFields)bestField; + return static_cast(bestField); } const UFieldResolutionTable Calendar::kDatePrecedence[] = @@ -3147,7 +3147,7 @@ void Calendar::computeTime(UErrorCode& status) { // time and call clear(MONTH) to reset the MONTH to January. This // is legacy behavior. Without this, clear(MONTH) has no effect, // since the internally set JULIAN_DAY is used. - if (fStamp[UCAL_MILLISECONDS_IN_DAY] >= ((int32_t)kMinimumUserStamp) && + if (fStamp[UCAL_MILLISECONDS_IN_DAY] >= static_cast(kMinimumUserStamp) && newestStamp(UCAL_AM_PM, UCAL_MILLISECOND, kUnset) <= fStamp[UCAL_MILLISECONDS_IN_DAY]) { millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY); } else { @@ -3155,7 +3155,8 @@ void Calendar::computeTime(UErrorCode& status) { } UDate t = 0; - if (fStamp[UCAL_ZONE_OFFSET] >= ((int32_t)kMinimumUserStamp) || fStamp[UCAL_DST_OFFSET] >= ((int32_t)kMinimumUserStamp)) { + if (fStamp[UCAL_ZONE_OFFSET] >= static_cast(kMinimumUserStamp) || + fStamp[UCAL_DST_OFFSET] >= static_cast(kMinimumUserStamp)) { t = millis + millisInDay - internalGet(UCAL_ZONE_OFFSET) - internalGet(UCAL_DST_OFFSET); } else { // Compute the time zone offset and DST offset. There are two potential @@ -3370,7 +3371,7 @@ int32_t Calendar::computeJulianDay(UErrorCode &status) // to January. This is legacy behavior. Without this, // clear(MONTH) has no effect, since the internally set JULIAN_DAY // is used. - if (fStamp[UCAL_JULIAN_DAY] >= (int32_t)kMinimumUserStamp) { + if (fStamp[UCAL_JULIAN_DAY] >= static_cast(kMinimumUserStamp)) { int32_t bestStamp = newestStamp(UCAL_ERA, UCAL_DAY_OF_WEEK_IN_MONTH, kUnset); bestStamp = newestStamp(UCAL_YEAR_WOY, UCAL_EXTENDED_YEAR, bestStamp); bestStamp = newestStamp(UCAL_ORDINAL_MONTH, UCAL_ORDINAL_MONTH, bestStamp); @@ -4167,11 +4168,11 @@ Calendar::setWeekData(const Locale& desiredLocale, const char *type, UErrorCode& && 1 <= weekDataArr[1] && weekDataArr[1] <= 7 && 1 <= weekDataArr[2] && weekDataArr[2] <= 7 && 1 <= weekDataArr[4] && weekDataArr[4] <= 7) { - fFirstDayOfWeek = (UCalendarDaysOfWeek)weekDataArr[0]; - fMinimalDaysInFirstWeek = (uint8_t)weekDataArr[1]; - fWeekendOnset = (UCalendarDaysOfWeek)weekDataArr[2]; + fFirstDayOfWeek = static_cast(weekDataArr[0]); + fMinimalDaysInFirstWeek = static_cast(weekDataArr[1]); + fWeekendOnset = static_cast(weekDataArr[2]); fWeekendOnsetMillis = weekDataArr[3]; - fWeekendCease = (UCalendarDaysOfWeek)weekDataArr[4]; + fWeekendCease = static_cast(weekDataArr[4]); fWeekendCeaseMillis = weekDataArr[5]; } else { status = U_INVALID_FORMAT_ERROR; @@ -4269,7 +4270,7 @@ Calendar::recalculateStamp() { void Calendar::internalSet(EDateFields field, int32_t value) { - internalSet((UCalendarDateFields) field, value); + internalSet(static_cast(field), value); } int32_t Calendar::internalGetMonth(UErrorCode& status) const { diff --git a/icu4c/source/i18n/chnsecal.cpp b/icu4c/source/i18n/chnsecal.cpp index c3a57ea1f190..050994fcbaf6 100644 --- a/icu4c/source/i18n/chnsecal.cpp +++ b/icu4c/source/i18n/chnsecal.cpp @@ -343,7 +343,7 @@ int64_t ChineseCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, U status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } - month = (int32_t)m; + month = static_cast(m); } const Setting setting = getSetting(status); @@ -422,7 +422,7 @@ void ChineseCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& * @stable ICU 2.8 */ void ChineseCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) { - add((UCalendarDateFields)field, amount, status); + add(static_cast(field), amount, status); } namespace { @@ -461,7 +461,7 @@ struct RollMonthInfo rollMonth(const TimeZone* timeZone, int32_t amount, int32_t // no leap month between month 0 and month m; // otherwise it will be the start of month 1. int prevMoon = output.thisMoon - - (int) (CalendarAstronomer::SYNODIC_MONTH * (month - 0.5)); + static_cast(CalendarAstronomer::SYNODIC_MONTH * (month - 0.5)); prevMoon = newMoonNear(timeZone, prevMoon, true, status); if (U_FAILURE(status)) { return output; @@ -522,7 +522,7 @@ void ChineseCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode } void ChineseCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { - roll((UCalendarDateFields)field, amount, status); + roll(static_cast(field), amount, status); } @@ -548,16 +548,16 @@ double daysToMillis(const TimeZone* timeZone, double days, UErrorCode& status) { if (U_FAILURE(status)) { return 0; } - double millis = days * (double)kOneDay; + double millis = days * kOneDay; if (timeZone != nullptr) { int32_t rawOffset, dstOffset; timeZone->getOffset(millis, false, rawOffset, dstOffset, status); if (U_FAILURE(status)) { return 0; } - return millis - (double)(rawOffset + dstOffset); + return millis - static_cast(rawOffset + dstOffset); } - return millis - (double)CHINA_OFFSET; + return millis - static_cast(CHINA_OFFSET); } /** @@ -576,9 +576,9 @@ double millisToDays(const TimeZone* timeZone, double millis, UErrorCode& status) if (U_FAILURE(status)) { return 0; } - return ClockMath::floorDivide(millis + (double)(rawOffset + dstOffset), kOneDay); + return ClockMath::floorDivide(millis + static_cast(rawOffset + dstOffset), kOneDay); } - return ClockMath::floorDivide(millis + (double)CHINA_OFFSET, kOneDay); + return ClockMath::floorDivide(millis + static_cast(CHINA_OFFSET), kOneDay); } //------------------------------------------------------------------ @@ -629,7 +629,7 @@ int32_t winterSolstice(const icu::ChineseCalendar::Setting& setting, status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } - cacheValue = (int32_t) days; + cacheValue = static_cast(days); CalendarCache::put(setting.winterSolsticeCache, gyear, cacheValue, status); } if(U_FAILURE(status)) { @@ -657,11 +657,11 @@ int32_t newMoonNear(const TimeZone* timeZone, double days, UBool after, UErrorCo if (U_FAILURE(status)) { return 0; } - return (int32_t) millisToDays( + return static_cast(millisToDays( timeZone, CalendarAstronomer(ms) .getMoonTime(CalendarAstronomer::NEW_MOON(), after), - status); + status)); } /** @@ -673,7 +673,7 @@ int32_t newMoonNear(const TimeZone* timeZone, double days, UBool after, UErrorCo */ int32_t synodicMonthsBetween(int32_t day1, int32_t day2) { double roundme = ((day2 - day1) / CalendarAstronomer::SYNODIC_MONTH); - return (int32_t) (roundme + (roundme >= 0 ? .5 : -.5)); + return static_cast(roundme + (roundme >= 0 ? .5 : -.5)); } /** @@ -692,7 +692,7 @@ int32_t majorSolarTerm(const TimeZone* timeZone, int32_t days, UErrorCode& statu if (U_FAILURE(status)) { return 0; } - int32_t term = ( ((int32_t)(6 * CalendarAstronomer(ms) + int32_t term = ((static_cast(6 * CalendarAstronomer(ms) .getSunLongitude() / CalendarAstronomer::PI)) + 2 ) % 12; if (U_FAILURE(status)) { return 0; @@ -1153,7 +1153,7 @@ int32_t ChineseCalendar::internalGetMonth(UErrorCode& status) const { return 0; } - ChineseCalendar *nonConstThis = (ChineseCalendar*)this; // cast away const + ChineseCalendar* nonConstThis = const_cast(this); // cast away const nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, temp->get(UCAL_IS_LEAP_MONTH, status)); int32_t month = temp->get(UCAL_MONTH, status); if (U_FAILURE(status)) { diff --git a/icu4c/source/i18n/choicfmt.cpp b/icu4c/source/i18n/choicfmt.cpp index 96e73fabcfa7..6f44b9504d06 100644 --- a/icu4c/source/i18n/choicfmt.cpp +++ b/icu4c/source/i18n/choicfmt.cpp @@ -380,7 +380,7 @@ ChoiceFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& status) const { - return format((double) number, appendTo, status); + return format(static_cast(number), appendTo, status); } // ------------------------------------- @@ -392,7 +392,7 @@ ChoiceFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& status) const { - return format((double) number, appendTo, status); + return format(static_cast(number), appendTo, status); } // ------------------------------------- diff --git a/icu4c/source/i18n/coleitr.cpp b/icu4c/source/i18n/coleitr.cpp index be0a8e4690f9..5ae15ae5a728 100644 --- a/icu4c/source/i18n/coleitr.cpp +++ b/icu4c/source/i18n/coleitr.cpp @@ -127,8 +127,8 @@ int32_t CollationElementIterator::next(UErrorCode& status) int64_t ce = iter_->nextCE(status); if (ce == Collation::NO_CE) { return NULLORDER; } // Turn the 64-bit CE into two old-style 32-bit CEs, without quaternary bits. - uint32_t p = (uint32_t)(ce >> 32); - uint32_t lower32 = (uint32_t)ce; + uint32_t p = static_cast(ce >> 32); + uint32_t lower32 = static_cast(ce); uint32_t firstHalf = getFirstHalf(p, lower32); uint32_t secondHalf = getSecondHalf(p, lower32); if (secondHalf != 0) { @@ -199,8 +199,8 @@ int32_t CollationElementIterator::previous(UErrorCode& status) int64_t ce = iter_->previousCE(*offsets_, status); if (ce == Collation::NO_CE) { return NULLORDER; } // Turn the 64-bit CE into two old-style 32-bit CEs, without quaternary bits. - uint32_t p = (uint32_t)(ce >> 32); - uint32_t lower32 = (uint32_t)ce; + uint32_t p = static_cast(ce >> 32); + uint32_t lower32 = static_cast(ce); uint32_t firstHalf = getFirstHalf(p, lower32); uint32_t secondHalf = getSecondHalf(p, lower32); if (secondHalf != 0) { @@ -309,7 +309,7 @@ void CollationElementIterator::setText(CharacterIterator& source, int32_t CollationElementIterator::strengthOrder(int32_t order) const { - UColAttributeValue s = (UColAttributeValue)rbc_->settings->getStrength(); + UColAttributeValue s = static_cast(rbc_->settings->getStrength()); // Mask off the unwanted differences. if (s == UCOL_PRIMARY) { order &= 0xffff0000; @@ -410,8 +410,8 @@ class MaxExpSink : public ContractionsAndExpansions::CESink { } // last "half" of the last CE int64_t ce = ces[length - 1]; - uint32_t p = (uint32_t)(ce >> 32); - uint32_t lower32 = (uint32_t)ce; + uint32_t p = static_cast(ce >> 32); + uint32_t lower32 = static_cast(ce); uint32_t lastHalf = getSecondHalf(p, lower32); if (lastHalf == 0) { lastHalf = getFirstHalf(p, lower32); @@ -419,8 +419,8 @@ class MaxExpSink : public ContractionsAndExpansions::CESink { } else { lastHalf |= 0xc0; // old-style continuation CE } - if (count > uhash_igeti(maxExpansions, (int32_t)lastHalf)) { - uhash_iputi(maxExpansions, (int32_t)lastHalf, count, &errorCode); + if (count > uhash_igeti(maxExpansions, static_cast(lastHalf))) { + uhash_iputi(maxExpansions, static_cast(lastHalf), count, &errorCode); } } diff --git a/icu4c/source/i18n/coll.cpp b/icu4c/source/i18n/coll.cpp index c83b29043612..1f8b8e417b04 100644 --- a/icu4c/source/i18n/coll.cpp +++ b/icu4c/source/i18n/coll.cpp @@ -413,7 +413,7 @@ void setAttributesFromKeywords(const Locale &loc, Collator &coll, UErrorCode &er errorCode = U_ILLEGAL_ARGUMENT_ERROR; return; } - coll.setMaxVariable((UColReorderCode)code, errorCode); + coll.setMaxVariable(static_cast(code), errorCode); } if (U_FAILURE(errorCode)) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; @@ -493,7 +493,7 @@ Collator::EComparisonResult Collator::compare(const UnicodeString& source, const UnicodeString& target) const { UErrorCode ec = U_ZERO_ERROR; - return (EComparisonResult)compare(source, target, ec); + return static_cast(compare(source, target, ec)); } // implement deprecated, previously abstract method @@ -502,7 +502,7 @@ Collator::EComparisonResult Collator::compare(const UnicodeString& source, int32_t length) const { UErrorCode ec = U_ZERO_ERROR; - return (EComparisonResult)compare(source, target, length, ec); + return static_cast(compare(source, target, length, ec)); } // implement deprecated, previously abstract method @@ -511,7 +511,7 @@ Collator::EComparisonResult Collator::compare(const char16_t* source, int32_t so const { UErrorCode ec = U_ZERO_ERROR; - return (EComparisonResult)compare(source, sourceLength, target, targetLength, ec); + return static_cast(compare(source, sourceLength, target, targetLength, ec)); } UCollationResult Collator::compare(UCharIterator &/*sIter*/, @@ -834,7 +834,7 @@ class CollationLocaleListEnumeration : public StringEnumeration { if(index < availableLocaleListCount) { result = availableLocaleList[index++].getName(); if(resultLength != nullptr) { - *resultLength = (int32_t)uprv_strlen(result); + *resultLength = static_cast(uprv_strlen(result)); } } else { if(resultLength != nullptr) { @@ -915,13 +915,13 @@ Collator::getFunctionalEquivalent(const char* keyword, const Locale& locale, Collator::ECollationStrength Collator::getStrength() const { UErrorCode intStatus = U_ZERO_ERROR; - return (ECollationStrength)getAttribute(UCOL_STRENGTH, intStatus); + return static_cast(getAttribute(UCOL_STRENGTH, intStatus)); } void Collator::setStrength(ECollationStrength newStrength) { UErrorCode intStatus = U_ZERO_ERROR; - setAttribute(UCOL_STRENGTH, (UColAttributeValue)newStrength, intStatus); + setAttribute(UCOL_STRENGTH, static_cast(newStrength), intStatus); } Collator & diff --git a/icu4c/source/i18n/collation.cpp b/icu4c/source/i18n/collation.cpp index 705ee12e23cc..61838e10fd2a 100644 --- a/icu4c/source/i18n/collation.cpp +++ b/icu4c/source/i18n/collation.cpp @@ -27,38 +27,38 @@ Collation::incTwoBytePrimaryByOffset(uint32_t basePrimary, UBool isCompressible, // Reserve the PRIMARY_COMPRESSION_LOW_BYTE and high byte if necessary. uint32_t primary; if(isCompressible) { - offset += ((int32_t)(basePrimary >> 16) & 0xff) - 4; - primary = (uint32_t)((offset % 251) + 4) << 16; + offset += (static_cast(basePrimary >> 16) & 0xff) - 4; + primary = static_cast((offset % 251) + 4) << 16; offset /= 251; } else { - offset += ((int32_t)(basePrimary >> 16) & 0xff) - 2; - primary = (uint32_t)((offset % 254) + 2) << 16; + offset += (static_cast(basePrimary >> 16) & 0xff) - 2; + primary = static_cast((offset % 254) + 2) << 16; offset /= 254; } // First byte, assume no further overflow. - return primary | ((basePrimary & 0xff000000) + (uint32_t)(offset << 24)); + return primary | ((basePrimary & 0xff000000) + static_cast(offset << 24)); } uint32_t Collation::incThreeBytePrimaryByOffset(uint32_t basePrimary, UBool isCompressible, int32_t offset) { // Extract the third byte, minus the minimum byte value, // plus the offset, modulo the number of usable byte values, plus the minimum. - offset += ((int32_t)(basePrimary >> 8) & 0xff) - 2; - uint32_t primary = (uint32_t)((offset % 254) + 2) << 8; + offset += (static_cast(basePrimary >> 8) & 0xff) - 2; + uint32_t primary = static_cast((offset % 254) + 2) << 8; offset /= 254; // Same with the second byte, // but reserve the PRIMARY_COMPRESSION_LOW_BYTE and high byte if necessary. if(isCompressible) { - offset += ((int32_t)(basePrimary >> 16) & 0xff) - 4; - primary |= (uint32_t)((offset % 251) + 4) << 16; + offset += (static_cast(basePrimary >> 16) & 0xff) - 4; + primary |= static_cast((offset % 251) + 4) << 16; offset /= 251; } else { - offset += ((int32_t)(basePrimary >> 16) & 0xff) - 2; - primary |= (uint32_t)((offset % 254) + 2) << 16; + offset += (static_cast(basePrimary >> 16) & 0xff) - 2; + primary |= static_cast((offset % 254) + 2) << 16; offset /= 254; } // First byte, assume no further overflow. - return primary | ((basePrimary & 0xff000000) + (uint32_t)(offset << 24)); + return primary | ((basePrimary & 0xff000000) + static_cast(offset << 24)); } uint32_t @@ -68,7 +68,7 @@ Collation::decTwoBytePrimaryByOneStep(uint32_t basePrimary, UBool isCompressible // Reserve the PRIMARY_COMPRESSION_LOW_BYTE and high byte if necessary. // Assume no further underflow for the first byte. U_ASSERT(0 < step && step <= 0x7f); - int32_t byte2 = ((int32_t)(basePrimary >> 16) & 0xff) - step; + int32_t byte2 = (static_cast(basePrimary >> 16) & 0xff) - step; if(isCompressible) { if(byte2 < 4) { byte2 += 251; @@ -80,7 +80,7 @@ Collation::decTwoBytePrimaryByOneStep(uint32_t basePrimary, UBool isCompressible basePrimary -= 0x1000000; } } - return (basePrimary & 0xff000000) | ((uint32_t)byte2 << 16); + return (basePrimary & 0xff000000) | (static_cast(byte2) << 16); } uint32_t @@ -88,14 +88,14 @@ Collation::decThreeBytePrimaryByOneStep(uint32_t basePrimary, UBool isCompressib // Extract the third byte, minus the minimum byte value, // minus the step, modulo the number of usable byte values, plus the minimum. U_ASSERT(0 < step && step <= 0x7f); - int32_t byte3 = ((int32_t)(basePrimary >> 8) & 0xff) - step; + int32_t byte3 = (static_cast(basePrimary >> 8) & 0xff) - step; if(byte3 >= 2) { - return (basePrimary & 0xffff0000) | ((uint32_t)byte3 << 8); + return (basePrimary & 0xffff0000) | (static_cast(byte3) << 8); } byte3 += 254; // Same with the second byte, // but reserve the PRIMARY_COMPRESSION_LOW_BYTE and high byte if necessary. - int32_t byte2 = ((int32_t)(basePrimary >> 16) & 0xff) - 1; + int32_t byte2 = (static_cast(basePrimary >> 16) & 0xff) - 1; if(isCompressible) { if(byte2 < 4) { byte2 = 0xfe; @@ -108,13 +108,13 @@ Collation::decThreeBytePrimaryByOneStep(uint32_t basePrimary, UBool isCompressib } } // First byte, assume no further underflow. - return (basePrimary & 0xff000000) | ((uint32_t)byte2 << 16) | ((uint32_t)byte3 << 8); + return (basePrimary & 0xff000000) | (static_cast(byte2) << 16) | (static_cast(byte3) << 8); } uint32_t Collation::getThreeBytePrimaryForOffsetData(UChar32 c, int64_t dataCE) { - uint32_t p = (uint32_t)(dataCE >> 32); // three-byte primary pppppp00 - int32_t lower32 = (int32_t)dataCE; // base code point b & step s: bbbbbbss (bit 7: isCompressible) + uint32_t p = static_cast(dataCE >> 32); // three-byte primary pppppp00 + int32_t lower32 = static_cast(dataCE); // base code point b & step s: bbbbbbss (bit 7: isCompressible) int32_t offset = (c - (lower32 >> 8)) * (lower32 & 0x7f); // delta * increment UBool isCompressible = (lower32 & 0x80) != 0; return Collation::incThreeBytePrimaryByOffset(p, isCompressible, offset); diff --git a/icu4c/source/i18n/collation.h b/icu4c/source/i18n/collation.h index 2062ef294673..5dcc0e19999e 100644 --- a/icu4c/source/i18n/collation.h +++ b/icu4c/source/i18n/collation.h @@ -317,7 +317,7 @@ class U_I18N_API Collation { return ce32 & 0xffffff00; } static inline int64_t ceFromLongPrimaryCE32(uint32_t ce32) { - return ((int64_t)(ce32 & 0xffffff00) << 32) | COMMON_SEC_AND_TER_CE; + return (static_cast(ce32 & 0xffffff00) << 32) | COMMON_SEC_AND_TER_CE; } static uint32_t makeLongSecondaryCE32(uint32_t lower32) { @@ -341,7 +341,7 @@ class U_I18N_API Collation { } static inline int32_t tagFromCE32(uint32_t ce32) { - return (int32_t)(ce32 & 0xf); + return static_cast(ce32 & 0xf); } static inline UBool hasCE32Tag(uint32_t ce32, int32_t tag) { @@ -387,7 +387,7 @@ class U_I18N_API Collation { * @see LATIN_EXPANSION_TAG */ static inline int64_t latinCE0FromCE32(uint32_t ce32) { - return ((int64_t)(ce32 & 0xff000000) << 32) | COMMON_SECONDARY_CE | ((ce32 & 0xff0000) >> 8); + return (static_cast(ce32 & 0xff000000) << 32) | COMMON_SECONDARY_CE | ((ce32 & 0xff0000) >> 8); } /** @@ -402,7 +402,7 @@ class U_I18N_API Collation { * Returns the data index from a special CE32. */ static inline int32_t indexFromCE32(uint32_t ce32) { - return (int32_t)(ce32 >> 13); + return static_cast(ce32 >> 13); } /** @@ -416,14 +416,14 @@ class U_I18N_API Collation { * Returns the digit value from a DIGIT_TAG ce32. */ static inline char digitFromCE32(uint32_t ce32) { - return (char)((ce32 >> 8) & 0xf); + return static_cast((ce32 >> 8) & 0xf); } /** Returns a 64-bit CE from a simple CE32 (not special). */ static inline int64_t ceFromSimpleCE32(uint32_t ce32) { // normal form ppppsstt -> pppp0000ss00tt00 // assert (ce32 & 0xff) < SPECIAL_CE32_LOW_BYTE - return ((int64_t)(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | ((ce32 & 0xff) << 8); + return (static_cast(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | ((ce32 & 0xff) << 8); } /** Returns a 64-bit CE from a simple/long-primary/long-secondary CE32. */ @@ -431,12 +431,12 @@ class U_I18N_API Collation { uint32_t tertiary = ce32 & 0xff; if(tertiary < SPECIAL_CE32_LOW_BYTE) { // normal form ppppsstt -> pppp0000ss00tt00 - return ((int64_t)(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (tertiary << 8); + return (static_cast(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (tertiary << 8); } else { ce32 -= tertiary; if((tertiary & 0xf) == LONG_PRIMARY_TAG) { // long-primary form ppppppC1 -> pppppp00050000500 - return ((int64_t)ce32 << 32) | COMMON_SEC_AND_TER_CE; + return (static_cast(ce32) << 32) | COMMON_SEC_AND_TER_CE; } else { // long-secondary form ssssttC2 -> 00000000sssstt00 // assert (tertiary & 0xf) == LONG_SECONDARY_TAG @@ -447,14 +447,14 @@ class U_I18N_API Collation { /** Creates a CE from a primary weight. */ static inline int64_t makeCE(uint32_t p) { - return ((int64_t)p << 32) | COMMON_SEC_AND_TER_CE; + return (static_cast(p) << 32) | COMMON_SEC_AND_TER_CE; } /** * Creates a CE from a primary weight, * 16-bit secondary/tertiary weights, and a 2-bit quaternary. */ static inline int64_t makeCE(uint32_t p, uint32_t s, uint32_t t, uint32_t q) { - return ((int64_t)p << 32) | (s << 16) | t | (q << 6); + return (static_cast(p) << 32) | (s << 16) | t | (q << 6); } /** diff --git a/icu4c/source/i18n/collationbuilder.cpp b/icu4c/source/i18n/collationbuilder.cpp index af631e6a52ef..54c41385755e 100644 --- a/icu4c/source/i18n/collationbuilder.cpp +++ b/icu4c/source/i18n/collationbuilder.cpp @@ -182,7 +182,7 @@ RuleBasedCollator::internalBuildTailoring(const UnicodeString &rules, // Set attributes after building the collator, // to keep the default settings consistent with the rule string. if(strength != UCOL_DEFAULT) { - setAttribute(UCOL_STRENGTH, (UColAttributeValue)strength, errorCode); + setAttribute(UCOL_STRENGTH, static_cast(strength), errorCode); } if(decompositionMode != UCOL_DEFAULT) { setAttribute(UCOL_NORMALIZATION_MODE, decompositionMode, errorCode); @@ -601,7 +601,7 @@ CollationBuilder::getSpecialResetPosition(const UnicodeString &str, ce = tempCEFromIndexAndStrength(index, strength); } else { U_ASSERT(strength == UCOL_PRIMARY); - uint32_t p = (uint32_t)(ce >> 32); + uint32_t p = static_cast(ce >> 32); int32_t pIndex = rootElements.findPrimary(p); UBool isCompressible = baseData->isCompressiblePrimary(p); p = rootElements.getPrimaryAfter(p, pIndex, isCompressible); @@ -700,7 +700,7 @@ CollationBuilder::addRelation(int32_t strength, const UnicodeString &prefix, int32_t index = findOrInsertNodeForCEs(strength, parserErrorReason, errorCode); U_ASSERT(cesLength > 0); int64_t ce = ces[cesLength - 1]; - if(strength == UCOL_PRIMARY && !isTempCE(ce) && (uint32_t)(ce >> 32) == 0) { + if (strength == UCOL_PRIMARY && !isTempCE(ce) && static_cast(ce >> 32) == 0) { // There is no primary gap between ignorables and the space-first-primary. errorCode = U_UNSUPPORTED_ERROR; parserErrorReason = "tailoring primary after ignorables not supported"; @@ -791,7 +791,7 @@ CollationBuilder::findOrInsertNodeForCEs(int32_t strength, const char *&parserEr } // root CE - if((uint8_t)(ce >> 56) == Collation::UNASSIGNED_IMPLICIT_BYTE) { + if (static_cast(ce >> 56) == Collation::UNASSIGNED_IMPLICIT_BYTE) { errorCode = U_UNSUPPORTED_ERROR; parserErrorReason = "tailoring relative to an unassigned code point not supported"; return 0; @@ -808,9 +808,9 @@ CollationBuilder::findOrInsertNodeForRootCE(int64_t ce, int32_t strength, UError // down to the requested level/strength. // Root CEs must have common=zero quaternary weights (for which we never insert any nodes). U_ASSERT((ce & 0xc0) == 0); - int32_t index = findOrInsertNodeForPrimary((uint32_t)(ce >> 32), errorCode); + int32_t index = findOrInsertNodeForPrimary(static_cast(ce >> 32), errorCode); if(strength >= UCOL_SECONDARY) { - uint32_t lower32 = (uint32_t)ce; + uint32_t lower32 = static_cast(ce); index = findOrInsertWeakNode(index, lower32 >> 16, UCOL_SECONDARY, errorCode); if(strength >= UCOL_TERTIARY) { index = findOrInsertWeakNode(index, lower32 & Collation::ONLY_TERTIARY_MASK, @@ -838,7 +838,7 @@ binarySearchForRootPrimaryNode(const int32_t *rootPrimaryIndexes, int32_t length for (;;) { int32_t i = (start + limit) / 2; int64_t node = nodes[rootPrimaryIndexes[i]]; - uint32_t nodePrimary = (uint32_t)(node >> 32); // weight32FromNode(node) + uint32_t nodePrimary = static_cast(node >> 32); // weight32FromNode(node) if (p == nodePrimary) { return i; } else if (p < nodePrimary) { @@ -898,7 +898,7 @@ CollationBuilder::findOrInsertWeakNode(int32_t index, uint32_t weight16, int32_t // Move the HAS_BEFORE3 flag from the parent node // to the new secondary common node. commonNode |= node & HAS_BEFORE3; - node &= ~(int64_t)HAS_BEFORE3; + node &= ~static_cast(HAS_BEFORE3); } nodes.setElementAt(node | hasThisLevelBefore, index); // Insert below-common-weight node. @@ -1045,10 +1045,10 @@ CollationBuilder::setCaseBits(const UnicodeString &nfdString, int64_t ce = baseCEs.getCE(i); if((ce >> 32) != 0) { ++numBasePrimaries; - uint32_t c = ((uint32_t)ce >> 14) & 3; + uint32_t c = (static_cast(ce) >> 14) & 3; U_ASSERT(c == 0 || c == 2); // lowercase or uppercase, no mixed case in any base CE if(numBasePrimaries < numTailoredPrimaries) { - cases |= (int64_t)c << ((numBasePrimaries - 1) * 2); + cases |= static_cast(c) << ((numBasePrimaries - 1) * 2); } else if(numBasePrimaries == numTailoredPrimaries) { lastCase = c; } else if(c != lastCase) { @@ -1061,7 +1061,7 @@ CollationBuilder::setCaseBits(const UnicodeString &nfdString, } } if(numBasePrimaries >= numTailoredPrimaries) { - cases |= (int64_t)lastCase << ((numTailoredPrimaries - 1) * 2); + cases |= static_cast(lastCase) << ((numTailoredPrimaries - 1) * 2); } } @@ -1652,7 +1652,7 @@ CollationBuilder::ceStrength(int64_t ce) { return isTempCE(ce) ? strengthFromTempCE(ce) : (ce & INT64_C(0xff00000000000000)) != 0 ? UCOL_PRIMARY : - ((uint32_t)ce & 0xff000000) != 0 ? UCOL_SECONDARY : + (static_cast(ce) & 0xff000000) != 0 ? UCOL_SECONDARY : ce != 0 ? UCOL_TERTIARY : UCOL_IDENTICAL; } diff --git a/icu4c/source/i18n/collationbuilder.h b/icu4c/source/i18n/collationbuilder.h index 22e24ddb813a..091d2c817815 100644 --- a/icu4c/source/i18n/collationbuilder.h +++ b/icu4c/source/i18n/collationbuilder.h @@ -185,9 +185,9 @@ class U_I18N_API CollationBuilder : public CollationRuleParser::Sink { // CE byte offsets, to ensure valid CE bytes, and case bits 11 INT64_C(0x4040000006002000) + // index bits 19..13 -> primary byte 1 = CE bits 63..56 (byte values 40..BF) - ((int64_t)(index & 0xfe000) << 43) + + (static_cast(index & 0xfe000) << 43) + // index bits 12..6 -> primary byte 2 = CE bits 55..48 (byte values 40..BF) - ((int64_t)(index & 0x1fc0) << 42) + + (static_cast(index & 0x1fc0) << 42) + // index bits 5..0 -> secondary byte 1 = CE bits 31..24 (byte values 06..45) ((index & 0x3f) << 24) + // strength bits 1..0 -> tertiary byte 1 = CE bits 13..8 (byte values 20..23) @@ -196,24 +196,24 @@ class U_I18N_API CollationBuilder : public CollationRuleParser::Sink { static inline int32_t indexFromTempCE(int64_t tempCE) { tempCE -= INT64_C(0x4040000006002000); return - ((int32_t)(tempCE >> 43) & 0xfe000) | - ((int32_t)(tempCE >> 42) & 0x1fc0) | - ((int32_t)(tempCE >> 24) & 0x3f); + (static_cast(tempCE >> 43) & 0xfe000) | + (static_cast(tempCE >> 42) & 0x1fc0) | + (static_cast(tempCE >> 24) & 0x3f); } static inline int32_t strengthFromTempCE(int64_t tempCE) { - return ((int32_t)tempCE >> 8) & 3; + return (static_cast(tempCE) >> 8) & 3; } static inline UBool isTempCE(int64_t ce) { - uint32_t sec = (uint32_t)ce >> 24; + uint32_t sec = static_cast(ce) >> 24; return 6 <= sec && sec <= 0x45; } static inline int32_t indexFromTempCE32(uint32_t tempCE32) { tempCE32 -= 0x40400620; return - ((int32_t)(tempCE32 >> 11) & 0xfe000) | - ((int32_t)(tempCE32 >> 10) & 0x1fc0) | - ((int32_t)(tempCE32 >> 8) & 0x3f); + (static_cast(tempCE32 >> 11) & 0xfe000) | + (static_cast(tempCE32 >> 10) & 0x1fc0) | + (static_cast(tempCE32 >> 8) & 0x3f); } static inline UBool isTempCE32(uint32_t ce32) { return @@ -242,13 +242,13 @@ class U_I18N_API CollationBuilder : public CollationRuleParser::Sink { static const int32_t IS_TAILORED = 8; static inline int64_t nodeFromWeight32(uint32_t weight32) { - return (int64_t)weight32 << 32; + return static_cast(weight32) << 32; } static inline int64_t nodeFromWeight16(uint32_t weight16) { - return (int64_t)weight16 << 48; + return static_cast(weight16) << 48; } static inline int64_t nodeFromPreviousIndex(int32_t previous) { - return (int64_t)previous << 28; + return static_cast(previous) << 28; } static inline int64_t nodeFromNextIndex(int32_t next) { return next << 8; @@ -258,19 +258,19 @@ class U_I18N_API CollationBuilder : public CollationRuleParser::Sink { } static inline uint32_t weight32FromNode(int64_t node) { - return (uint32_t)(node >> 32); + return static_cast(node >> 32); } static inline uint32_t weight16FromNode(int64_t node) { - return (uint32_t)(node >> 48) & 0xffff; + return static_cast(node >> 48) & 0xffff; } static inline int32_t previousIndexFromNode(int64_t node) { - return (int32_t)(node >> 28) & MAX_INDEX; + return static_cast(node >> 28) & MAX_INDEX; } static inline int32_t nextIndexFromNode(int64_t node) { - return ((int32_t)node >> 8) & MAX_INDEX; + return (static_cast(node) >> 8) & MAX_INDEX; } static inline int32_t strengthFromNode(int64_t node) { - return (int32_t)node & 3; + return static_cast(node) & 3; } static inline UBool nodeHasBefore2(int64_t node) { diff --git a/icu4c/source/i18n/collationcompare.cpp b/icu4c/source/i18n/collationcompare.cpp index d9048afc2796..b4c0a3b23829 100644 --- a/icu4c/source/i18n/collationcompare.cpp +++ b/icu4c/source/i18n/collationcompare.cpp @@ -47,7 +47,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat uint32_t leftPrimary; do { int64_t ce = left.nextCE(errorCode); - leftPrimary = (uint32_t)(ce >> 32); + leftPrimary = static_cast(ce >> 32); if(leftPrimary < variableTop && leftPrimary > Collation::MERGE_SEPARATOR_PRIMARY) { // Variable CE, shift it to quaternary level. // Ignore all following primary ignorables, and shift further variable CEs. @@ -57,7 +57,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat left.setCurrentCE(ce & INT64_C(0xffffffff00000000)); for(;;) { ce = left.nextCE(errorCode); - leftPrimary = (uint32_t)(ce >> 32); + leftPrimary = static_cast(ce >> 32); if(leftPrimary == 0) { left.setCurrentCE(0); } else { @@ -72,7 +72,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat uint32_t rightPrimary; do { int64_t ce = right.nextCE(errorCode); - rightPrimary = (uint32_t)(ce >> 32); + rightPrimary = static_cast(ce >> 32); if(rightPrimary < variableTop && rightPrimary > Collation::MERGE_SEPARATOR_PRIMARY) { // Variable CE, shift it to quaternary level. // Ignore all following primary ignorables, and shift further variable CEs. @@ -82,7 +82,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat right.setCurrentCE(ce & INT64_C(0xffffffff00000000)); for(;;) { ce = right.nextCE(errorCode); - rightPrimary = (uint32_t)(ce >> 32); + rightPrimary = static_cast(ce >> 32); if(rightPrimary == 0) { right.setCurrentCE(0); } else { @@ -116,12 +116,12 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat for(;;) { uint32_t leftSecondary; do { - leftSecondary = ((uint32_t)left.getCE(leftIndex++)) >> 16; + leftSecondary = static_cast(left.getCE(leftIndex++)) >> 16; } while(leftSecondary == 0); uint32_t rightSecondary; do { - rightSecondary = ((uint32_t)right.getCE(rightIndex++)) >> 16; + rightSecondary = static_cast(right.getCE(rightIndex++)) >> 16; } while(rightSecondary == 0); if(leftSecondary != rightSecondary) { @@ -138,13 +138,13 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat // Find the merge separator or the NO_CE terminator. uint32_t p; int32_t leftLimit = leftStart; - while((p = (uint32_t)(left.getCE(leftLimit) >> 32)) > + while ((p = static_cast(left.getCE(leftLimit) >> 32)) > Collation::MERGE_SEPARATOR_PRIMARY || p == 0) { ++leftLimit; } int32_t rightLimit = rightStart; - while((p = (uint32_t)(right.getCE(rightLimit) >> 32)) > + while ((p = static_cast(right.getCE(rightLimit) >> 32)) > Collation::MERGE_SEPARATOR_PRIMARY || p == 0) { ++rightLimit; @@ -156,12 +156,12 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat for(;;) { int32_t leftSecondary = 0; while(leftSecondary == 0 && leftIndex > leftStart) { - leftSecondary = ((uint32_t)left.getCE(--leftIndex)) >> 16; + leftSecondary = static_cast(left.getCE(--leftIndex)) >> 16; } int32_t rightSecondary = 0; while(rightSecondary == 0 && rightIndex > rightStart) { - rightSecondary = ((uint32_t)right.getCE(--rightIndex)) >> 16; + rightSecondary = static_cast(right.getCE(--rightIndex)) >> 16; } if(leftSecondary != rightSecondary) { @@ -197,15 +197,15 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat int64_t ce; do { ce = left.getCE(leftIndex++); - leftCase = (uint32_t)ce; - } while((uint32_t)(ce >> 32) == 0 || leftCase == 0); + leftCase = static_cast(ce); + } while (static_cast(ce >> 32) == 0 || leftCase == 0); leftLower32 = leftCase; leftCase &= 0xc000; do { ce = right.getCE(rightIndex++); - rightCase = (uint32_t)ce; - } while((uint32_t)(ce >> 32) == 0 || rightCase == 0); + rightCase = static_cast(ce); + } while (static_cast(ce >> 32) == 0 || rightCase == 0); rightCase &= 0xc000; } else { // Secondary+caseLevel: By analogy with the above, @@ -223,13 +223,13 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat // turning 0.0.ut into 0.0.0.t. // (See LDML Collation, Case Parameters.) do { - leftCase = (uint32_t)left.getCE(leftIndex++); + leftCase = static_cast(left.getCE(leftIndex++)); } while(leftCase <= 0xffff); leftLower32 = leftCase; leftCase &= 0xc000; do { - rightCase = (uint32_t)right.getCE(rightIndex++); + rightCase = static_cast(right.getCE(rightIndex++)); } while(rightCase <= 0xffff); rightCase &= 0xc000; } @@ -257,7 +257,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat for(;;) { uint32_t leftLower32, leftTertiary; do { - leftLower32 = (uint32_t)left.getCE(leftIndex++); + leftLower32 = static_cast(left.getCE(leftIndex++)); anyQuaternaries |= leftLower32; U_ASSERT((leftLower32 & Collation::ONLY_TERTIARY_MASK) != 0 || (leftLower32 & 0xc0c0) == 0); @@ -266,7 +266,7 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat uint32_t rightLower32, rightTertiary; do { - rightLower32 = (uint32_t)right.getCE(rightIndex++); + rightLower32 = static_cast(right.getCE(rightIndex++)); anyQuaternaries |= rightLower32; U_ASSERT((rightLower32 & Collation::ONLY_TERTIARY_MASK) != 0 || (rightLower32 & 0xc0c0) == 0); @@ -313,10 +313,10 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat uint32_t leftQuaternary; do { int64_t ce = left.getCE(leftIndex++); - leftQuaternary = (uint32_t)ce & 0xffff; + leftQuaternary = static_cast(ce) & 0xffff; if(leftQuaternary <= Collation::NO_CE_WEIGHT16) { // Variable primary or completely ignorable or NO_CE. - leftQuaternary = (uint32_t)(ce >> 32); + leftQuaternary = static_cast(ce >> 32); } else { // Regular CE, not tertiary ignorable. // Preserve the quaternary weight in bits 7..6. @@ -327,10 +327,10 @@ CollationCompare::compareUpToQuaternary(CollationIterator &left, CollationIterat uint32_t rightQuaternary; do { int64_t ce = right.getCE(rightIndex++); - rightQuaternary = (uint32_t)ce & 0xffff; + rightQuaternary = static_cast(ce) & 0xffff; if(rightQuaternary <= Collation::NO_CE_WEIGHT16) { // Variable primary or completely ignorable or NO_CE. - rightQuaternary = (uint32_t)(ce >> 32); + rightQuaternary = static_cast(ce >> 32); } else { // Regular CE, not tertiary ignorable. // Preserve the quaternary weight in bits 7..6. diff --git a/icu4c/source/i18n/collationdata.cpp b/icu4c/source/i18n/collationdata.cpp index 1b8b6a76de39..8d31711aa9a8 100644 --- a/icu4c/source/i18n/collationdata.cpp +++ b/icu4c/source/i18n/collationdata.cpp @@ -118,7 +118,7 @@ CollationData::getSingleCE(UChar32 c, UErrorCode &errorCode) const { uint32_t CollationData::getFirstPrimaryForGroup(int32_t script) const { int32_t index = getScriptIndex(script); - return index == 0 ? 0 : (uint32_t)scriptStarts[index] << 16; + return index == 0 ? 0 : static_cast(scriptStarts[index]) << 16; } uint32_t @@ -251,14 +251,14 @@ CollationData::makeReorderRanges(const int32_t *reorder, int32_t length, for(int32_t i = 0; i < length; ++i) { int32_t reorderCode = reorder[i] - UCOL_REORDER_CODE_FIRST; if(0 <= reorderCode && reorderCode < MAX_NUM_SPECIAL_REORDER_CODES) { - specials |= (uint32_t)1 << reorderCode; + specials |= static_cast(1) << reorderCode; } } // Start the reordering with the special low reorder codes that do not occur in the input. for(int32_t i = 0; i < MAX_NUM_SPECIAL_REORDER_CODES; ++i) { int32_t index = scriptsIndex[numScripts + i]; - if(index != 0 && (specials & ((uint32_t)1 << i)) == 0) { + if (index != 0 && (specials & (static_cast(1) << i)) == 0) { lowStart = addLowScriptRange(table, index, lowStart); } } @@ -354,7 +354,7 @@ CollationData::makeReorderRanges(const int32_t *reorder, int32_t length, ++i; } if(offset != 0 || i < scriptStartsLength - 1) { - ranges.addElement(((int32_t)scriptStarts[i] << 16) | (offset & 0xffff), errorCode); + ranges.addElement((static_cast(scriptStarts[i]) << 16) | (offset & 0xffff), errorCode); } if(i == scriptStartsLength - 1) { break; } offset = nextOffset; @@ -367,7 +367,7 @@ CollationData::addLowScriptRange(uint8_t table[], int32_t index, int32_t lowStar if((start & 0xff) < (lowStart & 0xff)) { lowStart += 0x100; } - table[index] = (uint8_t)(lowStart >> 8); + table[index] = static_cast(lowStart >> 8); int32_t limit = scriptStarts[index + 1]; lowStart = ((lowStart & 0xff00) + ((limit & 0xff00) - (start & 0xff00))) | (limit & 0xff); return lowStart; @@ -381,7 +381,7 @@ CollationData::addHighScriptRange(uint8_t table[], int32_t index, int32_t highLi } int32_t start = scriptStarts[index]; highLimit = ((highLimit & 0xff00) - ((limit & 0xff00) - (start & 0xff00))) | (start & 0xff); - table[index] = (uint8_t)(highLimit >> 8); + table[index] = static_cast(highLimit >> 8); return highLimit; } diff --git a/icu4c/source/i18n/collationdata.h b/icu4c/source/i18n/collationdata.h index d4f66828fbcb..783a79d65d3b 100644 --- a/icu4c/source/i18n/collationdata.h +++ b/icu4c/source/i18n/collationdata.h @@ -91,7 +91,7 @@ struct U_I18N_API CollationData : public UMemory { * Access to the defaultCE32 for contraction and prefix matching. */ static uint32_t readCE32(const char16_t *p) { - return ((uint32_t)p[0] << 16) | p[1]; + return (static_cast(p[0]) << 16) | p[1]; } /** diff --git a/icu4c/source/i18n/collationdatabuilder.cpp b/icu4c/source/i18n/collationdatabuilder.cpp index 9fad7f988145..44a108086a7b 100644 --- a/icu4c/source/i18n/collationdatabuilder.cpp +++ b/icu4c/source/i18n/collationdatabuilder.cpp @@ -381,7 +381,7 @@ CollationDataBuilder::maybeSetPrimaryRange(UChar32 start, UChar32 end, if(2 <= step && step <= 0x7f && (blockDelta >= 3 || (blockDelta > 0 && (start & 0x1f) <= 0x1c && (end & 0x1f) >= 3))) { - int64_t dataCE = ((int64_t)primary << 32) | (start << 8) | step; + int64_t dataCE = (static_cast(primary) << 32) | (start << 8) | step; if(isCompressiblePrimary(primary)) { dataCE |= 0x80; } int32_t index = addCE(dataCE, errorCode); if(U_FAILURE(errorCode)) { return 0; } @@ -526,9 +526,9 @@ int32_t CollationDataBuilder::addCE32(uint32_t ce32, UErrorCode &errorCode) { int32_t length = ce32s.size(); for(int32_t i = 0; i < length; ++i) { - if(ce32 == (uint32_t)ce32s.elementAti(i)) { return i; } + if (ce32 == static_cast(ce32s.elementAti(i))) { return i; } } - ce32s.addElement((int32_t)ce32, errorCode); + ce32s.addElement(static_cast(ce32), errorCode); return length; } @@ -684,7 +684,7 @@ CollationDataBuilder::addCE32(const UnicodeString &prefix, const UnicodeString & if(!isBuilderContextCE32(oldCE32)) { // Replace the simple oldCE32 with a builder context CE32 // pointing to a new ConditionalCE32 list head. - int32_t index = addConditionalCE32(UnicodeString((char16_t)0), oldCE32, errorCode); + int32_t index = addConditionalCE32(UnicodeString(static_cast(0)), oldCE32, errorCode); if(U_FAILURE(errorCode)) { return; } uint32_t contextCE32 = makeBuilderContextCE32(index); utrie2_set32(trie, c, contextCE32, &errorCode); @@ -695,7 +695,7 @@ CollationDataBuilder::addCE32(const UnicodeString &prefix, const UnicodeString & cond->builtCE32 = Collation::NO_CE32; } UnicodeString suffix(s, cLength); - UnicodeString context((char16_t)prefix.length()); + UnicodeString context(static_cast(prefix.length())); context.append(prefix).append(suffix); unsafeBackwardSet.addAll(suffix); for(;;) { @@ -730,9 +730,9 @@ CollationDataBuilder::addCE32(const UnicodeString &prefix, const UnicodeString & uint32_t CollationDataBuilder::encodeOneCEAsCE32(int64_t ce) { - uint32_t p = (uint32_t)(ce >> 32); - uint32_t lower32 = (uint32_t)ce; - uint32_t t = (uint32_t)(ce & 0xffff); + uint32_t p = static_cast(ce >> 32); + uint32_t lower32 = static_cast(ce); + uint32_t t = static_cast(ce & 0xffff); U_ASSERT((t & 0xc000) != 0xc000); // Impossible case bits 11 mark special CE32s. if((ce & INT64_C(0xffff00ff00ff)) == 0) { // normal form ppppsstt @@ -786,15 +786,15 @@ CollationDataBuilder::encodeCEs(const int64_t ces[], int32_t cesLength, // on checking this tag when using the data. int64_t ce0 = ces[0]; int64_t ce1 = ces[1]; - uint32_t p0 = (uint32_t)(ce0 >> 32); + uint32_t p0 = static_cast(ce0 >> 32); if((ce0 & INT64_C(0xffffffffff00ff)) == Collation::COMMON_SECONDARY_CE && (ce1 & INT64_C(0xffffffff00ffffff)) == Collation::COMMON_TERTIARY_CE && p0 != 0) { // Latin mini expansion return p0 | - (((uint32_t)ce0 & 0xff00u) << 8) | - (uint32_t)(ce1 >> 16) | + ((static_cast(ce0) & 0xff00u) << 8) | + static_cast(ce1 >> 16) | Collation::SPECIAL_CE32_LOW_BYTE | Collation::LATIN_EXPANSION_TAG; } @@ -807,7 +807,7 @@ CollationDataBuilder::encodeCEs(const int64_t ces[], int32_t cesLength, } uint32_t ce32 = encodeOneCEAsCE32(ces[i]); if(ce32 == Collation::NO_CE32) { break; } - newCE32s[i] = (int32_t)ce32; + newCE32s[i] = static_cast(ce32); } return encodeExpansion(ces, cesLength, errorCode); } @@ -912,7 +912,7 @@ CollationDataBuilder::copyFromBaseCE32(UChar32 c, uint32_t ce32, UBool withConte return copyFromBaseCE32(c, ce32, false, errorCode); } ConditionalCE32 head; - UnicodeString context((char16_t)0); + UnicodeString context(static_cast(0)); int32_t index; if(Collation::isContractionCE32(ce32)) { index = copyContractionsFromBaseCE32(context, c, ce32, &head, errorCode); @@ -926,8 +926,8 @@ CollationDataBuilder::copyFromBaseCE32(UChar32 c, uint32_t ce32, UBool withConte while(prefixes.next(errorCode)) { context = prefixes.getString(); context.reverse(); - context.insert(0, (char16_t)context.length()); - ce32 = (uint32_t)prefixes.getValue(); + context.insert(0, static_cast(context.length())); + ce32 = static_cast(prefixes.getValue()); if(Collation::isContractionCE32(ce32)) { index = copyContractionsFromBaseCE32(context, c, ce32, cond, errorCode); } else { @@ -948,7 +948,7 @@ CollationDataBuilder::copyFromBaseCE32(UChar32 c, uint32_t ce32, UBool withConte return copyFromBaseCE32(c, ce32, false, errorCode); } ConditionalCE32 head; - UnicodeString context((char16_t)0); + UnicodeString context(static_cast(0)); copyContractionsFromBaseCE32(context, c, ce32, &head, errorCode); ce32 = makeBuilderContextCE32(head.next); contextChars.add(c); @@ -994,7 +994,7 @@ CollationDataBuilder::copyContractionsFromBaseCE32(UnicodeString &context, UChar UCharsTrie::Iterator suffixes(p + 2, 0, errorCode); while(suffixes.next(errorCode)) { context.append(suffixes.getString()); - ce32 = copyFromBaseCE32(c, (uint32_t)suffixes.getValue(), true, errorCode); + ce32 = copyFromBaseCE32(c, static_cast(suffixes.getValue()), true, errorCode); cond->next = index = addConditionalCE32(context, ce32, errorCode); if(U_FAILURE(errorCode)) { return 0; } // No need to update the unsafeBackwardSet because the tailoring set @@ -1315,7 +1315,7 @@ CollationDataBuilder::setLeadSurrogates(UErrorCode &errorCode) { utrie2_enumForLeadSurrogate(trie, lead, nullptr, enumRangeLeadValue, &value); utrie2_set32ForLeadSurrogateCodeUnit( trie, lead, - Collation::makeCE32FromTagAndIndex(Collation::LEAD_SURROGATE_TAG, 0) | (uint32_t)value, + Collation::makeCE32FromTagAndIndex(Collation::LEAD_SURROGATE_TAG, 0) | static_cast(value), &errorCode); } } @@ -1349,7 +1349,7 @@ CollationDataBuilder::buildMappings(CollationData &data, UErrorCode &errorCode) if(getJamoCE32s(jamoCE32s, errorCode)) { jamoIndex = ce32s.size(); for(int32_t i = 0; i < CollationData::JAMO_CE32S_LENGTH; ++i) { - ce32s.addElement((int32_t)jamoCE32s[i], errorCode); + ce32s.addElement(static_cast(jamoCE32s[i]), errorCode); } // Small optimization: Use a bit in the Hangul ce32 // to indicate that none of the Jamo CE32s are isSpecialCE32() @@ -1393,7 +1393,7 @@ CollationDataBuilder::buildMappings(CollationData &data, UErrorCode &errorCode) if (!icu4xMode) { // For U+0000, move its normal ce32 into CE32s[0] and set U0000_TAG. - ce32s.setElementAt((int32_t)utrie2_get32(trie, 0), 0); + ce32s.setElementAt(static_cast(utrie2_get32(trie, 0)), 0); utrie2_set32(trie, 0, Collation::makeCE32FromTagAndIndex(Collation::U0000_TAG, 0), &errorCode); } @@ -1564,7 +1564,7 @@ CollationDataBuilder::buildContext(ConditionalCE32 *head, UErrorCode &errorCode) } } } - contractionBuilder.add(suffix, (int32_t)cond->ce32, errorCode); + contractionBuilder.add(suffix, static_cast(cond->ce32), errorCode); if(cond == lastCond) { break; } cond = getConditionalCE32(cond->next); } @@ -1586,7 +1586,7 @@ CollationDataBuilder::buildContext(ConditionalCE32 *head, UErrorCode &errorCode) } else { prefix.remove(0, 1); // Remove the length unit. prefix.reverse(); - prefixBuilder.add(prefix, (int32_t)ce32, errorCode); + prefixBuilder.add(prefix, static_cast(ce32), errorCode); if(cond->next < 0) { break; } } } @@ -1604,7 +1604,7 @@ int32_t CollationDataBuilder::addContextTrie(uint32_t defaultCE32, UCharsTrieBuilder &trieBuilder, UErrorCode &errorCode) { UnicodeString context; - context.append((char16_t)(defaultCE32 >> 16)).append((char16_t)defaultCE32); + context.append(static_cast(defaultCE32 >> 16)).append(static_cast(defaultCE32)); UnicodeString trieString; context.append(trieBuilder.buildUnicodeString(USTRINGTRIE_BUILD_SMALL, trieString, errorCode)); if(U_FAILURE(errorCode)) { return -1; } diff --git a/icu4c/source/i18n/collationdatawriter.cpp b/icu4c/source/i18n/collationdatawriter.cpp index ce78a0526a3b..fea0116fa4d4 100644 --- a/icu4c/source/i18n/collationdatawriter.cpp +++ b/icu4c/source/i18n/collationdatawriter.cpp @@ -34,7 +34,7 @@ U_NAMESPACE_BEGIN uint8_t * RuleBasedCollator::cloneRuleData(int32_t &length, UErrorCode &errorCode) const { if(U_FAILURE(errorCode)) { return nullptr; } - LocalMemory buffer((uint8_t *)uprv_malloc(20000)); + LocalMemory buffer(static_cast(uprv_malloc(20000))); if(buffer.isNull()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -118,7 +118,7 @@ CollationDataWriter::write(UBool isBase, const UVersionInfo dataVersion, int32_t fastLatinVersion; if(data.fastLatinTable != nullptr) { - fastLatinVersion = (int32_t)CollationFastLatin::VERSION << 16; + fastLatinVersion = static_cast(CollationFastLatin::VERSION) << 16; } else { fastLatinVersion = 0; } @@ -185,7 +185,7 @@ CollationDataWriter::write(UBool isBase, const UVersionInfo dataVersion, header.dataHeader.magic2 = 0x27; uprv_memcpy(&header.info, &dataInfo, sizeof(UDataInfo)); uprv_memcpy(header.info.dataVersion, dataVersion, sizeof(UVersionInfo)); - headerSize = (int32_t)sizeof(header); + headerSize = static_cast(sizeof(header)); U_ASSERT((headerSize & 3) == 0); // multiple of 4 bytes if(hasMappings && data.cesLength != 0) { // Sum of the sizes of the data items which are @@ -199,7 +199,7 @@ CollationDataWriter::write(UBool isBase, const UVersionInfo dataVersion, headerSize += 4; } } - header.dataHeader.headerSize = (uint16_t)headerSize; + header.dataHeader.headerSize = static_cast(headerSize); if(headerSize <= capacity) { uprv_memcpy(dest, &header, sizeof(header)); // Write 00 bytes so that the padding is not mistaken for a copyright string. @@ -302,7 +302,7 @@ CollationDataWriter::write(UBool isBase, const UVersionInfo dataVersion, UnicodeString scripts; indexes[CollationDataReader::IX_SCRIPTS_OFFSET] = totalSize; if(isBase) { - scripts.append((char16_t)data.numScripts); + scripts.append(static_cast(data.numScripts)); scripts.append(reinterpret_cast(data.scriptsIndex), data.numScripts + 16); scripts.append(reinterpret_cast(data.scriptStarts), data.scriptStartsLength); totalSize += scripts.length() * 2; diff --git a/icu4c/source/i18n/collationfastlatin.cpp b/icu4c/source/i18n/collationfastlatin.cpp index f40781a1178f..e128df496761 100644 --- a/icu4c/source/i18n/collationfastlatin.cpp +++ b/icu4c/source/i18n/collationfastlatin.cpp @@ -94,7 +94,7 @@ CollationFastLatin::getOptions(const CollationData *data, const CollationSetting } else { p = 0; } - primaries[c] = (uint16_t)p; + primaries[c] = static_cast(p); } if(digitsAreReordered || (settings.options & CollationSettings::NUMERIC) != 0) { // Bail out for digits. @@ -102,7 +102,7 @@ CollationFastLatin::getOptions(const CollationData *data, const CollationSetting } // Shift the miniVarTop above other options. - return ((int32_t)miniVarTop << 16) | settings.options; + return (static_cast(miniVarTop) << 16) | settings.options; } int32_t @@ -116,7 +116,7 @@ CollationFastLatin::compareUTF16(const uint16_t *table, const uint16_t *primarie U_ASSERT((table[0] >> 8) == VERSION); table += (table[0] & 0xff); // skip the header - uint32_t variableTop = (uint32_t)options >> 16; // see getOptions() + uint32_t variableTop = static_cast(options) >> 16; // see getOptions() options &= 0xffff; // needed for CollationSettings::getStrength() to work // Check for supported characters, fetch mini CEs, and compare primaries. @@ -452,7 +452,7 @@ CollationFastLatin::compareUTF8(const uint16_t *table, const uint16_t *primaries U_ASSERT((table[0] >> 8) == VERSION); table += (table[0] & 0xff); // skip the header - uint32_t variableTop = (uint32_t)options >> 16; // see RuleBasedCollator::getFastLatinOptions() + uint32_t variableTop = static_cast(options) >> 16; // see RuleBasedCollator::getFastLatinOptions() options &= 0xffff; // needed for CollationSettings::getStrength() to work // Check for supported characters, fetch mini CEs, and compare primaries. @@ -859,7 +859,7 @@ CollationFastLatin::nextPair(const uint16_t *table, UChar32 c, uint32_t ce, return ce; // simple or special mini CE } else if(ce >= EXPANSION) { int32_t index = NUM_FAST_CHARS + (ce & INDEX_MASK); - return ((uint32_t)table[index + 1] << 16) | table[index]; + return (static_cast(table[index + 1]) << 16) | table[index]; } else /* ce >= CONTRACTION */ { if(c == 0 && sLength < 0) { sLength = sIndex - 1; @@ -938,7 +938,7 @@ CollationFastLatin::nextPair(const uint16_t *table, UChar32 c, uint32_t ce, if(length == 2) { return ce; } else { - return ((uint32_t)table[index + 2] << 16) | ce; + return (static_cast(table[index + 2]) << 16) | ce; } } } diff --git a/icu4c/source/i18n/collationfastlatinbuilder.cpp b/icu4c/source/i18n/collationfastlatinbuilder.cpp index b1fd3af70aaa..dbfdd9749797 100644 --- a/icu4c/source/i18n/collationfastlatinbuilder.cpp +++ b/icu4c/source/i18n/collationfastlatinbuilder.cpp @@ -45,9 +45,9 @@ namespace { */ int32_t compareInt64AsUnsigned(int64_t a, int64_t b) { - if((uint64_t)a < (uint64_t)b) { + if (static_cast(a) < static_cast(b)) { return -1; - } else if((uint64_t)a > (uint64_t)b) { + } else if (static_cast(a) > static_cast(b)) { return 1; } else { return 0; @@ -140,7 +140,7 @@ CollationFastLatinBuilder::loadGroups(const CollationData &data, UErrorCode &err if(U_FAILURE(errorCode)) { return false; } headerLength = 1 + NUM_SPECIAL_GROUPS; uint32_t r0 = (CollationFastLatin::VERSION << 8) | headerLength; - result.append((char16_t)r0); + result.append(static_cast(r0)); // The first few reordering groups should be special groups // (space, punct, ..., digit) followed by Latn, then Grek and other scripts. for(int32_t i = 0; i < NUM_SPECIAL_GROUPS; ++i) { @@ -149,7 +149,7 @@ CollationFastLatinBuilder::loadGroups(const CollationData &data, UErrorCode &err // missing data return false; } - result.append((char16_t)0); // reserve a slot for this group + result.append(static_cast(0)); // reserve a slot for this group } firstDigitPrimary = data.getFirstPrimaryForGroup(UCOL_REORDER_CODE_DIGIT); @@ -234,7 +234,7 @@ CollationFastLatinBuilder::getCEs(const CollationData &data, UErrorCode &errorCo // Write a contraction list with only a default value if there is no real contraction. U_ASSERT(contractionCEs.isEmpty()); addContractionEntry(CollationFastLatin::CONTR_CHAR_MASK, ce0, ce1, errorCode); - charCEs[0][0] = ((int64_t)Collation::NO_CE_PRIMARY << 32) | CONTRACTION_FLAG; + charCEs[0][0] = (static_cast(Collation::NO_CE_PRIMARY) << 32) | CONTRACTION_FLAG; charCEs[0][1] = 0; } } @@ -301,12 +301,12 @@ CollationFastLatinBuilder::getCEsFromCE32(const CollationData &data, UChar32 c, // A mapping can be completely ignorable. if(ce0 == 0) { return ce1 == 0; } // We do not support an ignorable ce0 unless it is completely ignorable. - uint32_t p0 = (uint32_t)(ce0 >> 32); + uint32_t p0 = static_cast(ce0 >> 32); if(p0 == 0) { return false; } // We only support primaries up to the Latin script. if(p0 > lastLatinPrimary) { return false; } // We support non-common secondary and case weights only together with short primaries. - uint32_t lower32_0 = (uint32_t)ce0; + uint32_t lower32_0 = static_cast(ce0); if(p0 < firstShortPrimary) { uint32_t sc0 = lower32_0 & Collation::SECONDARY_AND_CASE_MASK; if(sc0 != Collation::COMMON_SECONDARY_CE) { return false; } @@ -319,9 +319,9 @@ CollationFastLatinBuilder::getCEsFromCE32(const CollationData &data, UChar32 c, // or a short-primary CE is followed by a secondary CE. // This is so that we can test the first primary and use the same mask for both, // and determine for both whether they are variable. - uint32_t p1 = (uint32_t)(ce1 >> 32); + uint32_t p1 = static_cast(ce1 >> 32); if(p1 == 0 ? p0 < firstShortPrimary : !inSameGroup(p0, p1)) { return false; } - uint32_t lower32_1 = (uint32_t)ce1; + uint32_t lower32_1 = static_cast(ce1); // No tertiary CEs. if((lower32_1 >> 16) == 0) { return false; } // We support non-common secondary and case weights @@ -374,7 +374,7 @@ CollationFastLatinBuilder::getCEsFromContractionCE32(const CollationData &data, if(addContraction) { addContractionEntry(prevX, ce0, ce1, errorCode); } - ce32 = (uint32_t)suffixes.getValue(); + ce32 = static_cast(suffixes.getValue()); if(suffix.length() == 1 && getCEsFromCE32(data, U_SENTINEL, ce32, errorCode)) { addContraction = true; } else { @@ -392,7 +392,7 @@ CollationFastLatinBuilder::getCEsFromContractionCE32(const CollationData &data, // when there is a non-fast-Latin character following. // For example: Danish &Y<(Collation::NO_CE_PRIMARY) << 32) | CONTRACTION_FLAG | contractionIndex; ce1 = 0; return true; } @@ -410,8 +410,8 @@ CollationFastLatinBuilder::addContractionEntry(int32_t x, int64_t cce0, int64_t void CollationFastLatinBuilder::addUniqueCE(int64_t ce, UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return; } - if(ce == 0 || (uint32_t)(ce >> 32) == Collation::NO_CE_PRIMARY) { return; } - ce &= ~(int64_t)Collation::CASE_MASK; // blank out case bits + if (ce == 0 || static_cast(ce >> 32) == Collation::NO_CE_PRIMARY) { return; } + ce &= ~static_cast(Collation::CASE_MASK); // blank out case bits int32_t i = binarySearch(uniqueCEs.getBuffer(), uniqueCEs.size(), ce); if(i < 0) { uniqueCEs.insertElementAt(ce, ~i, errorCode); @@ -420,7 +420,7 @@ CollationFastLatinBuilder::addUniqueCE(int64_t ce, UErrorCode &errorCode) { uint32_t CollationFastLatinBuilder::getMiniCE(int64_t ce) const { - ce &= ~(int64_t)Collation::CASE_MASK; // blank out case bits + ce &= ~static_cast(Collation::CASE_MASK); // blank out case bits int32_t index = binarySearch(uniqueCEs.getBuffer(), uniqueCEs.size(), ce); U_ASSERT(index >= 0); return miniCEs[index]; @@ -430,7 +430,7 @@ UBool CollationFastLatinBuilder::encodeUniqueCEs(UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return false; } uprv_free(miniCEs); - miniCEs = (uint16_t *)uprv_malloc(uniqueCEs.size() * 2); + miniCEs = static_cast(uprv_malloc(uniqueCEs.size() * 2)); if(miniCEs == nullptr) { errorCode = U_MEMORY_ALLOCATION_ERROR; return false; @@ -448,13 +448,13 @@ CollationFastLatinBuilder::encodeUniqueCEs(UErrorCode &errorCode) { int64_t ce = uniqueCEs.elementAti(i); // Note: At least one of the p/s/t weights changes from one unique CE to the next. // (uniqueCEs does not store case bits.) - uint32_t p = (uint32_t)(ce >> 32); + uint32_t p = static_cast(ce >> 32); if(p != prevPrimary) { while(p > lastGroupPrimary) { U_ASSERT(pri <= CollationFastLatin::MAX_LONG); // Set the group's header entry to the // last "long primary" in or before the group. - result.setCharAt(1 + group, (char16_t)pri); + result.setCharAt(1 + group, static_cast(pri)); if(++group < NUM_SPECIAL_GROUPS) { lastGroupPrimary = lastSpecialPrimaries[group]; } else { @@ -494,7 +494,7 @@ CollationFastLatinBuilder::encodeUniqueCEs(UErrorCode &errorCode) { sec = CollationFastLatin::COMMON_SEC; ter = CollationFastLatin::COMMON_TER; } - uint32_t lower32 = (uint32_t)ce; + uint32_t lower32 = static_cast(ce); uint32_t s = lower32 >> 16; if(s != prevSecondary) { if(pri == 0) { @@ -544,9 +544,9 @@ CollationFastLatinBuilder::encodeUniqueCEs(UErrorCode &errorCode) { } if(CollationFastLatin::MIN_LONG <= pri && pri <= CollationFastLatin::MAX_LONG) { U_ASSERT(sec == CollationFastLatin::COMMON_SEC); - miniCEs[i] = (uint16_t)(pri | ter); + miniCEs[i] = static_cast(pri | ter); } else { - miniCEs[i] = (uint16_t)(pri | sec | ter); + miniCEs[i] = static_cast(pri | sec | ter); } } #if DEBUG_COLLATION_FAST_LATIN_BUILDER @@ -566,7 +566,7 @@ CollationFastLatinBuilder::encodeCharCEs(UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return false; } int32_t miniCEsStart = result.length(); for(int32_t i = 0; i < CollationFastLatin::NUM_FAST_CHARS; ++i) { - result.append((char16_t)0); // initialize to completely ignorable + result.append(static_cast(0)); // initialize to completely ignorable } int32_t indexBase = result.length(); for(int32_t i = 0; i < CollationFastLatin::NUM_FAST_CHARS; ++i) { @@ -578,14 +578,14 @@ CollationFastLatinBuilder::encodeCharCEs(UErrorCode &errorCode) { // and if so, then we could reuse the other expansion. // However, that seems unlikely. int32_t expansionIndex = result.length() - indexBase; - if(expansionIndex > (int32_t)CollationFastLatin::INDEX_MASK) { + if (expansionIndex > static_cast(CollationFastLatin::INDEX_MASK)) { miniCE = CollationFastLatin::BAIL_OUT; } else { - result.append((char16_t)(miniCE >> 16)).append((char16_t)miniCE); + result.append(static_cast(miniCE >> 16)).append(static_cast(miniCE)); miniCE = CollationFastLatin::EXPANSION | expansionIndex; } } - result.setCharAt(miniCEsStart + i, (char16_t)miniCE); + result.setCharAt(miniCEsStart + i, static_cast(miniCE)); } return U_SUCCESS(errorCode); } @@ -601,25 +601,25 @@ CollationFastLatinBuilder::encodeContractions(UErrorCode &errorCode) { int64_t ce = charCEs[i][0]; if(!isContractionCharCE(ce)) { continue; } int32_t contractionIndex = result.length() - indexBase; - if(contractionIndex > (int32_t)CollationFastLatin::INDEX_MASK) { + if (contractionIndex > static_cast(CollationFastLatin::INDEX_MASK)) { result.setCharAt(headerLength + i, CollationFastLatin::BAIL_OUT); continue; } UBool firstTriple = true; - for(int32_t index = (int32_t)ce & 0x7fffffff;; index += 3) { + for (int32_t index = static_cast(ce) & 0x7fffffff;; index += 3) { int32_t x = static_cast(contractionCEs.elementAti(index)); - if((uint32_t)x == CollationFastLatin::CONTR_CHAR_MASK && !firstTriple) { break; } + if (static_cast(x) == CollationFastLatin::CONTR_CHAR_MASK && !firstTriple) { break; } int64_t cce0 = contractionCEs.elementAti(index + 1); int64_t cce1 = contractionCEs.elementAti(index + 2); uint32_t miniCE = encodeTwoCEs(cce0, cce1); if(miniCE == CollationFastLatin::BAIL_OUT) { - result.append((char16_t)(x | (1 << CollationFastLatin::CONTR_LENGTH_SHIFT))); + result.append(static_cast(x | (1 << CollationFastLatin::CONTR_LENGTH_SHIFT))); } else if(miniCE <= 0xffff) { - result.append((char16_t)(x | (2 << CollationFastLatin::CONTR_LENGTH_SHIFT))); - result.append((char16_t)miniCE); + result.append(static_cast(x | (2 << CollationFastLatin::CONTR_LENGTH_SHIFT))); + result.append(static_cast(miniCE)); } else { - result.append((char16_t)(x | (3 << CollationFastLatin::CONTR_LENGTH_SHIFT))); - result.append((char16_t)(miniCE >> 16)).append((char16_t)miniCE); + result.append(static_cast(x | (3 << CollationFastLatin::CONTR_LENGTH_SHIFT))); + result.append(static_cast(miniCE >> 16)).append(static_cast(miniCE)); } firstTriple = false; } @@ -627,11 +627,11 @@ CollationFastLatinBuilder::encodeContractions(UErrorCode &errorCode) { // and if so, then we could truncate the result and reuse the other list. // However, that seems unlikely. result.setCharAt(headerLength + i, - (char16_t)(CollationFastLatin::CONTRACTION | contractionIndex)); + static_cast(CollationFastLatin::CONTRACTION | contractionIndex)); } if(result.length() > firstContractionIndex) { // Terminate the last contraction list. - result.append((char16_t)CollationFastLatin::CONTR_CHAR_MASK); + result.append(static_cast(CollationFastLatin::CONTR_CHAR_MASK)); } if(result.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; @@ -681,7 +681,7 @@ CollationFastLatinBuilder::encodeTwoCEs(int64_t first, int64_t second) const { if(miniCE >= CollationFastLatin::MIN_SHORT) { // Extract & copy the case bits. // Shift them from normal CE bits 15..14 to mini CE bits 4..3. - uint32_t c = (((uint32_t)first & Collation::CASE_MASK) >> (14 - 3)); + uint32_t c = ((static_cast(first) & Collation::CASE_MASK) >> (14 - 3)); // Only in mini CEs: Ignorable case bits = 0, lowercase = 1. c += CollationFastLatin::LOWER_CASE; miniCE |= c; @@ -691,7 +691,7 @@ CollationFastLatinBuilder::encodeTwoCEs(int64_t first, int64_t second) const { uint32_t miniCE1 = getMiniCE(second); if(miniCE1 == CollationFastLatin::BAIL_OUT) { return miniCE1; } - uint32_t case1 = (uint32_t)second & Collation::CASE_MASK; + uint32_t case1 = static_cast(second) & Collation::CASE_MASK; if(miniCE >= CollationFastLatin::MIN_SHORT && (miniCE & CollationFastLatin::SECONDARY_MASK) == CollationFastLatin::COMMON_SEC) { // Try to combine the two mini CEs into one. diff --git a/icu4c/source/i18n/collationfastlatinbuilder.h b/icu4c/source/i18n/collationfastlatinbuilder.h index 8b63b86815fd..18b20ac5f3ca 100644 --- a/icu4c/source/i18n/collationfastlatinbuilder.h +++ b/icu4c/source/i18n/collationfastlatinbuilder.h @@ -63,7 +63,7 @@ class U_I18N_API CollationFastLatinBuilder : public UObject { uint32_t encodeTwoCEs(int64_t first, int64_t second) const; static UBool isContractionCharCE(int64_t ce) { - return (uint32_t)(ce >> 32) == Collation::NO_CE_PRIMARY && ce != Collation::NO_CE; + return static_cast(ce >> 32) == Collation::NO_CE_PRIMARY && ce != Collation::NO_CE; } static const uint32_t CONTRACTION_FLAG = 0x80000000; diff --git a/icu4c/source/i18n/collationfcd.h b/icu4c/source/i18n/collationfcd.h index 9620452b97f0..c9ca54234f66 100644 --- a/icu4c/source/i18n/collationfcd.h +++ b/icu4c/source/i18n/collationfcd.h @@ -65,7 +65,7 @@ class U_I18N_API CollationFCD { // U+0300 is the first character with lccc!=0. c >= 0x300 && (i = lcccIndex[c >> 5]) != 0 && - (lcccBits[i] & ((uint32_t)1 << (c & 0x1f))) != 0; + (lcccBits[i] & (static_cast(1) << (c & 0x1f))) != 0; } static inline UBool hasTccc(UChar32 c) { @@ -77,7 +77,7 @@ class U_I18N_API CollationFCD { // U+00C0 is the first character with tccc!=0. c >= 0xc0 && (i = tcccIndex[c >> 5]) != 0 && - (tcccBits[i] & ((uint32_t)1 << (c & 0x1f))) != 0; + (tcccBits[i] & (static_cast(1) << (c & 0x1f))) != 0; } static inline UBool mayHaveLccc(UChar32 c) { @@ -89,7 +89,7 @@ class U_I18N_API CollationFCD { int32_t i; return (i = lcccIndex[c >> 5]) != 0 && - (lcccBits[i] & ((uint32_t)1 << (c & 0x1f))) != 0; + (lcccBits[i] & (static_cast(1) << (c & 0x1f))) != 0; } /** diff --git a/icu4c/source/i18n/collationiterator.cpp b/icu4c/source/i18n/collationiterator.cpp index f8c6da22b2ba..ef1980aebfc7 100644 --- a/icu4c/source/i18n/collationiterator.cpp +++ b/icu4c/source/i18n/collationiterator.cpp @@ -459,7 +459,7 @@ CollationIterator::getCE32FromPrefix(const CollationData *d, uint32_t ce32, ++lookBehind; UStringTrieResult match = prefixes.nextForCodePoint(c); if(USTRINGTRIE_HAS_VALUE(match)) { - ce32 = (uint32_t)prefixes.getValue(); + ce32 = static_cast(prefixes.getValue()); } if(!USTRINGTRIE_HAS_NEXT(match)) { break; } } @@ -506,7 +506,7 @@ CollationIterator::nextCE32FromContraction(const CollationData *d, uint32_t cont for(;;) { UChar32 nextCp; if(USTRINGTRIE_HAS_VALUE(match)) { - ce32 = (uint32_t)suffixes.getValue(); + ce32 = static_cast(suffixes.getValue()); if(!USTRINGTRIE_HAS_NEXT(match) || (c = nextSkippedCodePoint(errorCode)) < 0) { return ce32; } @@ -586,7 +586,7 @@ CollationIterator::nextCE32FromDiscontiguousContraction( return ce32; } ++lookAhead; - uint8_t prevCC = (uint8_t)fcd16; + uint8_t prevCC = static_cast(fcd16); fcd16 = d->getFCD16(nextCp); if(fcd16 <= 0xff) { // The next code point after c is a starter (S2.1.1 "process each non-starter"). @@ -632,7 +632,7 @@ CollationIterator::nextCE32FromDiscontiguousContraction( if(prevCC < (fcd16 >> 8) && USTRINGTRIE_HAS_VALUE(match = suffixes.nextForCodePoint(c))) { // "If there is a match, replace S by S + C, and remove C." (S2.1.3) // Keep prevCC unchanged. - ce32 = (uint32_t)suffixes.getValue(); + ce32 = static_cast(suffixes.getValue()); sinceMatch = 0; skipped->recordMatch(); if(!USTRINGTRIE_HAS_NEXT(match)) { break; } @@ -641,7 +641,7 @@ CollationIterator::nextCE32FromDiscontiguousContraction( // No match for "S + C", skip C. skipped->skip(c); skipped->resetToTrieState(suffixes); - prevCC = (uint8_t)fcd16; + prevCC = static_cast(fcd16); } if((c = nextSkippedCodePoint(errorCode)) < 0) { break; } ++sinceMatch; diff --git a/icu4c/source/i18n/collationiterator.h b/icu4c/source/i18n/collationiterator.h index 07bdf61985ae..46919ba6ab52 100644 --- a/icu4c/source/i18n/collationiterator.h +++ b/icu4c/source/i18n/collationiterator.h @@ -142,7 +142,7 @@ class U_I18N_API CollationIterator : public UObject { // Normal CE from the main data. // Forced-inline of ceFromSimpleCE32(ce32). return ceBuffer.set(cesIndex++, - ((int64_t)(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (t << 8)); + (static_cast(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (t << 8)); } const CollationData *d; // The compiler should be able to optimize the previous and the following @@ -157,7 +157,7 @@ class U_I18N_API CollationIterator : public UObject { if(t < Collation::SPECIAL_CE32_LOW_BYTE) { // Normal CE from the base data. return ceBuffer.set(cesIndex++, - ((int64_t)(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (t << 8)); + (static_cast(ce32 & 0xffff0000) << 32) | ((ce32 & 0xff00) << 16) | (t << 8)); } } else { d = data; @@ -165,7 +165,7 @@ class U_I18N_API CollationIterator : public UObject { if(t == Collation::LONG_PRIMARY_CE32_LOW_BYTE) { // Forced-inline of ceFromLongPrimaryCE32(ce32). return ceBuffer.set(cesIndex++, - ((int64_t)(ce32 - t) << 32) | Collation::COMMON_SEC_AND_TER_CE); + (static_cast(ce32 - t) << 32) | Collation::COMMON_SEC_AND_TER_CE); } return nextCEFromCE32(d, c, ce32, errorCode); } diff --git a/icu4c/source/i18n/collationkeys.cpp b/icu4c/source/i18n/collationkeys.cpp index c429ac3f8f70..b5bbd2a64aba 100644 --- a/icu4c/source/i18n/collationkeys.cpp +++ b/icu4c/source/i18n/collationkeys.cpp @@ -126,15 +126,15 @@ class SortKeyLevel : public UMemory { void SortKeyLevel::appendByte(uint32_t b) { if(len < buffer.getCapacity() || ensureCapacity(1)) { - buffer[len++] = (uint8_t)b; + buffer[len++] = static_cast(b); } } void SortKeyLevel::appendWeight16(uint32_t w) { U_ASSERT((w & 0xffff) != 0); - uint8_t b0 = (uint8_t)(w >> 8); - uint8_t b1 = (uint8_t)w; + uint8_t b0 = static_cast(w >> 8); + uint8_t b1 = static_cast(w); int32_t appendLength = (b1 == 0) ? 1 : 2; if((len + appendLength) <= buffer.getCapacity() || ensureCapacity(appendLength)) { buffer[len++] = b0; @@ -147,7 +147,12 @@ SortKeyLevel::appendWeight16(uint32_t w) { void SortKeyLevel::appendWeight32(uint32_t w) { U_ASSERT(w != 0); - uint8_t bytes[4] = { (uint8_t)(w >> 24), (uint8_t)(w >> 16), (uint8_t)(w >> 8), (uint8_t)w }; + uint8_t bytes[4] = { + static_cast(w >> 24), + static_cast(w >> 16), + static_cast(w >> 8), + static_cast(w) + }; int32_t appendLength = (bytes[1] == 0) ? 1 : (bytes[2] == 0) ? 2 : (bytes[3] == 0) ? 3 : 4; if((len + appendLength) <= buffer.getCapacity() || ensureCapacity(appendLength)) { buffer[len++] = bytes[0]; @@ -166,8 +171,8 @@ SortKeyLevel::appendWeight32(uint32_t w) { void SortKeyLevel::appendReverseWeight16(uint32_t w) { U_ASSERT((w & 0xffff) != 0); - uint8_t b0 = (uint8_t)(w >> 8); - uint8_t b1 = (uint8_t)w; + uint8_t b0 = static_cast(w >> 8); + uint8_t b1 = static_cast(w); int32_t appendLength = (b1 == 0) ? 1 : 2; if((len + appendLength) <= buffer.getCapacity() || ensureCapacity(appendLength)) { if(b1 == 0) { @@ -238,7 +243,7 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, levels |= Collation::CASE_LEVEL_FLAG; } // Minus the levels below minLevel. - levels &= ~(((uint32_t)1 << minLevel) - 1); + levels &= ~((static_cast(1) << minLevel) - 1); if(levels == 0) { return; } uint32_t variableTop; @@ -269,7 +274,7 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, // No need to keep all CEs in the buffer when we write a sort key. iter.clearCEsIfNoneRemaining(); int64_t ce = iter.nextCE(errorCode); - uint32_t p = (uint32_t)(ce >> 32); + uint32_t p = static_cast(ce >> 32); if(p < variableTop && p > Collation::MERGE_SEPARATOR_PRIMARY) { // Variable CE, shift it to quaternary level. // Ignore all following primary ignorables, and shift further variable CEs. @@ -297,7 +302,7 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, } do { ce = iter.nextCE(errorCode); - p = (uint32_t)(ce >> 32); + p = static_cast(ce >> 32); } while(p == 0); } while(p < variableTop && p > Collation::MERGE_SEPARATOR_PRIMARY); } @@ -331,9 +336,9 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, prevReorderedPrimary = 0; } } - char p2 = (char)(p >> 16); + char p2 = static_cast(p >> 16); if(p2 != 0) { - char buffer[3] = { p2, (char)(p >> 8), (char)p }; + char buffer[3] = {p2, static_cast(p >> 8), static_cast(p)}; sink.Append(buffer, (buffer[1] == 0) ? 1 : (buffer[2] == 0) ? 2 : 3); } // Optimization for internalNextSortKeyPart(): @@ -347,7 +352,7 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, } } - uint32_t lower32 = (uint32_t)ce; + uint32_t lower32 = static_cast(ce); if(lower32 == 0) { continue; } // completely ignorable, no secondary/case/tertiary/quaternary if((levels & Collation::SECONDARY_LEVEL_FLAG) != 0) { @@ -635,7 +640,7 @@ CollationKeys::writeSortKeyUpToQuaternary(CollationIterator &iter, int32_t length = cases.length() - 1; // Ignore the trailing NO_CE. uint8_t b = 0; for(int32_t i = 0; i < length; ++i) { - uint8_t c = (uint8_t)cases[i]; + uint8_t c = cases[i]; U_ASSERT((c & 0xf) == 0 && c != 0); if(b == 0) { b = c; diff --git a/icu4c/source/i18n/collationkeys.h b/icu4c/source/i18n/collationkeys.h index d1331566128b..0529b3098483 100644 --- a/icu4c/source/i18n/collationkeys.h +++ b/icu4c/source/i18n/collationkeys.h @@ -44,7 +44,7 @@ class SortKeyByteSink : public ByteSink { --ignore_; } else { if (appended_ < capacity_ || Resize(1, appended_)) { - buffer_[appended_] = (char)b; + buffer_[appended_] = static_cast(b); } ++appended_; } diff --git a/icu4c/source/i18n/collationrootelements.cpp b/icu4c/source/i18n/collationrootelements.cpp index 9b46d14144bb..041f53dbda10 100644 --- a/icu4c/source/i18n/collationrootelements.cpp +++ b/icu4c/source/i18n/collationrootelements.cpp @@ -64,7 +64,7 @@ CollationRootElements::lastCEWithPrimaryBefore(uint32_t p) const { secTer = q; } } - return ((int64_t)p << 32) | (secTer & ~SEC_TER_DELTA_FLAG); + return (static_cast(p) << 32) | (secTer & ~SEC_TER_DELTA_FLAG); } int64_t @@ -82,7 +82,7 @@ CollationRootElements::firstCEWithPrimaryAtLeast(uint32_t p) const { } } // The code above guarantees that p has at most 3 bytes: (p & 0xff) == 0. - return ((int64_t)p << 32) | Collation::COMMON_SEC_AND_TER_CE; + return (static_cast(p) << 32) | Collation::COMMON_SEC_AND_TER_CE; } uint32_t @@ -93,7 +93,7 @@ CollationRootElements::getPrimaryBefore(uint32_t p, UBool isCompressible) const if(p == (q & 0xffffff00)) { // Found p itself. Return the previous primary. // See if p is at the end of a previous range. - step = (int32_t)q & PRIMARY_STEP_MASK; + step = static_cast(q) & PRIMARY_STEP_MASK; if(step == 0) { // p is not at the end of a range. Look for the previous primary. do { @@ -105,7 +105,7 @@ CollationRootElements::getPrimaryBefore(uint32_t p, UBool isCompressible) const // p is in a range, and not at the start. uint32_t nextElement = elements[index + 1]; U_ASSERT(isEndOfPrimaryRange(nextElement)); - step = (int32_t)nextElement & PRIMARY_STEP_MASK; + step = static_cast(nextElement) & PRIMARY_STEP_MASK; } // Return the previous range primary. if((p & 0xffff) == 0) { @@ -120,7 +120,7 @@ CollationRootElements::getSecondaryBefore(uint32_t p, uint32_t s) const { int32_t index; uint32_t previousSec, sec; if(p == 0) { - index = (int32_t)elements[IX_FIRST_SECONDARY_INDEX]; + index = static_cast(elements[IX_FIRST_SECONDARY_INDEX]); // Gap at the beginning of the secondary CE range. previousSec = 0; sec = elements[index] >> 16; @@ -146,11 +146,11 @@ CollationRootElements::getTertiaryBefore(uint32_t p, uint32_t s, uint32_t t) con uint32_t previousTer, secTer; if(p == 0) { if(s == 0) { - index = (int32_t)elements[IX_FIRST_TERTIARY_INDEX]; + index = static_cast(elements[IX_FIRST_TERTIARY_INDEX]); // Gap at the beginning of the tertiary CE range. previousTer = 0; } else { - index = (int32_t)elements[IX_FIRST_SECONDARY_INDEX]; + index = static_cast(elements[IX_FIRST_SECONDARY_INDEX]); previousTer = Collation::BEFORE_WEIGHT16; } secTer = elements[index] & ~SEC_TER_DELTA_FLAG; @@ -174,7 +174,7 @@ CollationRootElements::getPrimaryAfter(uint32_t p, int32_t index, UBool isCompre U_ASSERT(p == (elements[index] & 0xffffff00) || isEndOfPrimaryRange(elements[index + 1])); uint32_t q = elements[++index]; int32_t step; - if((q & SEC_TER_DELTA_FLAG) == 0 && (step = (int32_t)q & PRIMARY_STEP_MASK) != 0) { + if ((q & SEC_TER_DELTA_FLAG) == 0 && (step = static_cast(q) & PRIMARY_STEP_MASK) != 0) { // Return the next primary in this range. if((p & 0xffff) == 0) { return Collation::incTwoBytePrimaryByOffset(p, isCompressible, step); @@ -198,7 +198,7 @@ CollationRootElements::getSecondaryAfter(int32_t index, uint32_t s) const { if(index == 0) { // primary = 0 U_ASSERT(s != 0); - index = (int32_t)elements[IX_FIRST_SECONDARY_INDEX]; + index = static_cast(elements[IX_FIRST_SECONDARY_INDEX]); secTer = elements[index]; // Gap at the end of the secondary CE range. secLimit = 0x10000; @@ -225,11 +225,11 @@ CollationRootElements::getTertiaryAfter(int32_t index, uint32_t s, uint32_t t) c // primary = 0 if(s == 0) { U_ASSERT(t != 0); - index = (int32_t)elements[IX_FIRST_TERTIARY_INDEX]; + index = static_cast(elements[IX_FIRST_TERTIARY_INDEX]); // Gap at the end of the tertiary CE range. terLimit = 0x4000; } else { - index = (int32_t)elements[IX_FIRST_SECONDARY_INDEX]; + index = static_cast(elements[IX_FIRST_SECONDARY_INDEX]); // Gap for tertiaries of primary/secondary CEs. terLimit = getTertiaryBoundary(); } @@ -287,7 +287,7 @@ CollationRootElements::findP(uint32_t p) const { // For example, it might be a reordering group boundary. U_ASSERT((p >> 24) != Collation::UNASSIGNED_IMPLICIT_BYTE); // modified binary search - int32_t start = (int32_t)elements[IX_FIRST_PRIMARY_INDEX]; + int32_t start = static_cast(elements[IX_FIRST_PRIMARY_INDEX]); U_ASSERT(p >= elements[start]); int32_t limit = length - 1; U_ASSERT(elements[limit] >= PRIMARY_SENTINEL); diff --git a/icu4c/source/i18n/collationruleparser.cpp b/icu4c/source/i18n/collationruleparser.cpp index def5ea096d47..b20d2c9428c4 100644 --- a/icu4c/source/i18n/collationruleparser.cpp +++ b/icu4c/source/i18n/collationruleparser.cpp @@ -378,7 +378,7 @@ CollationRuleParser::parseString(int32_t i, UnicodeString &raw, UErrorCode &erro if(c == 0x27) { // apostrophe if(i < rules->length() && rules->charAt(i) == 0x27) { // Double apostrophe, encodes a single one. - raw.append((char16_t)0x27); + raw.append(static_cast(0x27)); ++i; continue; } @@ -398,7 +398,7 @@ CollationRuleParser::parseString(int32_t i, UnicodeString &raw, UErrorCode &erro break; } } - raw.append((char16_t)c); + raw.append(static_cast(c)); } } else if(c == 0x5c) { // backslash if(i == rules->length()) { @@ -418,7 +418,7 @@ CollationRuleParser::parseString(int32_t i, UnicodeString &raw, UErrorCode &erro --i; break; } else { - raw.append((char16_t)c); + raw.append(static_cast(c)); } } for(int32_t j = 0; j < raw.length();) { @@ -466,16 +466,16 @@ CollationRuleParser::parseSpecialPosition(int32_t i, UnicodeString &str, UErrorC ++j; for(int32_t pos = 0; pos < UPRV_LENGTHOF(positions); ++pos) { if(raw == UnicodeString(positions[pos], -1, US_INV)) { - str.setTo((char16_t)POS_LEAD).append((char16_t)(POS_BASE + pos)); + str.setTo(POS_LEAD).append(static_cast(POS_BASE + pos)); return j; } } if(raw == UNICODE_STRING_SIMPLE("top")) { - str.setTo((char16_t)POS_LEAD).append((char16_t)(POS_BASE + LAST_REGULAR)); + str.setTo(POS_LEAD).append(static_cast(POS_BASE + LAST_REGULAR)); return j; } if(raw == UNICODE_STRING_SIMPLE("variable top")) { - str.setTo((char16_t)POS_LEAD).append((char16_t)(POS_BASE + LAST_VARIABLE)); + str.setTo(POS_LEAD).append(static_cast(POS_BASE + LAST_VARIABLE)); return j; } } @@ -507,7 +507,7 @@ CollationRuleParser::parseSetting(UErrorCode &errorCode) { return; } UnicodeString v; - int32_t valueIndex = raw.lastIndexOf((char16_t)0x20); + int32_t valueIndex = raw.lastIndexOf(static_cast(0x20)); if(valueIndex >= 0) { v.setTo(raw, valueIndex + 1); raw.truncate(valueIndex); @@ -694,7 +694,7 @@ CollationRuleParser::parseReordering(const UnicodeString &raw, UErrorCode &error CharString word; while(i < raw.length()) { ++i; // skip the word-separating space - int32_t limit = raw.indexOf((char16_t)0x20, i); + int32_t limit = raw.indexOf(static_cast(0x20), i); if(limit < 0) { limit = raw.length(); } word.clear().appendInvariantChars(raw.tempSubStringBetween(i, limit), errorCode); if(U_FAILURE(errorCode)) { return; } diff --git a/icu4c/source/i18n/collationsets.cpp b/icu4c/source/i18n/collationsets.cpp index 62e6a5d1806e..a73c7fafdd0b 100644 --- a/icu4c/source/i18n/collationsets.cpp +++ b/icu4c/source/i18n/collationsets.cpp @@ -222,7 +222,7 @@ TailoredSet::comparePrefixes(UChar32 c, const char16_t *p, const char16_t *q) { const UnicodeString *bp = nullptr; // Base prefix. // Use a string with a U+FFFF as the limit sentinel. // U+FFFF is untailorable and will not occur in prefixes. - UnicodeString none((char16_t)0xffff); + UnicodeString none(static_cast(0xffff)); for(;;) { if(tp == nullptr) { if(prefixes.next(errorCode)) { @@ -242,15 +242,15 @@ TailoredSet::comparePrefixes(UChar32 c, const char16_t *p, const char16_t *q) { int32_t cmp = tp->compare(*bp); if(cmp < 0) { // tp occurs in the tailoring but not in the base. - addPrefix(data, *tp, c, (uint32_t)prefixes.getValue()); + addPrefix(data, *tp, c, static_cast(prefixes.getValue())); tp = nullptr; } else if(cmp > 0) { // bp occurs in the base but not in the tailoring. - addPrefix(baseData, *bp, c, (uint32_t)basePrefixes.getValue()); + addPrefix(baseData, *bp, c, static_cast(basePrefixes.getValue())); bp = nullptr; } else { setPrefix(*tp); - compare(c, (uint32_t)prefixes.getValue(), (uint32_t)basePrefixes.getValue()); + compare(c, static_cast(prefixes.getValue()), static_cast(basePrefixes.getValue())); resetPrefix(); tp = nullptr; bp = nullptr; @@ -268,8 +268,8 @@ TailoredSet::compareContractions(UChar32 c, const char16_t *p, const char16_t *q // Use a string with two U+FFFF as the limit sentinel. // U+FFFF is untailorable and will not occur in contractions except maybe // as a single suffix character for a root-collator boundary contraction. - UnicodeString none((char16_t)0xffff); - none.append((char16_t)0xffff); + UnicodeString none(static_cast(0xffff)); + none.append(static_cast(0xffff)); for(;;) { if(ts == nullptr) { if(suffixes.next(errorCode)) { @@ -297,7 +297,7 @@ TailoredSet::compareContractions(UChar32 c, const char16_t *p, const char16_t *q bs = nullptr; } else { suffix = ts; - compare(c, (uint32_t)suffixes.getValue(), (uint32_t)baseSuffixes.getValue()); + compare(c, static_cast(suffixes.getValue()), static_cast(baseSuffixes.getValue())); suffix = nullptr; ts = nullptr; bs = nullptr; @@ -309,7 +309,7 @@ void TailoredSet::addPrefixes(const CollationData *d, UChar32 c, const char16_t *p) { UCharsTrie::Iterator prefixes(p, 0, errorCode); while(prefixes.next(errorCode)) { - addPrefix(d, prefixes.getString(), c, (uint32_t)prefixes.getValue()); + addPrefix(d, prefixes.getString(), c, static_cast(prefixes.getValue())); } } @@ -512,7 +512,7 @@ ContractionsAndExpansions::handleCE32(UChar32 start, UChar32 end, uint32_t ce32) UTF16CollationIterator iter(data, false, nullptr, nullptr, nullptr); char16_t hangul[1] = { 0 }; for(UChar32 c = start; c <= end; ++c) { - hangul[0] = (char16_t)c; + hangul[0] = static_cast(c); iter.setText(hangul, hangul + 1); int32_t length = iter.fetchCEs(errorCode); if(U_FAILURE(errorCode)) { return; } @@ -551,7 +551,7 @@ ContractionsAndExpansions::handlePrefixes( // that always yield expansions. addStrings(start, end, contractions); addStrings(start, end, expansions); - handleCE32(start, end, (uint32_t)prefixes.getValue()); + handleCE32(start, end, static_cast(prefixes.getValue())); } resetPrefix(); } @@ -577,7 +577,7 @@ ContractionsAndExpansions::handleContractions( if(!unreversedPrefix.isEmpty()) { addStrings(start, end, expansions); } - handleCE32(start, end, (uint32_t)suffixes.getValue()); + handleCE32(start, end, static_cast(suffixes.getValue())); } suffix = nullptr; } diff --git a/icu4c/source/i18n/collationsettings.cpp b/icu4c/source/i18n/collationsettings.cpp index 1533daf38c7a..660efc12f63b 100644 --- a/icu4c/source/i18n/collationsettings.cpp +++ b/icu4c/source/i18n/collationsettings.cpp @@ -158,9 +158,9 @@ CollationSettings::setReordering(const CollationData &data, int32_t firstSplitByteRangeIndex = -1; for(int32_t i = 0; i < rangesLength; ++i) { uint32_t pair = ranges[i]; - int32_t limit1 = (int32_t)(pair >> 24); + int32_t limit1 = static_cast(pair >> 24); while(b < limit1) { - table[b] = (uint8_t)(b + pair); + table[b] = static_cast(b + pair); ++b; } // Check the second byte of the limit. @@ -173,7 +173,7 @@ CollationSettings::setReordering(const CollationData &data, } } while(b <= 0xff) { - table[b] = (uint8_t)b; + table[b] = static_cast(b); ++b; } if(firstSplitByteRangeIndex < 0) { @@ -200,7 +200,7 @@ CollationSettings::setReorderArrays(const int32_t *codes, int32_t codesLength, } else { // Allocate one memory block for the codes, the ranges, and the 16-aligned table. int32_t capacity = (totalLength + 3) & ~3; // round up to a multiple of 4 ints - ownedCodes = (int32_t *)uprv_malloc(capacity * 4 + 256); + ownedCodes = static_cast(uprv_malloc(capacity * 4 + 256)); if(ownedCodes == nullptr) { resetReordering(); errorCode = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/collationsettings.h b/icu4c/source/i18n/collationsettings.h index 43a181211c07..6ef3c8a8d759 100644 --- a/icu4c/source/i18n/collationsettings.h +++ b/icu4c/source/i18n/collationsettings.h @@ -136,7 +136,7 @@ struct U_I18N_API CollationSettings : public SharedObject { inline uint32_t reorder(uint32_t p) const { uint8_t b = reorderTable[p >> 24]; if(b != 0 || p <= Collation::NO_CE_PRIMARY) { - return ((uint32_t)b << 24) | (p & 0xffffff); + return (static_cast(b) << 24) | (p & 0xffffff); } else { return reorderEx(p); } @@ -178,7 +178,7 @@ struct U_I18N_API CollationSettings : public SharedObject { void setMaxVariable(int32_t value, int32_t defaultOptions, UErrorCode &errorCode); MaxVariable getMaxVariable() const { - return (MaxVariable)((options & MAX_VARIABLE_MASK) >> MAX_VARIABLE_SHIFT); + return static_cast((options & MAX_VARIABLE_MASK) >> MAX_VARIABLE_SHIFT); } /** diff --git a/icu4c/source/i18n/collationtailoring.cpp b/icu4c/source/i18n/collationtailoring.cpp index 8d22cf251660..63419af74fa7 100644 --- a/icu4c/source/i18n/collationtailoring.cpp +++ b/icu4c/source/i18n/collationtailoring.cpp @@ -101,7 +101,7 @@ CollationTailoring::setVersion(const UVersionInfo baseVersion, const UVersionInf int32_t CollationTailoring::getUCAVersion() const { - return ((int32_t)version[1] << 4) | (version[2] >> 6); + return (static_cast(version[1]) << 4) | (version[2] >> 6); } CollationCacheEntry::~CollationCacheEntry() { diff --git a/icu4c/source/i18n/collationweights.cpp b/icu4c/source/i18n/collationweights.cpp index 2351484590c9..6a4c32bc6015 100644 --- a/icu4c/source/i18n/collationweights.cpp +++ b/icu4c/source/i18n/collationweights.cpp @@ -42,13 +42,13 @@ U_NAMESPACE_BEGIN static inline uint32_t getWeightTrail(uint32_t weight, int32_t length) { - return (uint32_t)(weight>>(8*(4-length)))&0xff; + return (weight >> (8 * (4 - length))) & 0xff; } static inline uint32_t setWeightTrail(uint32_t weight, int32_t length, uint32_t trail) { length=8*(4-length); - return (uint32_t)((weight&(0xffffff00<((weight & (0xffffff00 << length)) | (trail << length)); } static inline uint32_t @@ -62,7 +62,7 @@ setWeightByte(uint32_t weight, int32_t idx, uint32_t byte) { idx*=8; if(idx<32) { - mask=((uint32_t)0xffffffff)>>idx; + mask = (static_cast(0xffffffff)) >> idx; } else { // Do not use uint32_t>>32 because on some platforms that does not shift at all // while we need it to become 0. @@ -77,22 +77,22 @@ setWeightByte(uint32_t weight, int32_t idx, uint32_t byte) { } idx=32-idx; mask|=0xffffff00<(weight & (0xffffffff << (8 * (4 - length)))); } static inline uint32_t incWeightTrail(uint32_t weight, int32_t length) { - return (uint32_t)(weight+(1UL<<(8*(4-length)))); + return static_cast(weight + (1UL << (8 * (4 - length)))); } static inline uint32_t decWeightTrail(uint32_t weight, int32_t length) { - return (uint32_t)(weight-(1UL<<(8*(4-length)))); + return static_cast(weight - (1UL << (8 * (4 - length)))); } CollationWeights::CollationWeights() @@ -169,7 +169,7 @@ uint32_t CollationWeights::incWeightByOffset(uint32_t weight, int32_t length, int32_t offset) const { for(;;) { offset += getWeightByte(weight, length); - if((uint32_t)offset <= maxBytes[length]) { + if (static_cast(offset) <= maxBytes[length]) { return setWeightByte(weight, length, offset); } else { // Split the offset between this byte and the previous one. @@ -196,8 +196,8 @@ static int32_t U_CALLCONV compareRanges(const void * /*context*/, const void *left, const void *right) { uint32_t l, r; - l=((const CollationWeights::WeightRange *)left)->start; - r=((const CollationWeights::WeightRange *)right)->start; + l = static_cast(left)->start; + r = static_cast(right)->start; if(lr) { @@ -295,7 +295,7 @@ CollationWeights::getWeightRanges(uint32_t lowerLimit, uint32_t upperLimit) { /* set the middle range */ middle.length=middleLength; if(middle.end>=middle.start) { - middle.count=(int32_t)((middle.end-middle.start)>>(8*(4-middleLength)))+1; + middle.count = static_cast((middle.end - middle.start) >> (8 * (4 - middleLength))) + 1; } else { /* no middle range, eliminate overlaps */ for(int32_t length=4; length>middleLength; --length) { @@ -322,8 +322,8 @@ CollationWeights::getWeightRanges(uint32_t lowerLimit, uint32_t upperLimit) { // Intersect these two ranges. lower[length].end=upper[length].end; lower[length].count= - (int32_t)getWeightTrail(lower[length].end, length)- - (int32_t)getWeightTrail(lower[length].start, length)+1; + static_cast(getWeightTrail(lower[length].end, length)) - + static_cast(getWeightTrail(lower[length].start, length)) + 1; // count might be <=0 in which case there is no room, // and the range-collecting code below will ignore this range. merged=true; diff --git a/icu4c/source/i18n/collationweights.h b/icu4c/source/i18n/collationweights.h index 0d20b927b269..b893baba80c2 100644 --- a/icu4c/source/i18n/collationweights.h +++ b/icu4c/source/i18n/collationweights.h @@ -84,7 +84,7 @@ class U_I18N_API CollationWeights : public UMemory { private: /** @return number of usable byte values for byte idx */ inline int32_t countBytes(int32_t idx) const { - return (int32_t)(maxBytes[idx] - minBytes[idx] + 1); + return static_cast(maxBytes[idx] - minBytes[idx] + 1); } uint32_t incWeight(uint32_t weight, int32_t length) const; diff --git a/icu4c/source/i18n/cpdtrans.cpp b/icu4c/source/i18n/cpdtrans.cpp index c419153e43c7..99643da07eb9 100644 --- a/icu4c/source/i18n/cpdtrans.cpp +++ b/icu4c/source/i18n/cpdtrans.cpp @@ -196,7 +196,7 @@ void CompoundTransliterator::init(UVector& list, // Allocate array if (U_SUCCESS(status)) { count = list.size(); - trans = (Transliterator **)uprv_malloc(count * sizeof(Transliterator *)); + trans = static_cast(uprv_malloc(count * sizeof(Transliterator*))); /* test for nullptr */ if (trans == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -214,7 +214,7 @@ void CompoundTransliterator::init(UVector& list, int32_t i; for (i=0; i(list.elementAt(j)); } // If the direction is UTRANS_REVERSE then we may need to fix the @@ -296,7 +296,7 @@ CompoundTransliterator& CompoundTransliterator::operator=( if (trans != nullptr) { uprv_free(trans); } - trans = (Transliterator **)uprv_malloc(t.count * sizeof(Transliterator *)); + trans = static_cast(uprv_malloc(t.count * sizeof(Transliterator*))); } count = t.count; if (trans != nullptr) { @@ -347,7 +347,7 @@ const Transliterator& CompoundTransliterator::getTransliterator(int32_t index) c void CompoundTransliterator::setTransliterators(Transliterator* const transliterators[], int32_t transCount) { - Transliterator** a = (Transliterator **)uprv_malloc(transCount * sizeof(Transliterator *)); + Transliterator** a = static_cast(uprv_malloc(transCount * sizeof(Transliterator*))); if (a == nullptr) { return; } diff --git a/icu4c/source/i18n/csdetect.cpp b/icu4c/source/i18n/csdetect.cpp index 158014351072..cedc3c063490 100644 --- a/icu4c/source/i18n/csdetect.cpp +++ b/icu4c/source/i18n/csdetect.cpp @@ -162,7 +162,7 @@ CharsetDetector::CharsetDetector(UErrorCode &status) return; } - resultArray = (CharsetMatch **)uprv_malloc(sizeof(CharsetMatch *)*fCSRecognizers_size); + resultArray = static_cast(uprv_malloc(sizeof(CharsetMatch*) * fCSRecognizers_size)); if (resultArray == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -459,7 +459,7 @@ UEnumeration * CharsetDetector::getAllDetectableCharsets(UErrorCode &status) return nullptr; } uprv_memset(en->context, 0, sizeof(Context)); - ((Context*)en->context)->all = true; + static_cast(en->context)->all = true; return en; } @@ -482,8 +482,8 @@ UEnumeration * CharsetDetector::getDetectableCharsets(UErrorCode &status) const return nullptr; } uprv_memset(en->context, 0, sizeof(Context)); - ((Context*)en->context)->all = false; - ((Context*)en->context)->enabledRecognizers = fEnabledRecognizers; + static_cast(en->context)->all = false; + static_cast(en->context)->enabledRecognizers = fEnabledRecognizers; return en; } diff --git a/icu4c/source/i18n/csmatch.cpp b/icu4c/source/i18n/csmatch.cpp index 4c5f73b31b03..35a84c76f282 100644 --- a/icu4c/source/i18n/csmatch.cpp +++ b/icu4c/source/i18n/csmatch.cpp @@ -61,7 +61,7 @@ int32_t CharsetMatch::getConfidence()const int32_t CharsetMatch::getUChars(char16_t *buf, int32_t cap, UErrorCode *status) const { UConverter *conv = ucnv_open(getName(), status); - int32_t result = ucnv_toUChars(conv, buf, cap, (const char *) textIn->fRawInput, textIn->fRawLength, status); + int32_t result = ucnv_toUChars(conv, buf, cap, reinterpret_cast(textIn->fRawInput), textIn->fRawLength, status); ucnv_close(conv); diff --git a/icu4c/source/i18n/csr2022.cpp b/icu4c/source/i18n/csr2022.cpp index e064c426a2a2..9de668a8a07d 100644 --- a/icu4c/source/i18n/csr2022.cpp +++ b/icu4c/source/i18n/csr2022.cpp @@ -46,7 +46,7 @@ int32_t CharsetRecog_2022::match_2022(const uint8_t *text, int32_t textLen, cons escN = 0; while(escN < escapeSequences_length) { const uint8_t *seq = escapeSequences[escN]; - int32_t seq_length = (int32_t)uprv_strlen((const char *) seq); + int32_t seq_length = static_cast(uprv_strlen((const char*)seq)); if (textLen-i >= seq_length) { j = 1; diff --git a/icu4c/source/i18n/csrmbcs.cpp b/icu4c/source/i18n/csrmbcs.cpp index a6bd1d3a1e37..cb78a3433b2a 100644 --- a/icu4c/source/i18n/csrmbcs.cpp +++ b/icu4c/source/i18n/csrmbcs.cpp @@ -219,9 +219,9 @@ int32_t CharsetRecog_mbcs::match_mbcs(InputText *det, const uint16_t commonChars // Frequency of occurrence statistics exist. // - double maxVal = log((double)doubleByteCharCount / 4); /*(float)?*/ + double maxVal = log(static_cast(doubleByteCharCount) / 4); /*(float)?*/ double scaleFactor = 90.0 / maxVal; - confidence = (int32_t)(log((double)commonCharCount+1) * scaleFactor + 10.0); + confidence = static_cast(log(static_cast(commonCharCount) + 1) * scaleFactor + 10.0); confidence = min(confidence, 100); } diff --git a/icu4c/source/i18n/csrsbcs.cpp b/icu4c/source/i18n/csrsbcs.cpp index 92af9b5291b9..de2ad314b026 100644 --- a/icu4c/source/i18n/csrsbcs.cpp +++ b/icu4c/source/i18n/csrsbcs.cpp @@ -127,7 +127,7 @@ int32_t NGramParser::parse(InputText *det) // TODO: Is this OK? The buffer could have ended in the middle of a word... addByte(0x20); - double rawPercent = (double) hitCount / (double) ngramCount; + double rawPercent = static_cast(hitCount) / static_cast(ngramCount); // if (rawPercent <= 2.0) { // return 0; @@ -139,7 +139,7 @@ int32_t NGramParser::parse(InputText *det) return 98; } - return (int32_t) (rawPercent * 300.0); + return static_cast(rawPercent * 300.0); } #if !UCONFIG_ONLY_HTML_CONVERSION diff --git a/icu4c/source/i18n/currpinf.cpp b/icu4c/source/i18n/currpinf.cpp index 7c5adaaf7c39..6f43ecb2fedf 100644 --- a/icu4c/source/i18n/currpinf.cpp +++ b/icu4c/source/i18n/currpinf.cpp @@ -185,12 +185,12 @@ UnicodeString& CurrencyPluralInfo::getCurrencyPluralPattern(const UnicodeString& pluralCount, UnicodeString& result) const { const UnicodeString* currencyPluralPattern = - (UnicodeString*)fPluralCountToCurrencyUnitPattern->get(pluralCount); + static_cast(fPluralCountToCurrencyUnitPattern->get(pluralCount)); if (currencyPluralPattern == nullptr) { // fall back to "other" if (pluralCount.compare(gPluralCountOther, 5)) { currencyPluralPattern = - (UnicodeString*)fPluralCountToCurrencyUnitPattern->get(UnicodeString(true, gPluralCountOther, 5)); + static_cast(fPluralCountToCurrencyUnitPattern->get(UnicodeString(true, gPluralCountOther, 5))); } if (currencyPluralPattern == nullptr) { // no currencyUnitPatterns defined, @@ -388,7 +388,7 @@ CurrencyPluralInfo::deleteHash(Hashtable* hTable) { const UHashElement* element = nullptr; while ( (element = hTable->nextElement(pos)) != nullptr ) { const UHashTok valueTok = element->value; - const UnicodeString* value = (UnicodeString*)valueTok.pointer; + const UnicodeString* value = static_cast(valueTok.pointer); delete value; } delete hTable; @@ -420,9 +420,9 @@ CurrencyPluralInfo::copyHash(const Hashtable* source, if (source) { while ( (element = source->nextElement(pos)) != nullptr ) { const UHashTok keyTok = element->key; - const UnicodeString* key = (UnicodeString*)keyTok.pointer; + const UnicodeString* key = static_cast(keyTok.pointer); const UHashTok valueTok = element->value; - const UnicodeString* value = (UnicodeString*)valueTok.pointer; + const UnicodeString* value = static_cast(valueTok.pointer); LocalPointer copy(new UnicodeString(*value), status); if (U_FAILURE(status)) { return; diff --git a/icu4c/source/i18n/dangical.cpp b/icu4c/source/i18n/dangical.cpp index e1cf62953717..64e7e0be02f6 100644 --- a/icu4c/source/i18n/dangical.cpp +++ b/icu4c/source/i18n/dangical.cpp @@ -122,9 +122,9 @@ const char *DangiCalendar::getType() const { */ static void U_CALLCONV initAstronomerTimeZone(UErrorCode &status) { U_ASSERT(gAstronomerTimeZone == nullptr); - const UDate millis1897[] = { (UDate)((1897 - 1970) * 365 * kOneDay) }; // some days of error is not a problem here - const UDate millis1898[] = { (UDate)((1898 - 1970) * 365 * kOneDay) }; // some days of error is not a problem here - const UDate millis1912[] = { (UDate)((1912 - 1970) * 365 * kOneDay) }; // this doesn't create an issue for 1911/12/20 + const UDate millis1897[] = { static_cast((1897 - 1970) * 365 * kOneDay) }; // some days of error is not a problem here + const UDate millis1898[] = { static_cast((1898 - 1970) * 365 * kOneDay) }; // some days of error is not a problem here + const UDate millis1912[] = { static_cast((1912 - 1970) * 365 * kOneDay) }; // this doesn't create an issue for 1911/12/20 LocalPointer initialTimeZone(new InitialTimeZoneRule( UnicodeString(u"GMT+8"), 8*kOneHour, 0), status); diff --git a/icu4c/source/i18n/datefmt.cpp b/icu4c/source/i18n/datefmt.cpp index c62201988f64..80f74ede65df 100644 --- a/icu4c/source/i18n/datefmt.cpp +++ b/icu4c/source/i18n/datefmt.cpp @@ -89,7 +89,7 @@ class DateFmtBestPatternKey : public LocaleCacheKey { fSkeleton(other.fSkeleton) { } virtual ~DateFmtBestPatternKey(); virtual int32_t hashCode() const override { - return (int32_t)(37u * (uint32_t)LocaleCacheKey::hashCode() + (uint32_t)fSkeleton.hashCode()); + return static_cast(37u * static_cast(LocaleCacheKey::hashCode()) + static_cast(fSkeleton.hashCode())); } inline bool operator==(const DateFmtBestPatternKey &other) const { return fSkeleton == other.fSkeleton; @@ -207,10 +207,10 @@ DateFormat::format(const Formattable& obj, date = obj.getDate(); break; case Formattable::kDouble: - date = (UDate)obj.getDouble(); + date = static_cast(obj.getDouble()); break; case Formattable::kLong: - date = (UDate)obj.getLong(); + date = static_cast(obj.getLong()); break; default: status = U_ILLEGAL_ARGUMENT_ERROR; @@ -242,10 +242,10 @@ DateFormat::format(const Formattable& obj, date = obj.getDate(); break; case Formattable::kDouble: - date = (UDate)obj.getDouble(); + date = static_cast(obj.getDouble()); break; case Formattable::kLong: - date = (UDate)obj.getLong(); + date = static_cast(obj.getLong()); break; default: status = U_ILLEGAL_ARGUMENT_ERROR; @@ -430,7 +430,7 @@ DateFormat::createDateTimeInstance(EStyle dateStyle, { if(dateStyle != kNone) { - dateStyle = (EStyle) (dateStyle + kDateOffset); + dateStyle = static_cast(dateStyle + kDateOffset); } return create(timeStyle, dateStyle, aLocale); } @@ -540,7 +540,7 @@ DateFormat::create(EStyle timeStyle, EStyle dateStyle, const Locale& locale) // is it relative? if(/*((timeStyle!=UDAT_NONE)&&(timeStyle & UDAT_RELATIVE)) || */((dateStyle!=kNone)&&((dateStyle-kDateOffset) & UDAT_RELATIVE))) { - RelativeDateFormat *r = new RelativeDateFormat((UDateFormatStyle)timeStyle, (UDateFormatStyle)(dateStyle-kDateOffset), locale, status); + RelativeDateFormat* r = new RelativeDateFormat(static_cast(timeStyle), static_cast(dateStyle - kDateOffset), locale, status); if(U_SUCCESS(status)) return r; delete r; status = U_ZERO_ERROR; @@ -719,7 +719,7 @@ void DateFormat::setContext(UDisplayContext value, UErrorCode& status) { if (U_FAILURE(status)) return; - if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) { + if (static_cast(static_cast(value) >> 8) == UDISPCTX_TYPE_CAPITALIZATION) { fCapitalizationContext = value; } else { status = U_ILLEGAL_ARGUMENT_ERROR; @@ -733,10 +733,10 @@ void DateFormat::setContext(UDisplayContext value, UErrorCode& status) UDisplayContext DateFormat::getContext(UDisplayContextType type, UErrorCode& status) const { if (U_FAILURE(status)) - return (UDisplayContext)0; + return static_cast(0); if (type != UDISPCTX_TYPE_CAPITALIZATION) { status = U_ILLEGAL_ARGUMENT_ERROR; - return (UDisplayContext)0; + return static_cast(0); } return fCapitalizationContext; } diff --git a/icu4c/source/i18n/dcfmtsym.cpp b/icu4c/source/i18n/dcfmtsym.cpp index ac1f777399ad..b4c90e6765a7 100644 --- a/icu4c/source/i18n/dcfmtsym.cpp +++ b/icu4c/source/i18n/dcfmtsym.cpp @@ -154,11 +154,11 @@ DecimalFormatSymbols& DecimalFormatSymbols::operator=(const DecimalFormatSymbols& rhs) { if (this != &rhs) { - for(int32_t i = 0; i < (int32_t)kFormatSymbolCount; ++i) { + for (int32_t i = 0; i < static_cast(kFormatSymbolCount); ++i) { // fastCopyFrom is safe, see docs on fSymbols - fSymbols[(ENumberFormatSymbol)i].fastCopyFrom(rhs.fSymbols[(ENumberFormatSymbol)i]); + fSymbols[static_cast(i)].fastCopyFrom(rhs.fSymbols[static_cast(i)]); } - for(int32_t i = 0; i < (int32_t)UNUM_CURRENCY_SPACING_COUNT; ++i) { + for (int32_t i = 0; i < static_cast(UNUM_CURRENCY_SPACING_COUNT); ++i) { currencySpcBeforeSym[i].fastCopyFrom(rhs.currencySpcBeforeSym[i]); currencySpcAfterSym[i].fastCopyFrom(rhs.currencySpcAfterSym[i]); } @@ -188,12 +188,12 @@ DecimalFormatSymbols::operator==(const DecimalFormatSymbols& that) const if (fIsCustomIntlCurrencySymbol != that.fIsCustomIntlCurrencySymbol) { return false; } - for(int32_t i = 0; i < (int32_t)kFormatSymbolCount; ++i) { - if(fSymbols[(ENumberFormatSymbol)i] != that.fSymbols[(ENumberFormatSymbol)i]) { + for (int32_t i = 0; i < static_cast(kFormatSymbolCount); ++i) { + if (fSymbols[static_cast(i)] != that.fSymbols[static_cast(i)]) { return false; } } - for(int32_t i = 0; i < (int32_t)UNUM_CURRENCY_SPACING_COUNT; ++i) { + for (int32_t i = 0; i < static_cast(UNUM_CURRENCY_SPACING_COUNT); ++i) { if(currencySpcBeforeSym[i] != that.currencySpcBeforeSym[i]) { return false; } @@ -242,7 +242,7 @@ struct DecFmtSymDataSink : public ResourceSink { if (!seenSymbol[i]) { seenSymbol[i] = true; dfs.setSymbol( - (DecimalFormatSymbols::ENumberFormatSymbol) i, + static_cast(i), value.getUnicodeString(errorCode)); if (U_FAILURE(errorCode)) { return; } } @@ -331,11 +331,11 @@ struct CurrencySpacingSink : public ResourceSink { static const char* defaults[] = { "[:letter:]", "[:digit:]", " " }; if (!hasBeforeCurrency || !hasAfterCurrency) { for (int32_t pattern = 0; pattern < UNUM_CURRENCY_SPACING_COUNT; pattern++) { - dfs.setPatternForCurrencySpacing((UCurrencySpacing)pattern, + dfs.setPatternForCurrencySpacing(static_cast(pattern), false, UnicodeString(defaults[pattern], -1, US_INV)); } for (int32_t pattern = 0; pattern < UNUM_CURRENCY_SPACING_COUNT; pattern++) { - dfs.setPatternForCurrencySpacing((UCurrencySpacing)pattern, + dfs.setPatternForCurrencySpacing(static_cast(pattern), true, UnicodeString(defaults[pattern], -1, US_INV)); } } @@ -485,34 +485,34 @@ DecimalFormatSymbols::initialize() { * cannot initialize a static array with class constructors. * markus 2000may25 */ - fSymbols[kDecimalSeparatorSymbol] = (char16_t)0x2e; // '.' decimal separator + fSymbols[kDecimalSeparatorSymbol] = static_cast(0x2e); // '.' decimal separator fSymbols[kGroupingSeparatorSymbol].remove(); // group (thousands) separator - fSymbols[kPatternSeparatorSymbol] = (char16_t)0x3b; // ';' pattern separator - fSymbols[kPercentSymbol] = (char16_t)0x25; // '%' percent sign - fSymbols[kZeroDigitSymbol] = (char16_t)0x30; // '0' native 0 digit - fSymbols[kOneDigitSymbol] = (char16_t)0x31; // '1' native 1 digit - fSymbols[kTwoDigitSymbol] = (char16_t)0x32; // '2' native 2 digit - fSymbols[kThreeDigitSymbol] = (char16_t)0x33; // '3' native 3 digit - fSymbols[kFourDigitSymbol] = (char16_t)0x34; // '4' native 4 digit - fSymbols[kFiveDigitSymbol] = (char16_t)0x35; // '5' native 5 digit - fSymbols[kSixDigitSymbol] = (char16_t)0x36; // '6' native 6 digit - fSymbols[kSevenDigitSymbol] = (char16_t)0x37; // '7' native 7 digit - fSymbols[kEightDigitSymbol] = (char16_t)0x38; // '8' native 8 digit - fSymbols[kNineDigitSymbol] = (char16_t)0x39; // '9' native 9 digit - fSymbols[kDigitSymbol] = (char16_t)0x23; // '#' pattern digit - fSymbols[kPlusSignSymbol] = (char16_t)0x002b; // '+' plus sign - fSymbols[kMinusSignSymbol] = (char16_t)0x2d; // '-' minus sign - fSymbols[kCurrencySymbol] = (char16_t)0xa4; // 'OX' currency symbol + fSymbols[kPatternSeparatorSymbol] = static_cast(0x3b); // ';' pattern separator + fSymbols[kPercentSymbol] = static_cast(0x25); // '%' percent sign + fSymbols[kZeroDigitSymbol] = static_cast(0x30); // '0' native 0 digit + fSymbols[kOneDigitSymbol] = static_cast(0x31); // '1' native 1 digit + fSymbols[kTwoDigitSymbol] = static_cast(0x32); // '2' native 2 digit + fSymbols[kThreeDigitSymbol] = static_cast(0x33); // '3' native 3 digit + fSymbols[kFourDigitSymbol] = static_cast(0x34); // '4' native 4 digit + fSymbols[kFiveDigitSymbol] = static_cast(0x35); // '5' native 5 digit + fSymbols[kSixDigitSymbol] = static_cast(0x36); // '6' native 6 digit + fSymbols[kSevenDigitSymbol] = static_cast(0x37); // '7' native 7 digit + fSymbols[kEightDigitSymbol] = static_cast(0x38); // '8' native 8 digit + fSymbols[kNineDigitSymbol] = static_cast(0x39); // '9' native 9 digit + fSymbols[kDigitSymbol] = static_cast(0x23); // '#' pattern digit + fSymbols[kPlusSignSymbol] = static_cast(0x002b); // '+' plus sign + fSymbols[kMinusSignSymbol] = static_cast(0x2d); // '-' minus sign + fSymbols[kCurrencySymbol] = static_cast(0xa4); // 'OX' currency symbol fSymbols[kIntlCurrencySymbol].setTo(true, INTL_CURRENCY_SYMBOL_STR, 2); - fSymbols[kMonetarySeparatorSymbol] = (char16_t)0x2e; // '.' monetary decimal separator - fSymbols[kExponentialSymbol] = (char16_t)0x45; // 'E' exponential - fSymbols[kPerMillSymbol] = (char16_t)0x2030; // '%o' per mill - fSymbols[kPadEscapeSymbol] = (char16_t)0x2a; // '*' pad escape symbol - fSymbols[kInfinitySymbol] = (char16_t)0x221e; // 'oo' infinite - fSymbols[kNaNSymbol] = (char16_t)0xfffd; // SUB NaN - fSymbols[kSignificantDigitSymbol] = (char16_t)0x0040; // '@' significant digit + fSymbols[kMonetarySeparatorSymbol] = static_cast(0x2e); // '.' monetary decimal separator + fSymbols[kExponentialSymbol] = static_cast(0x45); // 'E' exponential + fSymbols[kPerMillSymbol] = static_cast(0x2030); // '%o' per mill + fSymbols[kPadEscapeSymbol] = static_cast(0x2a); // '*' pad escape symbol + fSymbols[kInfinitySymbol] = static_cast(0x221e); // 'oo' infinite + fSymbols[kNaNSymbol] = static_cast(0xfffd); // SUB NaN + fSymbols[kSignificantDigitSymbol] = static_cast(0x0040); // '@' significant digit fSymbols[kMonetaryGroupingSeparatorSymbol].remove(); // - fSymbols[kExponentMultiplicationSymbol] = (char16_t)0xd7; // 'x' multiplication symbol for exponents + fSymbols[kExponentMultiplicationSymbol] = static_cast(0xd7); // 'x' multiplication symbol for exponents fSymbols[kApproximatelySignSymbol] = u'~'; // '~' approximately sign fIsCustomCurrencySymbol = false; fIsCustomIntlCurrencySymbol = false; @@ -551,11 +551,11 @@ void DecimalFormatSymbols::setCurrency(const char16_t* currency, UErrorCode& sta ures_getByIndex(rb.getAlias(), 2, rb.getAlias(), &localStatus); int32_t currPatternLen = 0; currPattern = - ures_getStringByIndex(rb.getAlias(), (int32_t)0, &currPatternLen, &localStatus); + ures_getStringByIndex(rb.getAlias(), static_cast(0), &currPatternLen, &localStatus); UnicodeString decimalSep = - ures_getUnicodeStringByIndex(rb.getAlias(), (int32_t)1, &localStatus); + ures_getUnicodeStringByIndex(rb.getAlias(), static_cast(1), &localStatus); UnicodeString groupingSep = - ures_getUnicodeStringByIndex(rb.getAlias(), (int32_t)2, &localStatus); + ures_getUnicodeStringByIndex(rb.getAlias(), static_cast(2), &localStatus); if(U_SUCCESS(localStatus)){ fSymbols[kMonetaryGroupingSeparatorSymbol] = groupingSep; fSymbols[kMonetarySeparatorSymbol] = decimalSep; @@ -580,9 +580,9 @@ DecimalFormatSymbols::getPatternForCurrencySpacing(UCurrencySpacing type, return fNoSymbol; // always empty. } if (beforeCurrency) { - return currencySpcBeforeSym[(int32_t)type]; + return currencySpcBeforeSym[static_cast(type)]; } else { - return currencySpcAfterSym[(int32_t)type]; + return currencySpcAfterSym[static_cast(type)]; } } @@ -591,9 +591,9 @@ DecimalFormatSymbols::setPatternForCurrencySpacing(UCurrencySpacing type, UBool beforeCurrency, const UnicodeString& pattern) { if (beforeCurrency) { - currencySpcBeforeSym[(int32_t)type] = pattern; + currencySpcBeforeSym[static_cast(type)] = pattern; } else { - currencySpcAfterSym[(int32_t)type] = pattern; + currencySpcAfterSym[static_cast(type)] = pattern; } } U_NAMESPACE_END diff --git a/icu4c/source/i18n/decNumber.cpp b/icu4c/source/i18n/decNumber.cpp index e21ebfb04f8d..96ad3d7f986a 100644 --- a/icu4c/source/i18n/decNumber.cpp +++ b/icu4c/source/i18n/decNumber.cpp @@ -3876,7 +3876,7 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, /* [following code does not require input rounding] */ /* note whether signs differ [used all paths] */ - diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG); + diffsign = static_cast((lhs->bits ^ rhs->bits ^ negate) & DECNEG); /* handle infinities and NaNs */ if (SPECIALARGS) { /* a special bit set */ @@ -3982,9 +3982,9 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, partial+=*rhs->lsu; if ((partial<=DECDPUNMAX) /* result fits in unit */ && (lhs->digits>=DECDPUN || /* .. and no digits-count change */ - partial<(Int)powers[lhs->digits])) { /* .. */ + partial < static_cast(powers[lhs->digits]))) { /* .. */ if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */ - *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */ + *res->lsu = static_cast(partial); /* [copy could have overwritten RHS] */ break; } /* else drop out for careful add */ @@ -3993,7 +3993,7 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, partial-=*rhs->lsu; if (partial>0) { /* no borrow needed, and non-0 result */ if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */ - *res->lsu=(Unit)partial; + *res->lsu = static_cast(partial); /* this could have reduced digits [but result>0] */ res->digits=decGetDigits(res->lsu, D2U(res->digits)); break; @@ -4022,7 +4022,7 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, if (padding<0) { /* LHS needs the padding */ const decNumber *t; padding=-padding; /* will be +ve */ - bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */ + bits = static_cast(rhs->bits ^ negate); /* assumed sign is now that of RHS */ t=lhs; lhs=rhs; rhs=t; swapped=1; } @@ -4073,7 +4073,7 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, acc=accbuff; /* assume use local buffer */ if (need*sizeof(Unit)>sizeof(accbuff)) { /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */ - allocacc=(Unit *)malloc(need*sizeof(Unit)); + allocacc = static_cast(malloc(need * sizeof(Unit))); if (allocacc==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -4081,7 +4081,7 @@ static decNumber * decAddOp(decNumber *res, const decNumber *lhs, } } - res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */ + res->bits = static_cast(bits & DECNEG); /* it's now safe to overwrite.. */ res->exponent=lhs->exponent; /* .. operands (even if aliased) */ #if DECTRACE @@ -4438,7 +4438,7 @@ static decNumber * decDivideOp(decNumber *res, acclength=D2U(reqdigits+DECDPUN); /* in Units */ if (acclength*sizeof(Unit)>sizeof(accbuff)) { /* printf("malloc dvacc %ld units\n", acclength); */ - allocacc=(Unit *)malloc(acclength*sizeof(Unit)); + allocacc = static_cast(malloc(acclength * sizeof(Unit))); if (allocacc==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -4463,7 +4463,7 @@ static decNumber * decDivideOp(decNumber *res, if (!(op&DIVIDE)) var1units++; if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) { /* printf("malloc dvvar %ld units\n", var1units+1); */ - varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit)); + varalloc = static_cast(malloc((var1units + 1) * sizeof(Unit))); if (varalloc==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -4491,7 +4491,7 @@ static decNumber * decDivideOp(decNumber *res, /* 1 to make sure that the multiplier is never overestimated. */ msu2plus=*msu2; /* it's value .. */ if (var2units>1) msu2plus++; /* .. +1 if any more */ - msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */ + msu2pair = static_cast(*msu2) * (DECDPUNMAX + 1); /* top two pair .. */ if (var2units>1) { /* .. [else treat 2nd as 0] */ msu2pair+=*(msu2-1); /* .. */ if (var2units>2) msu2pair++; /* .. +1 if any more */ @@ -4573,16 +4573,16 @@ static decNumber * decDivideOp(decNumber *res, /* *pv1>v2. Prepare for real subtraction; the lengths are equal */ /* Estimate the multiplier (there's always a msu1-1)... */ /* Bring in two units of var2 to provide a good estimate. */ - mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair); + mult = static_cast((static_cast(*msu1) * (DECDPUNMAX + 1) + *(msu1 - 1)) / msu2pair); } /* lengths the same */ else { /* var1units > var2ulen, so subtraction is safe */ /* The var2 msu is one unit towards the lsu of the var1 msu, */ /* so only one unit for var2 can be used. */ - mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus); + mult = static_cast((static_cast(*msu1) * (DECDPUNMAX + 1) + *(msu1 - 1)) / msu2plus); } if (mult==0) mult=1; /* must always be at least 1 */ /* subtraction needed; var1 is > var2 */ - thisunit=(Unit)(thisunit+mult); /* accumulate */ + thisunit = static_cast(thisunit + mult); /* accumulate */ /* subtract var1-var2, into var1; only the overlap needs */ /* processing, as this is an in-place calculation */ shift=var2ulen-var2units; @@ -4706,7 +4706,7 @@ static decNumber * decDivideOp(decNumber *res, if (set->extended) #endif res->exponent=exp; /* .. with proper exponent */ - res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ + res->bits = static_cast(bits & DECNEG); /* [cleaned] */ decFinish(res, set, &residue, status); /* might clamp */ break; } @@ -4797,7 +4797,7 @@ static decNumber * decDivideOp(decNumber *res, /* subtract [A+B*(-m)]; the result will always be negative */ accunits=-decUnitAddSub(accnext, accunits, rhs->lsu, D2U(rhs->digits), - expunits, accnext, -(Int)powers[exprem]); + expunits, accnext, -static_cast(powers[exprem])); accdigits=decGetDigits(accnext, accunits); /* count digits exactly */ accunits=D2U(accdigits); /* and recalculate the units for copy */ /* [exponent is as for original remainder] */ @@ -4809,7 +4809,7 @@ static decNumber * decDivideOp(decNumber *res, /* Set exponent and bits */ res->exponent=exponent; - res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ + res->bits = static_cast(bits & DECNEG); /* [cleaned] */ /* Now the coefficient. */ decSetCoeff(res, set, accnext, accdigits, &residue, status); @@ -4934,7 +4934,7 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, #endif /* precalculate result sign */ - bits=(uByte)((lhs->bits^rhs->bits)&DECNEG); + bits = static_cast((lhs->bits ^ rhs->bits) & DECNEG); /* handle infinities and NaNs */ if (SPECIALARGS) { /* a special bit set */ @@ -4990,12 +4990,12 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, /* allocate buffers if required, as usual */ needbytes=ilhs*sizeof(uInt); - if (needbytes>(Int)sizeof(zlhibuff)) { - alloclhi=(uInt *)malloc(needbytes); + if (needbytes > static_cast(sizeof(zlhibuff))) { + alloclhi = static_cast(malloc(needbytes)); zlhi=alloclhi;} needbytes=irhs*sizeof(uInt); - if (needbytes>(Int)sizeof(zrhibuff)) { - allocrhi=(uInt *)malloc(needbytes); + if (needbytes > static_cast(sizeof(zrhibuff))) { + allocrhi = static_cast(malloc(needbytes)); zrhi=allocrhi;} /* Allocating the accumulator space needs a special case when */ @@ -5014,14 +5014,14 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, zoff=(iacc+7)/8; /* items to offset by */ needbytes+=zoff*8; #endif - if (needbytes>(Int)sizeof(zaccbuff)) { - allocacc=(uLong *)malloc(needbytes); - zacc=(uLong *)allocacc;} + if (needbytes > static_cast(sizeof(zaccbuff))) { + allocacc = static_cast(malloc(needbytes)); + zacc = static_cast(allocacc);} if (zlhi==nullptr||zrhi==nullptr||zacc==nullptr) { *status|=DEC_Insufficient_storage; break;} - acc=(Unit *)zacc; /* -> target Unit array */ + acc = reinterpret_cast(zacc); /* -> target Unit array */ #if DECDPUN==1 zacc+=zoff; /* start uLong accumulator to right */ #endif @@ -5062,7 +5062,7 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */ lp=zacc+(rip-zrhi); /* where to add the lhs */ for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */ - *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */ + *lp += static_cast(*lip) * (*rip); /* [this should in-line] */ } /* lip loop */ lazy--; if (lazy>0 && rip!=rmsi) continue; @@ -5075,15 +5075,15 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, /* and occasional extra divide (slow) is well worth it, as */ /* it allows FASTLAZY to be increased to 18 rather than 4 */ /* in the FASTDIGS=9 case */ - if (lcarry(lcarry); /* [usual] */ else { /* two-place carry [fairly rare] */ - uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */ + uInt carry2 = static_cast(lcarry / FASTBASE); /* top top part */ *(lp+2)+=carry2; /* add to item+2 */ - *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */ - carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */ + *lp -= (static_cast(FASTBASE) * FASTBASE * carry2); /* [slow] */ + carry = static_cast(lcarry - (static_cast(FASTBASE) * carry2)); /* [inline] */ } *(lp+1)+=carry; /* add to item above [inline] */ - *lp-=((uLong)FASTBASE*carry); /* [inline] */ + *lp -= (static_cast(FASTBASE) * carry); /* [inline] */ } /* carry resolution */ } /* rip loop */ @@ -5094,13 +5094,13 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, /* each item in the accumulator (which will become up to N */ /* units, where 2<=N<=9). */ for (lp=zacc, up=acc; lp(*lp); /* decapitate to uInt */ for (p=0; p(item - (part * (DECDPUNMAX + 1))); item=part; } /* p */ - *up=(Unit)item; up++; /* [final needs no division] */ + *up = static_cast(item); up++; /* [final needs no division] */ } /* lp */ accunits = static_cast(up-acc); /* count of units */ } @@ -5110,10 +5110,10 @@ static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, /* if accumulator will be too long for local storage, then allocate */ acc=accbuff; /* -> assume buffer for accumulator */ needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit); - if (needbytes>(Int)sizeof(accbuff)) { - allocacc=(Unit *)malloc(needbytes); + if (needbytes > static_cast(sizeof(accbuff))) { + allocacc = static_cast(malloc(needbytes)); if (allocacc==nullptr) {*status|=DEC_Insufficient_storage; break;} - acc=(Unit *)allocacc; /* use the allocated space */ + acc = static_cast(allocacc); /* use the allocated space */ } /* Now the main long multiplication loop */ @@ -5398,7 +5398,7 @@ decNumber * decExpOp(decNumber *res, const decNumber *rhs, decNumber *newrhs=bufr; /* assume will fit on stack */ needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); if (needbytes>sizeof(bufr)) { /* need malloc space */ - allocrhs=(decNumber *)malloc(needbytes); + allocrhs = static_cast(malloc(needbytes)); if (allocrhs==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -5430,7 +5430,7 @@ decNumber * decExpOp(decNumber *res, const decNumber *rhs, /* sufficiently exact. */ needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit); if (needbytes>sizeof(bufa)) { /* need malloc space */ - allocbufa=(decNumber *)malloc(needbytes); + allocbufa = static_cast(malloc(needbytes)); if (allocbufa==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -5442,7 +5442,7 @@ decNumber * decExpOp(decNumber *res, const decNumber *rhs, /* calculation below, which needs an extra two digits */ needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit); if (needbytes>sizeof(buft)) { /* need malloc space */ - allocbuft=(decNumber *)malloc(needbytes); + allocbuft = static_cast(malloc(needbytes)); if (allocbuft==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -5711,7 +5711,7 @@ decNumber * decLnOp(decNumber *res, const decNumber *rhs, /* estimate. */ needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit); if (needbytes>sizeof(bufa)) { /* need malloc space */ - allocbufa=(decNumber *)malloc(needbytes); + allocbufa = static_cast(malloc(needbytes)); if (allocbufa==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -5720,7 +5720,7 @@ decNumber * decLnOp(decNumber *res, const decNumber *rhs, pp=p+rhs->digits; needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit); if (needbytes>sizeof(bufb)) { /* need malloc space */ - allocbufb=(decNumber *)malloc(needbytes); + allocbufb = static_cast(malloc(needbytes)); if (allocbufb==nullptr) { /* hopeless -- abandon */ *status|=DEC_Insufficient_storage; break;} @@ -6299,8 +6299,8 @@ static Int decUnitCompare(const Unit *a, Int alength, /* Unaligned. If one is >1 unit longer than the other, padded */ /* approximately, then can return easily */ - if (alength>blength+(Int)D2U(exp)) return 1; - if (alength+1 blength + static_cast(D2U(exp))) return 1; + if (alength + 1 < blength + static_cast(D2U(exp))) return -1; /* Need to do a real subtract. For this, a result buffer is needed */ /* even though only the sign is of interest. Its length needs */ @@ -6310,7 +6310,7 @@ static Int decUnitCompare(const Unit *a, Int alength, need+=2; acc=accbuff; /* assume use local buffer */ if (need*sizeof(Unit)>sizeof(accbuff)) { - allocacc=(Unit *)malloc(need*sizeof(Unit)); + allocacc = static_cast(malloc(need * sizeof(Unit))); if (allocacc==nullptr) return BADINT; /* hopeless -- abandon */ acc=allocacc; } @@ -6319,7 +6319,7 @@ static Int decUnitCompare(const Unit *a, Int alength, exprem=exp%DECDPUN; /* subtract [A+B*(-m)] */ accunits=decUnitAddSub(a, alength, b, blength, expunits, acc, - -(Int)powers[exprem]); + -static_cast(powers[exprem])); /* [UnitAddSub result may have leading zeros, even on zero] */ if (accunits<0) result=-1; /* negative result */ else { /* non-negative result */ @@ -6424,11 +6424,11 @@ static Int decUnitAddSub(const Unit *a, Int alength, for (; c(*b)) * m; /* [special-casing m=1/-1 */ b++; /* here is not a win] */ /* here carry is new Unit of digits; it could be +ve or -ve */ - if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ - *c=(Unit)carry; + if (static_cast(carry) <= DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ + *c = static_cast(carry); carry=0; continue; } @@ -6472,14 +6472,14 @@ static Int decUnitAddSub(const Unit *a, Int alength, /* Can use QUOT10 as carry <= 4 digits */ if (carry>=0) { est=QUOT10(carry, DECDPUN); - *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ + *c = static_cast(carry - est * (DECDPUNMAX + 1)); /* remainder */ carry=est; /* quotient */ continue; } /* negative case */ - carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ + carry = carry + static_cast(DECDPUNMAX + 1) * (DECDPUNMAX + 1); /* make positive */ est=QUOT10(carry, DECDPUN); - *c=(Unit)(carry-est*(DECDPUNMAX+1)); + *c = static_cast(carry - est * (DECDPUNMAX + 1)); carry=est-(DECDPUNMAX+1); /* correctly negative */ #else /* remainder operator is undefined if negative, so must test */ @@ -6508,13 +6508,13 @@ static Int decUnitAddSub(const Unit *a, Int alength, a++; } else { /* inside B */ - carry+=((eInt)*b)*m; + carry += static_cast(*b) * m; b++; } /* here carry is new Unit of digits; it could be +ve or -ve and */ /* magnitude up to DECDPUNMAX squared */ - if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ - *c=(Unit)carry; + if (static_cast(carry) <= DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ + *c = static_cast(carry); carry=0; continue; } @@ -6558,14 +6558,14 @@ static Int decUnitAddSub(const Unit *a, Int alength, #elif DECDPUN<=2 if (carry>=0) { est=QUOT10(carry, DECDPUN); - *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ + *c = static_cast(carry - est * (DECDPUNMAX + 1)); /* remainder */ carry=est; /* quotient */ continue; } /* negative case */ - carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ + carry = carry + static_cast(DECDPUNMAX + 1) * (DECDPUNMAX + 1); /* make positive */ est=QUOT10(carry, DECDPUN); - *c=(Unit)(carry-est*(DECDPUNMAX+1)); + *c = static_cast(carry - est * (DECDPUNMAX + 1)); carry=est-(DECDPUNMAX+1); /* correctly negative */ #else if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */ @@ -6590,7 +6590,7 @@ static Int decUnitAddSub(const Unit *a, Int alength, /* return number of Units in the result, negated if a borrow */ if (carry==0) return static_cast(c-clsu); /* no carry, so no more to do */ if (carry>0) { /* positive carry */ - *c=(Unit)carry; /* place as new unit */ + *c = static_cast(carry); /* place as new unit */ c++; /* .. */ return static_cast(c-clsu); } @@ -6599,7 +6599,7 @@ static Int decUnitAddSub(const Unit *a, Int alength, for (c=clsu; c(add); add=0; } else { @@ -6612,7 +6612,7 @@ static Int decUnitAddSub(const Unit *a, Int alength, printf("UAS borrow: add %ld, carry %ld\n", add, carry); #endif if ((add-carry-1)!=0) { - *c=(Unit)(add-carry-1); + *c = static_cast(add - carry - 1); c++; /* interesting, include it */ } return static_cast(clsu-c); /* -ve result indicates borrowed */ @@ -6733,7 +6733,7 @@ static Int decShiftToMost(Unit *uar, Int digits, Int shift) { if (shift==0) return digits; /* [fastpath] nothing to do */ if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */ - *uar=(Unit)(*uar*powers[shift]); + *uar = static_cast(*uar * powers[shift]); return digits+shift; } @@ -6756,14 +6756,14 @@ static Int decShiftToMost(Unit *uar, Int digits, Int shift) { uInt rem=*source%powers[cut]; next+=*source/powers[cut]; #endif - if (target<=first) *target=(Unit)next; /* write to target iff valid */ + if (target <= first) *target = static_cast(next); /* write to target iff valid */ next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */ } } /* shift-move */ /* propagate any partial unit to one below and clear the rest */ for (; target>=uar; target--) { - *target=(Unit)next; + *target = static_cast(next); next=0; } return digits+shift; @@ -6810,7 +6810,7 @@ static Int decShiftToLeast(Unit *uar, Int units, Int shift) { quot=*up/powers[cut]; #endif for (; ; target++) { - *target=(Unit)quot; + *target = static_cast(quot); count-=(DECDPUN-cut); if (count<=0) break; up++; @@ -6822,7 +6822,7 @@ static Int decShiftToLeast(Unit *uar, Int units, Int shift) { rem=quot%powers[cut]; quot=quot/powers[cut]; #endif - *target=(Unit)(*target+rem*powers[DECDPUN-cut]); + *target = static_cast(*target + rem * powers[DECDPUN - cut]); count-=cut; if (count<=0) break; } @@ -6993,7 +6993,7 @@ static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu, /* here up -> Unit with first discarded digit */ cut=discard-(count-DECDPUN)-1; if (cut==DECDPUN-1) { /* unit-boundary case (fast) */ - Unit half=(Unit)powers[DECDPUN]>>1; + Unit half = static_cast(powers[DECDPUN]) >> 1; /* set residue directly */ if (*up>=half) { if (*up>half) *residue=7; @@ -7057,7 +7057,7 @@ static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu, dn->digits=count; /* set the new length */ /* shift-copy the coefficient array to the result number */ for (target=dn->lsu; ; target++) { - *target=(Unit)quot; + *target = static_cast(quot); count-=(DECDPUN-cut); if (count<=0) break; up++; @@ -7069,7 +7069,7 @@ static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu, rem=quot%powers[cut]; quot=quot/powers[cut]; #endif - *target=(Unit)(*target+rem*powers[DECDPUN-cut]); + *target = static_cast(*target + rem * powers[DECDPUN - cut]); count-=cut; if (count<=0) break; } /* shift-copy loop */ @@ -7205,7 +7205,7 @@ static void decApplyRound(decNumber *dn, decContext *set, Int residue, /* this is the last Unit (the msu) */ if (*up!=powers[count]-1) break; /* not still 9s */ /* here if it, too, is all nines */ - *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */ + *up = static_cast(powers[count - 1]); /* here 999 -> 100 etc. */ for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */ dn->exponent++; /* and bump exponent */ /* [which, very rarely, could cause Overflow...] */ @@ -7230,9 +7230,9 @@ static void decApplyRound(decNumber *dn, decContext *set, Int residue, if (*up!=powers[count-1]) break; /* not 100.. */ /* here if have the 1000... case */ sup=up; /* save msu pointer */ - *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */ + *up = static_cast(powers[count]) - 1; /* here 100 in msu -> 999 */ /* others all to all-nines, too */ - for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1; + for (up=up-1; up>=dn->lsu; up--) *up = static_cast(powers[DECDPUN]) - 1; dn->exponent--; /* and bump exponent */ /* iff the number was at the subnormal boundary (exponent=etiny) */ @@ -7243,7 +7243,7 @@ static void decApplyRound(decNumber *dn, decContext *set, Int residue, if (dn->exponent+1==set->emin-set->digits+1) { if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */ else { - *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */ + *sup = static_cast(powers[count - 1]) - 1; /* here 999.. in msu -> 99.. */ dn->digits--; } dn->exponent++; @@ -7442,7 +7442,7 @@ static void decSetMaxValue(decNumber *dn, decContext *set) { for (up=dn->lsu; ; up++) { if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */ else { /* this is the msu */ - *up=(Unit)(powers[count]-1); + *up = static_cast(powers[count] - 1); break; } count-=DECDPUN; /* filled those digits */ @@ -7642,7 +7642,7 @@ static Int decGetInt(const decNumber *dn) { got+=DECDPUN; } if (ilength==10) { /* need to check for wrap */ - if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11; + if (theInt / static_cast(powers[got - DECDPUN]) != static_cast(*(up - 1))) ilength = 11; /* [that test also disallows the BADINT result case] */ else if (neg && theInt>1999999997) ilength=11; else if (!neg && theInt>999999999) ilength=11; diff --git a/icu4c/source/i18n/decimfmt.cpp b/icu4c/source/i18n/decimfmt.cpp index 36c44afe2cc1..85ba4d83cb61 100644 --- a/icu4c/source/i18n/decimfmt.cpp +++ b/icu4c/source/i18n/decimfmt.cpp @@ -210,7 +210,7 @@ DecimalFormat::setAttribute(UNumberFormatAttribute attr, int32_t newValue, UErro break; case UNUM_ROUNDING_MODE: - setRoundingMode((DecimalFormat::ERoundingMode) newValue); + setRoundingMode(static_cast(newValue)); break; case UNUM_FORMAT_WIDTH: @@ -219,7 +219,7 @@ DecimalFormat::setAttribute(UNumberFormatAttribute attr, int32_t newValue, UErro case UNUM_PADDING_POSITION: /** The position at which padding will take place. */ - setPadPosition((DecimalFormat::EPadPosition) newValue); + setPadPosition(static_cast(newValue)); break; case UNUM_SECONDARY_GROUPING_SIZE: @@ -228,20 +228,20 @@ DecimalFormat::setAttribute(UNumberFormatAttribute attr, int32_t newValue, UErro #if UCONFIG_HAVE_PARSEALLINPUT case UNUM_PARSE_ALL_INPUT: - setParseAllInput((UNumberFormatAttributeValue) newValue); + setParseAllInput(static_cast(newValue)); break; #endif case UNUM_PARSE_NO_EXPONENT: - setParseNoExponent((UBool) newValue); + setParseNoExponent(static_cast(newValue)); break; case UNUM_PARSE_DECIMAL_MARK_REQUIRED: - setDecimalPatternMatchRequired((UBool) newValue); + setDecimalPatternMatchRequired(static_cast(newValue)); break; case UNUM_CURRENCY_USAGE: - setCurrencyUsage((UCurrencyUsage) newValue, &status); + setCurrencyUsage(static_cast(newValue), &status); break; case UNUM_MINIMUM_GROUPING_DIGITS: diff --git a/icu4c/source/i18n/double-conversion-string-to-double.cpp b/icu4c/source/i18n/double-conversion-string-to-double.cpp index 727fff24e17a..0a33b91b7c90 100644 --- a/icu4c/source/i18n/double-conversion-string-to-double.cpp +++ b/icu4c/source/i18n/double-conversion-string-to-double.cpp @@ -383,7 +383,7 @@ static double RadixStringToIeee(Iterator* current, } // Rounding up may cause overflow. - if ((number & ((int64_t)1 << kSignificandSize)) != 0) { + if ((number & (static_cast(1) << kSignificandSize)) != 0) { exponent++; number >>= 1; } diff --git a/icu4c/source/i18n/dtfmtsym.cpp b/icu4c/source/i18n/dtfmtsym.cpp index 5d770eada481..23cea3eba20a 100644 --- a/icu4c/source/i18n/dtfmtsym.cpp +++ b/icu4c/source/i18n/dtfmtsym.cpp @@ -370,7 +370,7 @@ DateFormatSymbols::createZoneStrings(const UnicodeString *const * otherStrings) int32_t row, col; UBool failed = false; - fZoneStrings = (UnicodeString **)uprv_malloc(fZoneStringsRowCount * sizeof(UnicodeString *)); + fZoneStrings = static_cast(uprv_malloc(fZoneStringsRowCount * sizeof(UnicodeString*))); if (fZoneStrings != nullptr) { for (row=0; rowinitZoneStringsArray(); + const_cast(this)->initZoneStringsArray(); } result = (const UnicodeString**)fLocaleZoneStrings; } else { @@ -1306,7 +1306,7 @@ DateFormatSymbols::initZoneStringsArray() { // Allocate array int32_t size = rows * sizeof(UnicodeString*); - zarray = (UnicodeString**)uprv_malloc(size); + zarray = static_cast(uprv_malloc(size)); if (zarray == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; break; @@ -1370,7 +1370,7 @@ DateFormatSymbols::setZoneStrings(const UnicodeString* const *strings, int32_t r // than adopting the list passed in) fZoneStringsRowCount = rowCount; fZoneStringsColCount = columnCount; - createZoneStrings((const UnicodeString**)strings); + createZoneStrings(const_cast(strings)); } //------------------------------------------------------ @@ -1391,39 +1391,39 @@ DateFormatSymbols::getPatternCharIndex(char16_t c) { } static const uint64_t kNumericFieldsAlways = - ((uint64_t)1 << UDAT_YEAR_FIELD) | // y - ((uint64_t)1 << UDAT_DATE_FIELD) | // d - ((uint64_t)1 << UDAT_HOUR_OF_DAY1_FIELD) | // k - ((uint64_t)1 << UDAT_HOUR_OF_DAY0_FIELD) | // H - ((uint64_t)1 << UDAT_MINUTE_FIELD) | // m - ((uint64_t)1 << UDAT_SECOND_FIELD) | // s - ((uint64_t)1 << UDAT_FRACTIONAL_SECOND_FIELD) | // S - ((uint64_t)1 << UDAT_DAY_OF_YEAR_FIELD) | // D - ((uint64_t)1 << UDAT_DAY_OF_WEEK_IN_MONTH_FIELD) | // F - ((uint64_t)1 << UDAT_WEEK_OF_YEAR_FIELD) | // w - ((uint64_t)1 << UDAT_WEEK_OF_MONTH_FIELD) | // W - ((uint64_t)1 << UDAT_HOUR1_FIELD) | // h - ((uint64_t)1 << UDAT_HOUR0_FIELD) | // K - ((uint64_t)1 << UDAT_YEAR_WOY_FIELD) | // Y - ((uint64_t)1 << UDAT_EXTENDED_YEAR_FIELD) | // u - ((uint64_t)1 << UDAT_JULIAN_DAY_FIELD) | // g - ((uint64_t)1 << UDAT_MILLISECONDS_IN_DAY_FIELD) | // A - ((uint64_t)1 << UDAT_RELATED_YEAR_FIELD); // r + (static_cast(1) << UDAT_YEAR_FIELD) | // y + (static_cast(1) << UDAT_DATE_FIELD) | // d + (static_cast(1) << UDAT_HOUR_OF_DAY1_FIELD) | // k + (static_cast(1) << UDAT_HOUR_OF_DAY0_FIELD) | // H + (static_cast(1) << UDAT_MINUTE_FIELD) | // m + (static_cast(1) << UDAT_SECOND_FIELD) | // s + (static_cast(1) << UDAT_FRACTIONAL_SECOND_FIELD) | // S + (static_cast(1) << UDAT_DAY_OF_YEAR_FIELD) | // D + (static_cast(1) << UDAT_DAY_OF_WEEK_IN_MONTH_FIELD) | // F + (static_cast(1) << UDAT_WEEK_OF_YEAR_FIELD) | // w + (static_cast(1) << UDAT_WEEK_OF_MONTH_FIELD) | // W + (static_cast(1) << UDAT_HOUR1_FIELD) | // h + (static_cast(1) << UDAT_HOUR0_FIELD) | // K + (static_cast(1) << UDAT_YEAR_WOY_FIELD) | // Y + (static_cast(1) << UDAT_EXTENDED_YEAR_FIELD) | // u + (static_cast(1) << UDAT_JULIAN_DAY_FIELD) | // g + (static_cast(1) << UDAT_MILLISECONDS_IN_DAY_FIELD) | // A + (static_cast(1) << UDAT_RELATED_YEAR_FIELD); // r static const uint64_t kNumericFieldsForCount12 = - ((uint64_t)1 << UDAT_MONTH_FIELD) | // M or MM - ((uint64_t)1 << UDAT_DOW_LOCAL_FIELD) | // e or ee - ((uint64_t)1 << UDAT_STANDALONE_DAY_FIELD) | // c or cc - ((uint64_t)1 << UDAT_STANDALONE_MONTH_FIELD) | // L or LL - ((uint64_t)1 << UDAT_QUARTER_FIELD) | // Q or QQ - ((uint64_t)1 << UDAT_STANDALONE_QUARTER_FIELD); // q or qq + (static_cast(1) << UDAT_MONTH_FIELD) | // M or MM + (static_cast(1) << UDAT_DOW_LOCAL_FIELD) | // e or ee + (static_cast(1) << UDAT_STANDALONE_DAY_FIELD) | // c or cc + (static_cast(1) << UDAT_STANDALONE_MONTH_FIELD) | // L or LL + (static_cast(1) << UDAT_QUARTER_FIELD) | // Q or QQ + (static_cast(1) << UDAT_STANDALONE_QUARTER_FIELD); // q or qq UBool U_EXPORT2 DateFormatSymbols::isNumericField(UDateFormatField f, int32_t count) { if (f == UDAT_FIELD_COUNT) { return false; } - uint64_t flag = ((uint64_t)1 << f); + uint64_t flag = static_cast(1) << f; return ((kNumericFieldsAlways & flag) != 0 || ((kNumericFieldsForCount12 & flag) != 0 && count < 3)); } @@ -1626,11 +1626,11 @@ struct CalendarDataSink : public ResourceSink { modified = false; for (int32_t i = 0; i < aliasPathPairs.size();) { UBool mod = false; - UnicodeString *alias = (UnicodeString*)aliasPathPairs[i]; + UnicodeString* alias = static_cast(aliasPathPairs[i]); UnicodeString *aliasArray; Hashtable *aliasMap; - if ((aliasArray = (UnicodeString*)arrays.get(*alias)) != nullptr) { - UnicodeString *path = (UnicodeString*)aliasPathPairs[i + 1]; + if ((aliasArray = static_cast(arrays.get(*alias))) != nullptr) { + UnicodeString* path = static_cast(aliasPathPairs[i + 1]); if (arrays.get(*path) == nullptr) { // Clone the array int32_t aliasArraySize = arraySizes.geti(*alias); @@ -1643,8 +1643,8 @@ struct CalendarDataSink : public ResourceSink { } if (U_FAILURE(errorCode)) { return; } mod = true; - } else if ((aliasMap = (Hashtable*)maps.get(*alias)) != nullptr) { - UnicodeString *path = (UnicodeString*)aliasPathPairs[i + 1]; + } else if ((aliasMap = static_cast(maps.get(*alias))) != nullptr) { + UnicodeString* path = static_cast(aliasPathPairs[i + 1]); if (maps.get(*path) == nullptr) { maps.put(*path, aliasMap, errorCode); } @@ -1848,12 +1848,12 @@ static void initField(UnicodeString **field, int32_t& length, const char16_t *data, LastResortSize numStr, LastResortSize strLen, UErrorCode &status) { if (U_SUCCESS(status)) { length = numStr; - *field = newUnicodeStringArray((size_t)numStr); + *field = newUnicodeStringArray(static_cast(numStr)); if (*field) { for(int32_t i = 0; isetTo(true, data+(i*((int32_t)strLen)), -1); + (*(field) + i)->setTo(true, data + (i * (static_cast(strLen))), -1); } } else { @@ -1969,7 +1969,7 @@ static const ContextUsageTypeNameToEnumValue contextUsageTypeMap[] = { { "month-standalone-except-narrow", DateFormatSymbols::kCapContextUsageMonthStandalone }, { "zone-long", DateFormatSymbols::kCapContextUsageZoneLong }, { "zone-short", DateFormatSymbols::kCapContextUsageZoneShort }, - { nullptr, (DateFormatSymbols::ECapitalizationContextUsageType)0 }, + { nullptr, static_cast(0) }, }; // Resource keys to look up localized strings for day periods. @@ -2496,31 +2496,31 @@ DateFormatSymbols::initializeData(const Locale& locale, const char *type, UError status = U_USING_FALLBACK_WARNING; //TODO(fabalbon): make sure we are storing las resort data for all fields in here. - initField(&fEras, fErasCount, (const char16_t *)gLastResortEras, kEraNum, kEraLen, status); - initField(&fEraNames, fEraNamesCount, (const char16_t *)gLastResortEras, kEraNum, kEraLen, status); - initField(&fNarrowEras, fNarrowErasCount, (const char16_t *)gLastResortEras, kEraNum, kEraLen, status); - initField(&fMonths, fMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fShortMonths, fShortMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fNarrowMonths, fNarrowMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fStandaloneMonths, fStandaloneMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fStandaloneShortMonths, fStandaloneShortMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fStandaloneNarrowMonths, fStandaloneNarrowMonthsCount, (const char16_t *)gLastResortMonthNames, kMonthNum, kMonthLen, status); - initField(&fWeekdays, fWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fShortWeekdays, fShortWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fShorterWeekdays, fShorterWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fNarrowWeekdays, fNarrowWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fStandaloneWeekdays, fStandaloneWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fStandaloneShortWeekdays, fStandaloneShortWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fStandaloneShorterWeekdays, fStandaloneShorterWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fStandaloneNarrowWeekdays, fStandaloneNarrowWeekdaysCount, (const char16_t *)gLastResortDayNames, kDayNum, kDayLen, status); - initField(&fAmPms, fAmPmsCount, (const char16_t *)gLastResortAmPmMarkers, kAmPmNum, kAmPmLen, status); - initField(&fNarrowAmPms, fNarrowAmPmsCount, (const char16_t *)gLastResortAmPmMarkers, kAmPmNum, kAmPmLen, status); - initField(&fQuarters, fQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); - initField(&fShortQuarters, fShortQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); - initField(&fNarrowQuarters, fNarrowQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); - initField(&fStandaloneQuarters, fStandaloneQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); - initField(&fStandaloneShortQuarters, fStandaloneShortQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); - initField(&fStandaloneNarrowQuarters, fStandaloneNarrowQuartersCount, (const char16_t *)gLastResortQuarters, kQuarterNum, kQuarterLen, status); + initField(&fEras, fErasCount, reinterpret_cast(gLastResortEras), kEraNum, kEraLen, status); + initField(&fEraNames, fEraNamesCount, reinterpret_cast(gLastResortEras), kEraNum, kEraLen, status); + initField(&fNarrowEras, fNarrowErasCount, reinterpret_cast(gLastResortEras), kEraNum, kEraLen, status); + initField(&fMonths, fMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fShortMonths, fShortMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fNarrowMonths, fNarrowMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fStandaloneMonths, fStandaloneMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fStandaloneShortMonths, fStandaloneShortMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fStandaloneNarrowMonths, fStandaloneNarrowMonthsCount, reinterpret_cast(gLastResortMonthNames), kMonthNum, kMonthLen, status); + initField(&fWeekdays, fWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fShortWeekdays, fShortWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fShorterWeekdays, fShorterWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fNarrowWeekdays, fNarrowWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fStandaloneWeekdays, fStandaloneWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fStandaloneShortWeekdays, fStandaloneShortWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fStandaloneShorterWeekdays, fStandaloneShorterWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fStandaloneNarrowWeekdays, fStandaloneNarrowWeekdaysCount, reinterpret_cast(gLastResortDayNames), kDayNum, kDayLen, status); + initField(&fAmPms, fAmPmsCount, reinterpret_cast(gLastResortAmPmMarkers), kAmPmNum, kAmPmLen, status); + initField(&fNarrowAmPms, fNarrowAmPmsCount, reinterpret_cast(gLastResortAmPmMarkers), kAmPmNum, kAmPmLen, status); + initField(&fQuarters, fQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); + initField(&fShortQuarters, fShortQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); + initField(&fNarrowQuarters, fNarrowQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); + initField(&fStandaloneQuarters, fStandaloneQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); + initField(&fStandaloneShortQuarters, fStandaloneShortQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); + initField(&fStandaloneNarrowQuarters, fStandaloneNarrowQuartersCount, reinterpret_cast(gLastResortQuarters), kQuarterNum, kQuarterLen, status); fLocalPatternChars.setTo(true, gPatternChars, PATTERN_CHARS_LEN); } } diff --git a/icu4c/source/i18n/dtitvfmt.cpp b/icu4c/source/i18n/dtitvfmt.cpp index a8aefe064faa..985aabda0402 100644 --- a/icu4c/source/i18n/dtitvfmt.cpp +++ b/icu4c/source/i18n/dtitvfmt.cpp @@ -641,7 +641,7 @@ DateIntervalFormat::setContext(UDisplayContext value, UErrorCode& status) { if (U_FAILURE(status)) return; - if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) { + if (static_cast(static_cast(value) >> 8) == UDISPCTX_TYPE_CAPITALIZATION) { fCapitalizationContext = value; } else { status = U_ILLEGAL_ARGUMENT_ERROR; @@ -652,10 +652,10 @@ UDisplayContext DateIntervalFormat::getContext(UDisplayContextType type, UErrorCode& status) const { if (U_FAILURE(status)) - return (UDisplayContext)0; + return static_cast(0); if (type != UDISPCTX_TYPE_CAPITALIZATION) { status = U_ILLEGAL_ARGUMENT_ERROR; - return (UDisplayContext)0; + return static_cast(0); } return fCapitalizationContext; } @@ -829,7 +829,7 @@ DateIntervalFormat::initializePattern(UErrorCode& status) { int32_t dateTimeFormatLength; const char16_t* dateTimeFormat = ures_getStringByIndex( dateTimePatternsRes.getAlias(), - (int32_t)DateFormat::kDateTime, + static_cast(DateFormat::kDateTime), &dateTimeFormatLength, &status); if ( U_SUCCESS(status) && dateTimeFormatLength >= 3 ) { fDateTimeFormat = new UnicodeString(dateTimeFormat, dateTimeFormatLength); @@ -1538,7 +1538,7 @@ DateIntervalFormat::splitPatternInto2Part(const UnicodeString& intervalPattern) if (ch != prevCh && count > 0) { // check the repeativeness of pattern letter - UBool repeated = patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)]; + UBool repeated = patternRepeated[prevCh - PATTERN_CHAR_BASE]; if ( repeated == false ) { patternRepeated[prevCh - PATTERN_CHAR_BASE] = true; } else { @@ -1569,7 +1569,7 @@ DateIntervalFormat::splitPatternInto2Part(const UnicodeString& intervalPattern) // "d-d"(last char repeated ), and // "d-d MM" ( repetition found ) if ( count > 0 && foundRepetition == false ) { - if ( patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)] == false ) { + if (patternRepeated[prevCh - PATTERN_CHAR_BASE] == false) { count = 0; } } @@ -1774,8 +1774,8 @@ DateIntervalFormat::adjustFieldWidth(const UnicodeString& inputSkeleton, // for skeleton "M+", the pattern might be "...L..." skeletonChar = CAP_M; } - int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)]; - int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)]; + int32_t fieldCount = bestMatchSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; + int32_t inputFieldCount = inputSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; if ( fieldCount == count && inputFieldCount > fieldCount ) { count = inputFieldCount - fieldCount; int32_t j; @@ -1813,8 +1813,8 @@ DateIntervalFormat::adjustFieldWidth(const UnicodeString& inputSkeleton, // for skeleton "M+", the pattern might be "...L..." skeletonChar = CAP_M; } - int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)]; - int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)]; + int32_t fieldCount = bestMatchSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; + int32_t inputFieldCount = inputSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; if ( fieldCount == count && inputFieldCount > fieldCount ) { count = inputFieldCount - fieldCount; int32_t j; diff --git a/icu4c/source/i18n/dtitvinf.cpp b/icu4c/source/i18n/dtitvinf.cpp index 8ebb2f70d88d..6a1e48fbe32a 100644 --- a/icu4c/source/i18n/dtitvinf.cpp +++ b/icu4c/source/i18n/dtitvinf.cpp @@ -188,7 +188,7 @@ DateIntervalInfo::getIntervalPattern(const UnicodeString& skeleton, return result; } - const UnicodeString* patternsOfOneSkeleton = (UnicodeString*) fIntervalPatterns->get(skeleton); + const UnicodeString* patternsOfOneSkeleton = static_cast(fIntervalPatterns->get(skeleton)); if ( patternsOfOneSkeleton != nullptr ) { IntervalPatternIndex index = calendarFieldToIntervalIndex(field, status); if ( U_FAILURE(status) ) { @@ -364,7 +364,7 @@ struct DateIntervalInfo::DateIntervalSink : public ResourceSink { UnicodeString skeleton(currentSkeleton, -1, US_INV); UnicodeString* patternsOfOneSkeleton = - (UnicodeString*)(dateIntervalInfo.fIntervalPatterns->get(skeleton)); + static_cast(dateIntervalInfo.fIntervalPatterns->get(skeleton)); if (patternsOfOneSkeleton == nullptr || patternsOfOneSkeleton[index].isEmpty()) { UnicodeString pattern = value.getUnicodeString(errorCode); @@ -491,7 +491,7 @@ DateIntervalInfo::setIntervalPatternInternally(const UnicodeString& skeleton, if ( U_FAILURE(status) ) { return; } - UnicodeString* patternsOfOneSkeleton = (UnicodeString*)(fIntervalPatterns->get(skeleton)); + UnicodeString* patternsOfOneSkeleton = static_cast(fIntervalPatterns->get(skeleton)); UBool emptyHash = false; if ( patternsOfOneSkeleton == nullptr ) { patternsOfOneSkeleton = new UnicodeString[kIPI_MAX_INDEX]; @@ -517,7 +517,7 @@ DateIntervalInfo::parseSkeleton(const UnicodeString& skeleton, int32_t i; for ( i = 0; i < skeleton.length(); ++i ) { // it is an ASCII char in skeleton - int8_t ch = (int8_t)skeleton.charAt(i); + int8_t ch = static_cast(skeleton.charAt(i)); ++skeletonFieldWidth[ch - PATTERN_CHAR_BASE]; } } @@ -612,7 +612,7 @@ DateIntervalInfo::getBestSkeleton(const UnicodeString& skeleton, const UHashElement* elem = nullptr; while ( (elem = fIntervalPatterns->nextElement(pos)) != nullptr ) { const UHashTok keyTok = elem->key; - UnicodeString* newSkeleton = (UnicodeString*)keyTok.pointer; + UnicodeString* newSkeleton = static_cast(keyTok.pointer); #ifdef DTITVINF_DEBUG skeleton->extract(0, skeleton->length(), result, "UTF-8"); snprintf(mesg, sizeof(mesg), "available skeletons: skeleton: %s; \n", result); @@ -641,7 +641,7 @@ DateIntervalInfo::getBestSkeleton(const UnicodeString& skeleton, fieldDifference = -1; distance += DIFFERENT_FIELD; } else if (stringNumeric(inputFieldWidth, fieldWidth, - (char)(i+BASE) ) ) { + static_cast(i + BASE))) { distance += STRING_NUMERIC_DIFFERENCE; } else { distance += (inputFieldWidth > fieldWidth) ? @@ -723,7 +723,7 @@ DateIntervalInfo::deleteHash(Hashtable* hTable) const UHashElement* element = nullptr; while ( (element = hTable->nextElement(pos)) != nullptr ) { const UHashTok valueTok = element->value; - const UnicodeString* value = (UnicodeString*)valueTok.pointer; + const UnicodeString* value = static_cast(valueTok.pointer); delete[] value; } delete fIntervalPatterns; @@ -787,9 +787,9 @@ DateIntervalInfo::copyHash(const Hashtable* source, if ( source ) { while ( (element = source->nextElement(pos)) != nullptr ) { const UHashTok keyTok = element->key; - const UnicodeString* key = (UnicodeString*)keyTok.pointer; + const UnicodeString* key = static_cast(keyTok.pointer); const UHashTok valueTok = element->value; - const UnicodeString* value = (UnicodeString*)valueTok.pointer; + const UnicodeString* value = static_cast(valueTok.pointer); UnicodeString* copy = new UnicodeString[kIPI_MAX_INDEX]; if (copy == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/dtptngen.cpp b/icu4c/source/i18n/dtptngen.cpp index 4fe00a23e19e..3207291f34af 100644 --- a/icu4c/source/i18n/dtptngen.cpp +++ b/icu4c/source/i18n/dtptngen.cpp @@ -647,9 +647,9 @@ static int32_t* getAllowedHourFormatsLangCountry(const char* language, const cha langCountry.append(country, status); int32_t* allowedFormats; - allowedFormats = (int32_t *)uhash_get(localeToAllowedHourFormatsMap, langCountry.data()); + allowedFormats = static_cast(uhash_get(localeToAllowedHourFormatsMap, langCountry.data())); if (allowedFormats == nullptr) { - allowedFormats = (int32_t *)uhash_get(localeToAllowedHourFormatsMap, const_cast(country)); + allowedFormats = static_cast(uhash_get(localeToAllowedHourFormatsMap, const_cast(country))); } return allowedFormats; @@ -810,7 +810,7 @@ DateTimePatternGenerator::addICUPatterns(const Locale& locale, UErrorCode& statu // Load with ICU patterns for (int32_t i=DateFormat::kFull; i<=DateFormat::kShort; i++) { - DateFormat::EStyle style = (DateFormat::EStyle)i; + DateFormat::EStyle style = static_cast(i); df = DateFormat::createDateInstance(style, locale); SimpleDateFormat* sdf; if (df != nullptr && (sdf = dynamic_cast(df)) != nullptr) { @@ -947,7 +947,7 @@ struct DateTimePatternGenerator::AppendItemFormatsSink : public ResourceSink { void fillInMissing() { UnicodeString defaultItemFormat(true, UDATPG_ItemFormat, UPRV_LENGTHOF(UDATPG_ItemFormat)-1); // Read-only alias. for (int32_t i = 0; i < UDATPG_FIELD_COUNT; i++) { - UDateTimePatternField field = (UDateTimePatternField)i; + UDateTimePatternField field = static_cast(i); if (dtpg.getAppendItemFormat(field).isEmpty()) { dtpg.setAppendItemFormat(field, defaultItemFormat); } @@ -979,25 +979,25 @@ struct DateTimePatternGenerator::AppendItemNamesSink : public ResourceSink { void fillInMissing() { for (int32_t i = 0; i < UDATPG_FIELD_COUNT; i++) { - UnicodeString& valueStr = dtpg.getMutableFieldDisplayName((UDateTimePatternField)i, UDATPG_WIDE); + UnicodeString& valueStr = dtpg.getMutableFieldDisplayName(static_cast(i), UDATPG_WIDE); if (valueStr.isEmpty()) { valueStr = CAP_F; U_ASSERT(i < 20); if (i < 10) { // F0, F1, ..., F9 - valueStr += (char16_t)(i+0x30); + valueStr += static_cast(i + 0x30); } else { // F10, F11, ... - valueStr += (char16_t)0x31; - valueStr += (char16_t)(i-10 + 0x30); + valueStr += static_cast(0x31); + valueStr += static_cast(i - 10 + 0x30); } // NUL-terminate for the C API. valueStr.getTerminatedBuffer(); } for (int32_t j = 1; j < UDATPG_WIDTH_COUNT; j++) { - UnicodeString& valueStr2 = dtpg.getMutableFieldDisplayName((UDateTimePatternField)i, (UDateTimePGDisplayWidth)j); + UnicodeString& valueStr2 = dtpg.getMutableFieldDisplayName(static_cast(i), static_cast(j)); if (valueStr2.isEmpty()) { - valueStr2 = dtpg.getFieldDisplayName((UDateTimePatternField)i, (UDateTimePGDisplayWidth)(j-1)); + valueStr2 = dtpg.getFieldDisplayName(static_cast(i), static_cast(j - 1)); } } } @@ -1259,7 +1259,7 @@ DateTimePatternGenerator::mapSkeletonMetacharacters(const UnicodeString& pattern } else { AllowedHourFormat bestAllowed; if (fAllowedHourFormats[0] != ALLOWED_HOUR_FORMAT_UNKNOWN) { - bestAllowed = (AllowedHourFormat)fAllowedHourFormats[0]; + bestAllowed = static_cast(fAllowedHourFormats[0]); } else { status = U_INVALID_FORMAT_ERROR; return {}; @@ -1353,7 +1353,7 @@ void DateTimePatternGenerator::setDateTimeFormat(const UnicodeString& dtFormat) { UErrorCode status = U_ZERO_ERROR; for (int32_t style = UDAT_FULL; style <= UDAT_SHORT; style++) { - setDateTimeFormat((UDateFormatStyle)style, dtFormat, status); + setDateTimeFormat(static_cast(style), dtFormat, status); } } @@ -1441,7 +1441,7 @@ DateTimePatternGenerator::setDateTimeFromCalendar(const Locale& locale, UErrorCo // Try again with standard variant status = U_ZERO_ERROR; dateTimePatterns.orphan(); - dateTimeOffset = (int32_t)DateFormat::kDateTimeOffset; + dateTimeOffset = static_cast(DateFormat::kDateTimeOffset); if (!cTypeIsGregorian) { specificCalBundle.adoptInstead(ures_getByKeyWithFallback(calData.getAlias(), cType, nullptr, &status)); @@ -1462,7 +1462,7 @@ DateTimePatternGenerator::setDateTimeFromCalendar(const Locale& locale, UErrorCo if (U_FAILURE(status)) { return; } for (int32_t style = UDAT_FULL; style <= UDAT_SHORT; style++) { resStr = ures_getStringByIndex(dateTimePatterns.getAlias(), dateTimeOffset + style, &resStrLen, &status); - setDateTimeFormat((UDateFormatStyle)style, UnicodeString(true, resStr, resStrLen), status); + setDateTimeFormat(static_cast(style), UnicodeString(true, resStr, resStrLen), status); } } @@ -1568,7 +1568,7 @@ UDateTimePatternField DateTimePatternGenerator::getAppendFormatNumber(const char* field) const { for (int32_t i=0; i(i); } } return UDATPG_FIELD_COUNT; @@ -1584,7 +1584,7 @@ DateTimePatternGenerator::getFieldAndWidthIndices(const char* key, UDateTimePGDi if (hyphenPtr) { for (int32_t i=UDATPG_WIDTH_COUNT-1; i>0; --i) { if (uprv_strcmp(CLDR_FIELD_WIDTH[i], hyphenPtr)==0) { - *widthP=(UDateTimePGDisplayWidth)i; + *widthP = static_cast(i); break; } } @@ -1592,7 +1592,7 @@ DateTimePatternGenerator::getFieldAndWidthIndices(const char* key, UDateTimePGDi } for (int32_t i=0; i(i); } } return UDATPG_FIELD_COUNT; @@ -1809,7 +1809,7 @@ DateTimePatternGenerator::getBestAppending(int32_t missingFields, int32_t flags, if (appendItemFormats[topField].length() != 0) { UnicodeString appendName; - getAppendName((UDateTimePatternField)topField, appendName); + getAppendName(static_cast(topField), appendName); const UnicodeString *values[3] = { &resultPattern, &tempPattern, @@ -1849,7 +1849,7 @@ DateTimePatternGenerator::setAvailableFormat(const UnicodeString &key, UErrorCod UBool DateTimePatternGenerator::isAvailableFormatSet(const UnicodeString &key) const { - return (UBool)(fAvailableFormatKeyHash->geti(key) == 1); + return static_cast(fAvailableFormatKeyHash->geti(key) == 1); } void @@ -1870,7 +1870,7 @@ DateTimePatternGenerator::copyHashtable(Hashtable *other, UErrorCode &status) { // walk through the hash table and create a deep clone while((elem = other->nextElement(pos))!= nullptr){ const UHashTok otherKeyTok = elem->key; - UnicodeString* otherKey = (UnicodeString*)otherKeyTok.pointer; + UnicodeString* otherKey = static_cast(otherKeyTok.pointer); fAvailableFormatKeyHash->puti(*otherKey, 1, status); if(U_FAILURE(status)){ return; @@ -2551,7 +2551,7 @@ FormatParser::getCanonicalIndex(const UnicodeString& s, UBool strict) { UBool FormatParser::isQuoteLiteral(const UnicodeString& s) { - return (UBool)(s.charAt(0) == SINGLE_QUOTE); + return static_cast(s.charAt(0) == SINGLE_QUOTE); } // This function assumes the current itemIndex points to the quote literal. @@ -2734,8 +2734,8 @@ void SkeletonFields::populate(int32_t field, const UnicodeString& value) { } void SkeletonFields::populate(int32_t field, char16_t ch, int32_t length) { - chars[field] = (int8_t) ch; - lengths[field] = (int8_t) length; + chars[field] = static_cast(ch); + lengths[field] = static_cast(length); } UBool SkeletonFields::isFieldEmpty(int32_t field) const { @@ -2751,7 +2751,7 @@ UnicodeString& SkeletonFields::appendTo(UnicodeString& string) const { UnicodeString& SkeletonFields::appendFieldTo(int32_t field, UnicodeString& string) const { char16_t ch(chars[field]); - int32_t length = (int32_t) lengths[field]; + int32_t length = static_cast(lengths[field]); for (int32_t i=0; isize()) { - return (const UnicodeString*)fSkeletons->elementAt(pos++); + return static_cast(fSkeletons->elementAt(pos++)); } return nullptr; } @@ -2922,7 +2922,7 @@ DTSkeletonEnumeration::~DTSkeletonEnumeration() { UnicodeString *s; if (fSkeletons.isValid()) { for (int32_t i = 0; i < fSkeletons->size(); ++i) { - if ((s = (UnicodeString *)fSkeletons->elementAt(i)) != nullptr) { + if ((s = static_cast(fSkeletons->elementAt(i))) != nullptr) { delete s; } } @@ -2957,7 +2957,7 @@ DTRedundantEnumeration::add(const UnicodeString& pattern, UErrorCode& status) { const UnicodeString* DTRedundantEnumeration::snext(UErrorCode& status) { if (U_SUCCESS(status) && fPatterns.isValid() && pos < fPatterns->size()) { - return (const UnicodeString*)fPatterns->elementAt(pos++); + return static_cast(fPatterns->elementAt(pos++)); } return nullptr; } @@ -2989,7 +2989,7 @@ DTRedundantEnumeration::~DTRedundantEnumeration() { UnicodeString *s; if (fPatterns.isValid()) { for (int32_t i = 0; i < fPatterns->size(); ++i) { - if ((s = (UnicodeString *)fPatterns->elementAt(i)) != nullptr) { + if ((s = static_cast(fPatterns->elementAt(i))) != nullptr) { delete s; } } diff --git a/icu4c/source/i18n/erarules.cpp b/icu4c/source/i18n/erarules.cpp index ff270ea696be..8ab6f00ae04b 100644 --- a/icu4c/source/i18n/erarules.cpp +++ b/icu4c/source/i18n/erarules.cpp @@ -54,7 +54,7 @@ static UBool isValidRuleStartDate(int32_t year, int32_t month, int32_t day) { * @return an encoded date. */ static int32_t encodeDate(int32_t year, int32_t month, int32_t day) { - return (int32_t)((uint32_t)year << 16) | month << 8 | day; + return static_cast(static_cast(year) << 16) | month << 8 | day; } static void decodeDate(int32_t encodedDate, int32_t (&fields)[3]) { @@ -141,8 +141,8 @@ EraRules* EraRules::createInstance(const char *calType, UBool includeTentativeEr } const char *eraIdxStr = ures_getKey(eraRuleRes.getAlias()); char *endp; - int32_t eraIdx = (int32_t)strtol(eraIdxStr, &endp, 10); - if ((size_t)(endp - eraIdxStr) != uprv_strlen(eraIdxStr)) { + int32_t eraIdx = static_cast(strtol(eraIdxStr, &endp, 10)); + if (static_cast(endp - eraIdxStr) != uprv_strlen(eraIdxStr)) { status = U_INVALID_FORMAT_ERROR; return nullptr; } diff --git a/icu4c/source/i18n/fmtable.cpp b/icu4c/source/i18n/fmtable.cpp index 01d7bad1ba6f..b7f0dddabb76 100644 --- a/icu4c/source/i18n/fmtable.cpp +++ b/icu4c/source/i18n/fmtable.cpp @@ -399,7 +399,7 @@ Formattable::getLong(UErrorCode& status) const switch (fType) { case Formattable::kLong: - return (int32_t)fValue.fInt64; + return static_cast(fValue.fInt64); case Formattable::kInt64: if (fValue.fInt64 > INT32_MAX) { status = U_INVALID_FORMAT_ERROR; @@ -408,7 +408,7 @@ Formattable::getLong(UErrorCode& status) const status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { - return (int32_t)fValue.fInt64; + return static_cast(fValue.fInt64); } case Formattable::kDouble: if (fValue.fDouble > INT32_MAX) { @@ -418,7 +418,7 @@ Formattable::getLong(UErrorCode& status) const status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { - return (int32_t)fValue.fDouble; // loses fraction + return static_cast(fValue.fDouble); // loses fraction } case Formattable::kObject: if (fValue.fObject == nullptr) { @@ -456,10 +456,10 @@ Formattable::getInt64(UErrorCode& status) const case Formattable::kInt64: return fValue.fInt64; case Formattable::kDouble: - if (fValue.fDouble > (double)U_INT64_MAX) { + if (fValue.fDouble > static_cast(U_INT64_MAX)) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MAX; - } else if (fValue.fDouble < (double)U_INT64_MIN) { + } else if (fValue.fDouble < static_cast(U_INT64_MIN)) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MIN; } else if (fabs(fValue.fDouble) > U_DOUBLE_MAX_EXACT_INT && fDecimalQuantity != nullptr) { @@ -471,7 +471,7 @@ Formattable::getInt64(UErrorCode& status) const return fDecimalQuantity->isNegative() ? U_INT64_MIN : U_INT64_MAX; } } else { - return (int64_t)fValue.fDouble; + return static_cast(fValue.fDouble); } case Formattable::kObject: if (fValue.fObject == nullptr) { @@ -500,7 +500,7 @@ Formattable::getDouble(UErrorCode& status) const switch (fType) { case Formattable::kLong: case Formattable::kInt64: // loses precision - return (double)fValue.fInt64; + return static_cast(fValue.fInt64); case Formattable::kDouble: return fValue.fDouble; case Formattable::kObject: @@ -688,7 +688,7 @@ Formattable::getArray(int32_t& count, UErrorCode& status) const UnicodeString* Formattable::getBogus() const { - return (UnicodeString*)&fBogus; /* cast away const :-( */ + return const_cast(&fBogus); /* cast away const :-( */ } diff --git a/icu4c/source/i18n/formatted_string_builder.cpp b/icu4c/source/i18n/formatted_string_builder.cpp index 6481f73dcf65..94082dc379f2 100644 --- a/icu4c/source/i18n/formatted_string_builder.cpp +++ b/icu4c/source/i18n/formatted_string_builder.cpp @@ -156,7 +156,7 @@ FormattedStringBuilder::insertCodePoint(int32_t index, UChar32 codePoint, Field auto* charPtr = getCharPtr(); auto* fieldPtr = getFieldPtr(); if (count == 1) { - charPtr[position] = (char16_t) codePoint; + charPtr[position] = static_cast(codePoint); fieldPtr[position] = field; } else { charPtr[position] = U16_LEAD(codePoint); diff --git a/icu4c/source/i18n/gender.cpp b/icu4c/source/i18n/gender.cpp index ab76dab12173..6e9d8d2ac036 100644 --- a/icu4c/source/i18n/gender.cpp +++ b/icu4c/source/i18n/gender.cpp @@ -107,7 +107,7 @@ const GenderInfo* GenderInfo::getInstance(const Locale& locale, UErrorCode& stat const char* key = locale.getName(); { Mutex lock(&gGenderMetaLock); - result = (const GenderInfo*) uhash_get(gGenderInfoCache, key); + result = static_cast(uhash_get(gGenderInfoCache, key)); } if (result) { return result; @@ -123,7 +123,7 @@ const GenderInfo* GenderInfo::getInstance(const Locale& locale, UErrorCode& stat // favor the GenderInfo object that is already in the cache. { Mutex lock(&gGenderMetaLock); - GenderInfo* temp = (GenderInfo*) uhash_get(gGenderInfoCache, key); + GenderInfo* temp = static_cast(uhash_get(gGenderInfoCache, key)); if (temp) { result = temp; } else { diff --git a/icu4c/source/i18n/gregocal.cpp b/icu4c/source/i18n/gregocal.cpp index dfd64faa50e7..23366c7ab7a3 100644 --- a/icu4c/source/i18n/gregocal.cpp +++ b/icu4c/source/i18n/gregocal.cpp @@ -331,7 +331,7 @@ GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status) // normalized cutover is in pure date milliseconds; it contains no time // of day or timezone component, and it used to compare against other // pure date values. - double cutoverDay = ClockMath::floorDivide(date, (double)kOneDay); + double cutoverDay = ClockMath::floorDivide(date, kOneDay); // Handle the rare case of numeric overflow where the user specifies a time // outside of INT32_MIN .. INT32_MAX number of days. @@ -363,7 +363,7 @@ GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status) if (cal->get(UCAL_ERA, status) == BC) { fGregorianCutoverYear = 1 - fGregorianCutoverYear; } - fCutoverJulianDay = (int32_t)cutoverDay; + fCutoverJulianDay = static_cast(cutoverDay); delete cal; } @@ -388,10 +388,10 @@ void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& statu // The Julian epoch day (not the same as Julian Day) // is zero on Saturday December 30, 0 (Gregorian). int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2); - eyear = (int32_t) ClockMath::floorDivide((4.0*julianEpochDay) + 1464.0, (int32_t) 1461, &unusedRemainder); + eyear = static_cast(ClockMath::floorDivide((4.0 * julianEpochDay) + 1464.0, static_cast(1461), &unusedRemainder)); // Compute the Julian calendar day number for January 1, eyear - int32_t january1 = 365*(eyear-1) + ClockMath::floorDivide(eyear-1, (int32_t)4); + int32_t january1 = 365 * (eyear - 1) + ClockMath::floorDivide(eyear - 1, static_cast(4)); dayOfYear = (julianEpochDay - january1); // 0-based // Julian leap years occurred historically every 4 years starting @@ -542,7 +542,7 @@ int64_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, if (U_FAILURE(status)) { return 0; } - GregorianCalendar *nonConstThis = (GregorianCalendar*)this; // cast away const + GregorianCalendar* nonConstThis = const_cast(this); // cast away const // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. @@ -555,7 +555,7 @@ int64_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, } UBool isLeap = eyear%4 == 0; - int64_t y = (int64_t)eyear-1; + int64_t y = static_cast(eyear) - 1; int64_t julianDay = 365LL * y + ClockMath::floorDivideInt64(y, 4LL) + kJan1_1JulianDay - 3LL; @@ -638,8 +638,8 @@ GregorianCalendar::validateFields() const // Ignore DATE and DAY_OF_YEAR which are handled below if (field != UCAL_DATE && field != UCAL_DAY_OF_YEAR && - isSet((UCalendarDateFields)field) && - ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field)) + isSet(static_cast(field)) && + !boundsCheck(internalGet(static_cast(field)), static_cast(field))) return false; } @@ -778,7 +778,7 @@ double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian, double GregorianCalendar::millisToJulianDay(UDate millis) { - return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay); + return static_cast(kEpochStartAsJulianDay) + ClockMath::floorDivide(millis, kOneDay); } // ------------------------------------- @@ -786,7 +786,7 @@ GregorianCalendar::millisToJulianDay(UDate millis) UDate GregorianCalendar::julianDayToMillis(double julian) { - return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay); + return static_cast((julian - kEpochStartAsJulianDay) * kOneDay); } // ------------------------------------- @@ -796,7 +796,7 @@ GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b) { return (((stamp_a != kUnset && stamp_b != kUnset) ? uprv_max(stamp_a, stamp_b) - : (int32_t)kUnset)); + : static_cast(kUnset))); } // ------------------------------------- @@ -808,7 +808,7 @@ GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b) void GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { - roll((UCalendarDateFields) field, amount, status); + roll(static_cast(field), amount, status); } void @@ -1055,12 +1055,12 @@ GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& s */ int32_t GregorianCalendar::getActualMinimum(EDateFields field) const { - return getMinimum((UCalendarDateFields)field); + return getMinimum(static_cast(field)); } int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const { - return getMinimum((UCalendarDateFields)field); + return getMinimum(static_cast(field)); } /** @@ -1258,7 +1258,7 @@ int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, */ int32_t GregorianCalendar::internalGetEra() const { - return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD; + return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : static_cast(AD); } const char * diff --git a/icu4c/source/i18n/gregoimp.cpp b/icu4c/source/i18n/gregoimp.cpp index 9ae0c04c6570..d5c8437a9b80 100644 --- a/icu4c/source/i18n/gregoimp.cpp +++ b/icu4c/source/i18n/gregoimp.cpp @@ -51,7 +51,7 @@ double ClockMath::floorDivide(double numerator, int32_t denominator, // expression `(int32_t) (x + n)` evaluated with rounding to nearest // differs from ⌊x+n⌋ if 0 < ⌈x⌉−x ≪ x+n, as `x + n` is rounded up to // n+⌈x⌉ = ⌊x+n⌋ + 1. Rewriting it as ⌊x⌋+n makes the addition exact. - *remainder = (int32_t) (uprv_floor(numerator) - (quotient * denominator)); + *remainder = static_cast(uprv_floor(numerator) - (quotient * denominator)); } return quotient; } @@ -163,8 +163,8 @@ void Grego::timeToFields(UDate time, int32_t& year, int32_t& month, int32_t& dom, int32_t& dow, int32_t& doy, int32_t& mid, UErrorCode& status) { if (U_FAILURE(status)) return; double millisInDay; - double day = ClockMath::floorDivide((double)time, (double)U_MILLIS_PER_DAY, &millisInDay); - mid = (int32_t)millisInDay; + double day = ClockMath::floorDivide(static_cast(time), static_cast(U_MILLIS_PER_DAY), &millisInDay); + mid = static_cast(millisInDay); dayToFields(day, year, month, dom, dow, doy, status); } diff --git a/icu4c/source/i18n/gregoimp.h b/icu4c/source/i18n/gregoimp.h index bd6664ea752b..e069fb60de79 100644 --- a/icu4c/source/i18n/gregoimp.h +++ b/icu4c/source/i18n/gregoimp.h @@ -317,11 +317,11 @@ inline double Grego::julianDayToMillis(int32_t julian) } inline int32_t Grego::millisToJulianDay(double millis) { - return (int32_t) (kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay)); + return static_cast(kEpochStartAsJulianDay + ClockMath::floorDivide(millis, kOneDay)); } inline int32_t Grego::gregorianShift(int32_t eyear) { - int64_t y = (int64_t)eyear-1; + int64_t y = static_cast(eyear) - 1; int64_t gregShift = ClockMath::floorDivideInt64(y, 400LL) - ClockMath::floorDivideInt64(y, 100LL) + 2; return static_cast(gregShift); } diff --git a/icu4c/source/i18n/hebrwcal.cpp b/icu4c/source/i18n/hebrwcal.cpp index f5f9c13fede8..ef70a48f2353 100644 --- a/icu4c/source/i18n/hebrwcal.cpp +++ b/icu4c/source/i18n/hebrwcal.cpp @@ -301,7 +301,7 @@ void HebrewCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& */ void HebrewCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) { - add((UCalendarDateFields)field, amount, status); + add(static_cast(field), amount, status); } namespace { @@ -378,7 +378,7 @@ void HebrewCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& } void HebrewCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { - roll((UCalendarDateFields)field, amount, status); + roll(static_cast(field), amount, status); } //------------------------------------------------------------------------- @@ -435,7 +435,7 @@ int32_t startOfYear(int32_t year, UErrorCode &status) if (day == 0) { // # of months before year int64_t months = ClockMath::floorDivideInt64( - (235LL * (int64_t)year - 234LL), 19LL); + (235LL * static_cast(year) - 234LL), 19LL); int64_t frac = months * MONTH_FRACT + BAHARAD; // Fractional part of day # day = months * 29LL + frac / DAY_PARTS; // Whole # part of calculation @@ -641,8 +641,8 @@ void HebrewCalendar::handleComputeFields(int32_t julianDay, UErrorCode &status) return; } int32_t d = julianDay - 347997; - double m = ClockMath::floorDivide((d * (double)DAY_PARTS), (double) MONTH_PARTS); // Months (approx) - int32_t year = (int32_t)(ClockMath::floorDivide((19. * m + 234.), 235.) + 1.); // Years (approx) + double m = ClockMath::floorDivide((d * static_cast(DAY_PARTS)), static_cast(MONTH_PARTS)); // Months (approx) + int32_t year = static_cast(ClockMath::floorDivide((19. * m + 234.), 235.) + 1.); // Years (approx) int32_t ys = startOfYear(year, status); // 1st day of year if (U_FAILURE(status)) { return; @@ -863,7 +863,7 @@ int32_t HebrewCalendar::internalGetMonth(UErrorCode& status) const { } if (resolveFields(kMonthPrecedence) == UCAL_ORDINAL_MONTH) { int32_t ordinalMonth = internalGet(UCAL_ORDINAL_MONTH); - HebrewCalendar *nonConstThis = (HebrewCalendar*)this; // cast away const + HebrewCalendar* nonConstThis = const_cast(this); // cast away const int32_t year = nonConstThis->handleGetExtendedYear(status); if (U_FAILURE(status)) { diff --git a/icu4c/source/i18n/indiancal.cpp b/icu4c/source/i18n/indiancal.cpp index a15f59db52dc..b1fd39b9927e 100644 --- a/icu4c/source/i18n/indiancal.cpp +++ b/icu4c/source/i18n/indiancal.cpp @@ -273,7 +273,7 @@ void IndianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) if (U_FAILURE(status)) return; IndianYear = gregorianYear - INDIAN_ERA_START; // Year in Saka era jdAtStartOfGregYear = gregorianToJD(gregorianYear, 0, 1); // JD at start of Gregorian year - yday = (int32_t)(julianDay - jdAtStartOfGregYear); // Day number in Gregorian year (starting from 0) + yday = static_cast(julianDay - jdAtStartOfGregYear); // Day number in Gregorian year (starting from 0) if (yday < INDIAN_YEAR_START) { // Day is at the end of the preceding Saka year @@ -291,11 +291,11 @@ void IndianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) } else { mday = yday - leapMonth; if (mday < (31 * 5)) { - IndianMonth = (int32_t)uprv_floor(mday / 31) + 1; + IndianMonth = static_cast(uprv_floor(mday / 31)) + 1; IndianDayOfMonth = (mday % 31) + 1; } else { mday -= 31 * 5; - IndianMonth = (int32_t)uprv_floor(mday / 30) + 6; + IndianMonth = static_cast(uprv_floor(mday / 30)) + 6; IndianDayOfMonth = (mday % 30) + 1; } } diff --git a/icu4c/source/i18n/inputext.cpp b/icu4c/source/i18n/inputext.cpp index 0351518b704e..4a7712404ca3 100644 --- a/icu4c/source/i18n/inputext.cpp +++ b/icu4c/source/i18n/inputext.cpp @@ -50,15 +50,15 @@ void InputText::setText(const char *in, int32_t len) { fInputLen = 0; fC1Bytes = false; - fRawInput = (const uint8_t *) in; - fRawLength = len == -1? (int32_t)uprv_strlen(in) : len; + fRawInput = reinterpret_cast(in); + fRawLength = len == -1 ? static_cast(uprv_strlen(in)) : len; } void InputText::setDeclaredEncoding(const char* encoding, int32_t len) { if(encoding) { if (len == -1) { - len = (int32_t)uprv_strlen(encoding); + len = static_cast(uprv_strlen(encoding)); } len += 1; // to make place for the \0 at the end. @@ -98,7 +98,7 @@ void InputText::MungeInput(UBool fStripTags) { for (srci = 0; srci < fRawLength && dsti < BUFFER_SIZE; srci += 1) { b = fRawInput[srci]; - if (b == (uint8_t)0x3C) { /* Check for the ASCII '<' */ + if (b == static_cast(0x3C)) { /* Check for the ASCII '<' */ if (inMarkup) { badTags += 1; } @@ -111,7 +111,7 @@ void InputText::MungeInput(UBool fStripTags) { fInputBytes[dsti++] = b; } - if (b == (uint8_t)0x3E) { /* Check for the ASCII '>' */ + if (b == static_cast(0x3E)) { /* Check for the ASCII '>' */ inMarkup = false; } } diff --git a/icu4c/source/i18n/islamcal.cpp b/icu4c/source/i18n/islamcal.cpp index 7a9ac5c0852b..f8b8aa9f3bb0 100644 --- a/icu4c/source/i18n/islamcal.cpp +++ b/icu4c/source/i18n/islamcal.cpp @@ -387,7 +387,7 @@ int32_t trueMonthStart(int32_t month, UErrorCode& status) { } while (age < 0); } start = ClockMath::floorDivideInt64( - (int64_t)((int64_t)origin - HIJRA_MILLIS), (int64_t)kOneDay) + 1; + static_cast(static_cast(origin) - HIJRA_MILLIS), static_cast(kOneDay)) + 1; CalendarCache::put(&gMonthCache, month, start, status); } if(U_FAILURE(status)) { @@ -530,9 +530,9 @@ void IslamicCalendar::handleComputeFields(int32_t julianDay, UErrorCode &status) int32_t days = julianDay - getEpoc(); // Guess at the number of elapsed full months since the epoch - int32_t month = (int32_t)uprv_floor((double)days / CalendarAstronomer::SYNODIC_MONTH); + int32_t month = static_cast(uprv_floor(static_cast(days) / CalendarAstronomer::SYNODIC_MONTH)); - int32_t startDate = (int32_t)uprv_floor(month * CalendarAstronomer::SYNODIC_MONTH); + int32_t startDate = static_cast(uprv_floor(month * CalendarAstronomer::SYNODIC_MONTH)); double age = moonAge(internalGetTime()); if ( days - startDate >= 25 && age > 0) { @@ -825,7 +825,7 @@ int64_t IslamicUmalquraCalendar::yearStart(int32_t year, UErrorCode& status) con year -= UMALQURA_YEAR_START; // rounded least-squares fit of the dates previously calculated from UMALQURA_MONTHLENGTH iteration int64_t yrStartLinearEstimate = static_cast( - (354.36720 * (double)year) + 460322.05 + 0.5); + (354.36720 * static_cast(year)) + 460322.05 + 0.5); // need a slight correction to some return yrStartLinearEstimate + umAlQuraYrStartEstimateFix[year]; } @@ -863,7 +863,7 @@ int32_t IslamicUmalquraCalendar::handleGetMonthLength(int32_t extendedYear, int3 return IslamicCivilCalendar::handleGetMonthLength(extendedYear, month, status); } int32_t length = 29; - int32_t mask = (int32_t) (0x01 << (11 - month)); // set mask for bit corresponding to month + int32_t mask = static_cast(0x01 << (11 - month)); // set mask for bit corresponding to month int32_t index = extendedYear - UMALQURA_YEAR_START; if ((UMALQURA_MONTHLENGTH[index] & mask) != 0) { length++; @@ -935,7 +935,7 @@ void IslamicUmalquraCalendar::handleComputeFields(int32_t julianDay, UErrorCode // Estimate a value y which is closer to but not greater than the year. // It is the inverse function of the logic inside // IslamicUmalquraCalendar::yearStart(). - year = ((double(days) - (460322.05 + 0.5)) / 354.36720) + UMALQURA_YEAR_START - 1; + year = ((static_cast(days) - (460322.05 + 0.5)) / 354.36720) + UMALQURA_YEAR_START - 1; month = 0; int32_t d = 1; // need a slight correction to some diff --git a/icu4c/source/i18n/messageformat2.cpp b/icu4c/source/i18n/messageformat2.cpp index c5ae9f1c6085..7c337133780e 100644 --- a/icu4c/source/i18n/messageformat2.cpp +++ b/icu4c/source/i18n/messageformat2.cpp @@ -467,7 +467,7 @@ void MessageFormatter::resolvePreferences(MessageContext& context, UVector& res, int32_t numVariants = dataModel.numVariants(); const Variant* variants = dataModel.getVariantsInternal(); // 2. For each index i in res - for (int32_t i = 0; i < (int32_t) res.size(); i++) { + for (int32_t i = 0; i < res.size(); i++) { // 2i. Let keys be a new empty list of strings. LocalPointer keys(createUVector(status)); CHECK_ERROR(status); @@ -535,7 +535,7 @@ void MessageFormatter::filterVariants(const UVector& pref, UVector& vars, UError const Key* var = selectorKeys.getKeysInternal(); // 2i. For each index `i` in `pref`: bool noMatch = false; - for (int32_t i = 0; i < (int32_t) pref.size(); i++) { + for (int32_t i = 0; i < pref.size(); i++) { // 2i(a). Let `key` be the `var` key at position `i`. U_ASSERT(i < selectorKeys.len); const Key& key = var[i]; diff --git a/icu4c/source/i18n/messageformat2_function_registry.cpp b/icu4c/source/i18n/messageformat2_function_registry.cpp index 7bf5e2d82c36..34022b257ce1 100644 --- a/icu4c/source/i18n/messageformat2_function_registry.cpp +++ b/icu4c/source/i18n/messageformat2_function_registry.cpp @@ -385,7 +385,7 @@ MFFunctionRegistry::~MFFunctionRegistry() { } } } - return LocalizedNumberFormatter(nf.locale(number.locale)); + return nf.locale(number.locale); } Formatter* StandardFunctions::NumberFactory::createFormatter(const Locale& locale, UErrorCode& errorCode) { diff --git a/icu4c/source/i18n/messageformat2_parser.cpp b/icu4c/source/i18n/messageformat2_parser.cpp index abfbaedcacf3..fe5bfb484803 100644 --- a/icu4c/source/i18n/messageformat2_parser.cpp +++ b/icu4c/source/i18n/messageformat2_parser.cpp @@ -32,7 +32,7 @@ using namespace data_model; // Returns true iff `index` is a valid index for the string `source` static bool inBounds(const UnicodeString &source, uint32_t index) { - return (((int32_t)index) < source.length()); + return static_cast(index) < source.length(); } // Increments the line number and updates the "characters seen before @@ -815,7 +815,7 @@ Literal Parser::parseUnquotedLiteral(UErrorCode& errorCode) { } // Parse the integer part - if (source[index] == ((UChar32)0x0030) /* 0 */) { + if (source[index] == static_cast(0x0030) /* 0 */) { contents += source[index]; normalizedInput += source[index]; index++; @@ -2237,7 +2237,7 @@ void Parser::parse(UParseError &parseErrorResult, UErrorCode& status) { // if we know it's non-empty if (inBounds(source, index)) { if (source[index] == PERIOD - || (index < ((uint32_t) source.length() + 1) + || (index < static_cast(source.length()) + 1 && source[index] == LEFT_CURLY_BRACE && source[index + 1] == LEFT_CURLY_BRACE)) { // A complex message begins with a '.' or '{' @@ -2259,7 +2259,7 @@ void Parser::parse(UParseError &parseErrorResult, UErrorCode& status) { CHECK_ERROR(status); // There are no errors; finally, check that the entire input was consumed - if (((int32_t)index) != source.length()) { + if (static_cast(index) != source.length()) { ERROR(parseError, status, index); } diff --git a/icu4c/source/i18n/messageformat2_serializer.cpp b/icu4c/source/i18n/messageformat2_serializer.cpp index b55c55ab7ced..23c123e6f116 100644 --- a/icu4c/source/i18n/messageformat2_serializer.cpp +++ b/icu4c/source/i18n/messageformat2_serializer.cpp @@ -47,7 +47,7 @@ void Serializer::emit(const Literal& l) { if (l.isQuoted()) { emit(PIPE); const UnicodeString& contents = l.unquoted(); - for (int32_t i = 0; ((int32_t) i) < contents.length(); i++) { + for (int32_t i = 0; i < contents.length(); i++) { // Re-escape any PIPE or BACKSLASH characters switch(contents[i]) { case BACKSLASH: @@ -144,7 +144,7 @@ void Serializer::emit(const Reserved& reserved) { emit(l); } else { const UnicodeString& s = l.unquoted(); - for (int32_t j = 0; ((int32_t) j) < s.length(); j++) { + for (int32_t j = 0; j < s.length(); j++) { switch(s[j]) { case LEFT_CURLY_BRACE: case PIPE: @@ -199,7 +199,7 @@ void Serializer::emit(const PatternPart& part) { // Raw text const UnicodeString& text = part.asText(); // Re-escape '{'/'}'/'\' - for (int32_t i = 0; ((int32_t) i) < text.length(); i++) { + for (int32_t i = 0; i < text.length(); i++) { switch(text[i]) { case BACKSLASH: case LEFT_CURLY_BRACE: diff --git a/icu4c/source/i18n/msgfmt.cpp b/icu4c/source/i18n/msgfmt.cpp index 0413dc7465d6..ae6e76c99deb 100644 --- a/icu4c/source/i18n/msgfmt.cpp +++ b/icu4c/source/i18n/msgfmt.cpp @@ -355,8 +355,8 @@ UBool MessageFormat::allocateArgTypes(int32_t capacity, UErrorCode& status) { } else if (capacity < 2*argTypeCapacity) { capacity = 2*argTypeCapacity; } - Formattable::Type* a = (Formattable::Type*) - uprv_realloc(argTypes, sizeof(*argTypes) * capacity); + Formattable::Type* a = static_cast( + uprv_realloc(argTypes, sizeof(*argTypes) * capacity)); if (a == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return false; @@ -424,8 +424,8 @@ MessageFormat::operator==(const Format& rhs) const if (cur->key.integer != rhs_cur->key.integer) { return false; } - const Format* format = (const Format*)uhash_iget(cachedFormatters, cur->key.integer); - const Format* rhs_format = (const Format*)uhash_iget(that.cachedFormatters, rhs_cur->key.integer); + const Format* format = static_cast(uhash_iget(cachedFormatters, cur->key.integer)); + const Format* rhs_format = static_cast(uhash_iget(that.cachedFormatters, rhs_cur->key.integer)); if (*format != *rhs_format) { return false; } @@ -596,8 +596,8 @@ Format* MessageFormat::getCachedFormatter(int32_t argumentNumber) const { return nullptr; } void* ptr = uhash_iget(cachedFormatters, argumentNumber); - if (ptr != nullptr && dynamic_cast((Format*)ptr) == nullptr) { - return (Format*) ptr; + if (ptr != nullptr && dynamic_cast(static_cast(ptr)) == nullptr) { + return static_cast(ptr); } else { // Not cached, or a DummyFormat representing setFormat(nullptr). return nullptr; @@ -820,16 +820,16 @@ MessageFormat::getFormats(int32_t& cnt) const cnt = 0; if (formatAliases == nullptr) { t->formatAliasesCapacity = totalCapacity; - Format** a = (Format**) - uprv_malloc(sizeof(Format*) * formatAliasesCapacity); + Format** a = static_cast( + uprv_malloc(sizeof(Format*) * formatAliasesCapacity)); if (a == nullptr) { t->formatAliasesCapacity = 0; return nullptr; } t->formatAliases = a; } else if (totalCapacity > formatAliasesCapacity) { - Format** a = (Format**) - uprv_realloc(formatAliases, sizeof(Format*) * totalCapacity); + Format** a = static_cast( + uprv_realloc(formatAliases, sizeof(Format*) * totalCapacity)); if (a == nullptr) { t->formatAliasesCapacity = 0; return nullptr; @@ -1346,7 +1346,7 @@ void MessageFormat::copyObjects(const MessageFormat& that, UErrorCode& ec) { int32_t pos, idx; for (idx = 0, pos = UHASH_FIRST; idx < count && U_SUCCESS(ec); ++idx) { const UHashElement* cur = uhash_nextElement(that.cachedFormatters, &pos); - Format* newFormat = ((Format*)(cur->value.pointer))->clone(); + Format* newFormat = static_cast(cur->value.pointer)->clone(); if (newFormat) { uhash_iput(cachedFormatters, cur->key.integer, newFormat, &ec); } else { @@ -1827,7 +1827,7 @@ MessageFormat::createIntegerFormat(const Locale& locale, UErrorCode& status) con */ const NumberFormat* MessageFormat::getDefaultNumberFormat(UErrorCode& ec) const { if (defaultNumberFormat == nullptr) { - MessageFormat* t = (MessageFormat*) this; + MessageFormat* t = const_cast(this); t->defaultNumberFormat = NumberFormat::createInstance(fLocale, ec); if (U_FAILURE(ec)) { delete t->defaultNumberFormat; @@ -1848,7 +1848,7 @@ const NumberFormat* MessageFormat::getDefaultNumberFormat(UErrorCode& ec) const */ const DateFormat* MessageFormat::getDefaultDateFormat(UErrorCode& ec) const { if (defaultDateFormat == nullptr) { - MessageFormat* t = (MessageFormat*) this; + MessageFormat* t = const_cast(this); t->defaultDateFormat = DateFormat::createDateTimeInstance(DateFormat::kShort, DateFormat::kShort, fLocale); if (t->defaultDateFormat == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; @@ -1868,7 +1868,7 @@ MessageFormat::getArgTypeCount() const { } UBool MessageFormat::equalFormats(const void* left, const void* right) { - return *(const Format*)left==*(const Format*)right; + return *static_cast(left) == *static_cast(right); } @@ -1923,7 +1923,7 @@ FormatNameEnumeration::FormatNameEnumeration(LocalPointer nameList, UEr const UnicodeString* FormatNameEnumeration::snext(UErrorCode& status) { if (U_SUCCESS(status) && pos < fFormatNames->size()) { - return (const UnicodeString*)fFormatNames->elementAt(pos++); + return static_cast(fFormatNames->elementAt(pos++)); } return nullptr; } @@ -1972,7 +1972,7 @@ UnicodeString MessageFormat::PluralSelectorProvider::select(void *ctx, double nu context.numberArgIndex = msgFormat.findFirstPluralNumberArg(otherIndex, context.argName); if(context.numberArgIndex > 0 && msgFormat.cachedFormatters != nullptr) { context.formatter = - (const Format*)uhash_iget(msgFormat.cachedFormatters, context.numberArgIndex); + static_cast(uhash_iget(msgFormat.cachedFormatters, context.numberArgIndex)); } if(context.formatter == nullptr) { context.formatter = msgFormat.getDefaultNumberFormat(ec); diff --git a/icu4c/source/i18n/name2uni.cpp b/icu4c/source/i18n/name2uni.cpp index 2d26dba812c4..a15a0469cb5c 100644 --- a/icu4c/source/i18n/name2uni.cpp +++ b/icu4c/source/i18n/name2uni.cpp @@ -66,7 +66,7 @@ NameUnicodeTransliterator::NameUnicodeTransliterator(UnicodeFilter* adoptedFilte UnicodeSet *legalPtr = &legal; // Get the legal character set USetAdder sa = { - (USet *)legalPtr, // USet* == UnicodeSet* + reinterpret_cast(legalPtr), // USet* == UnicodeSet* _set_add, nullptr, // Don't need _set_addRange nullptr, // Don't need _set_addString @@ -121,7 +121,7 @@ void NameUnicodeTransliterator::handleTransliterate(Replaceable& text, UTransPos // Accommodate the longest possible name ++maxLen; // allow for temporary trailing space - char* cbuf = (char*) uprv_malloc(maxLen); + char* cbuf = static_cast(uprv_malloc(maxLen)); if (cbuf == nullptr) { offsets.start = offsets.limit; return; diff --git a/icu4c/source/i18n/nfrlist.h b/icu4c/source/i18n/nfrlist.h index 1864d4d3bd99..bb19cb2beac9 100644 --- a/icu4c/source/i18n/nfrlist.h +++ b/icu4c/source/i18n/nfrlist.h @@ -39,7 +39,7 @@ class NFRuleList : public UMemory { uint32_t fCapacity; public: NFRuleList(uint32_t capacity = 10) - : fStuff(capacity ? (NFRule**)uprv_malloc(capacity * sizeof(NFRule*)) : nullptr) + : fStuff(capacity ? static_cast(uprv_malloc(capacity * sizeof(NFRule*))) : nullptr) , fCount(0) , fCapacity(capacity) {} ~NFRuleList() { @@ -65,7 +65,7 @@ class NFRuleList : public UMemory { void add(NFRule* thing) { if (fCount == fCapacity) { fCapacity += 10; - fStuff = (NFRule**)uprv_realloc(fStuff, fCapacity * sizeof(NFRule*)); // assume success + fStuff = static_cast(uprv_realloc(fStuff, fCapacity * sizeof(NFRule*))); // assume success } if (fStuff != nullptr) { fStuff[fCount++] = thing; diff --git a/icu4c/source/i18n/nfrs.cpp b/icu4c/source/i18n/nfrs.cpp index 1f4b9b9d2945..b8bd7a31cbfe 100644 --- a/icu4c/source/i18n/nfrs.cpp +++ b/icu4c/source/i18n/nfrs.cpp @@ -490,7 +490,7 @@ NFRuleSet::findNormalRule(int64_t number) const // to find the rule (we should only go into this clause if the // value is 0) if (fIsFractionRuleSet) { - return findFractionRuleSetRule((double)number); + return findFractionRuleSetRule(static_cast(number)); } // if the number is negative, return the negative-number rule @@ -590,7 +590,7 @@ NFRuleSet::findFractionRuleSetRule(double number) const for (uint32_t i = 1; i < rules.size(); ++i) { leastCommonMultiple = util_lcm(leastCommonMultiple, rules[i]->getBaseValue()); } - numerator = util64_fromDouble(number * (double)leastCommonMultiple + 0.5); + numerator = util64_fromDouble(number * static_cast(leastCommonMultiple) + 0.5); } // for each rule, do the following... int64_t tempDifference; @@ -632,9 +632,9 @@ NFRuleSet::findFractionRuleSetRule(double number) const // the numerator of the fraction is anything else (this lets us // do things like "one third"/"two thirds" without having to define // a whole bunch of extra rule sets) - if ((unsigned)(winner + 1) < rules.size() && + if (static_cast(winner + 1) < rules.size() && rules[winner + 1]->getBaseValue() == rules[winner]->getBaseValue()) { - double n = ((double)rules[winner]->getBaseValue()) * number; + double n = static_cast(rules[winner]->getBaseValue()) * number; if (n < 0.5 || n >= 2) { ++winner; } @@ -825,7 +825,7 @@ int64_t util64_fromDouble(double d) { if (neg) { d = -d; } - result = (int64_t)uprv_floor(d); + result = static_cast(uprv_floor(d)); if (neg) { result = -result; } @@ -860,7 +860,7 @@ static const uint8_t asciiDigits[] = { 0x77u, 0x78u, 0x79u, 0x7au, }; -static const char16_t kUMinus = (char16_t)0x002d; +static const char16_t kUMinus = static_cast(0x002d); #ifdef RBNF_DEBUG static const char kMinus = '-'; @@ -998,15 +998,15 @@ uint32_t util64_tou(int64_t w, char16_t* buf, uint32_t len, uint32_t radix, UBoo *p++ = kUMinus; --len; } else if (len && (w == 0)) { - *p++ = (char16_t)raw ? 0 : asciiDigits[0]; + *p++ = static_cast(raw) ? 0 : asciiDigits[0]; --len; } while (len && (w != 0)) { int64_t n = w / base; int64_t m = n * base; - int32_t d = (int32_t)(w-m); - *p++ = (char16_t)(raw ? d : asciiDigits[d]); + int32_t d = static_cast(w - m); + *p++ = static_cast(raw ? d : asciiDigits[d]); w = n; --len; } @@ -1014,7 +1014,7 @@ uint32_t util64_tou(int64_t w, char16_t* buf, uint32_t len, uint32_t radix, UBoo *p = 0; // null terminate if room for caller convenience } - len = (uint32_t)(p - buf); + len = static_cast(p - buf); if (*buf == kUMinus) { ++buf; } diff --git a/icu4c/source/i18n/nfrule.cpp b/icu4c/source/i18n/nfrule.cpp index 1c78e6b1a25e..247c0a31be4b 100644 --- a/icu4c/source/i18n/nfrule.cpp +++ b/icu4c/source/i18n/nfrule.cpp @@ -35,7 +35,7 @@ U_NAMESPACE_BEGIN NFRule::NFRule(const RuleBasedNumberFormat* _rbnf, const UnicodeString &_ruleText, UErrorCode &status) - : baseValue((int32_t)0) + : baseValue(static_cast(0)) , radix(10) , exponent(0) , decimalPoint(0) @@ -289,7 +289,7 @@ NFRule::parseRuleDescriptor(UnicodeString& description, UErrorCode& status) while (p < descriptorLength) { c = descriptor.charAt(p); if (c >= gZero && c <= gNine) { - val = val * ll_10 + (int32_t)(c - gZero); + val = val * ll_10 + static_cast(c - gZero); } else if (c == gSlash || c == gGreaterThan) { break; @@ -318,7 +318,7 @@ NFRule::parseRuleDescriptor(UnicodeString& description, UErrorCode& status) while (p < descriptorLength) { c = descriptor.charAt(p); if (c >= gZero && c <= gNine) { - val = val * ll_10 + (int32_t)(c - gZero); + val = val * ll_10 + static_cast(c - gZero); } else if (c == gGreaterThan) { break; @@ -335,7 +335,7 @@ NFRule::parseRuleDescriptor(UnicodeString& description, UErrorCode& status) // tempValue now contain's the rule's radix. Set it // accordingly, and recalculate the rule's exponent - radix = (int32_t)val; + radix = static_cast(val); if (radix == 0) { // throw new IllegalArgumentException("Rule can't have radix of 0"); status = U_PARSE_ERROR; @@ -581,7 +581,8 @@ NFRule::expectedExponent() const // we get rounding error in some cases-- for example, log 1000 / log 10 // gives us 1.9999999996 instead of 2. The extra logic here is to take // that into account - int16_t tempResult = (int16_t)(uprv_log((double)baseValue) / uprv_log((double)radix)); + int16_t tempResult = static_cast(uprv_log(static_cast(baseValue)) / + uprv_log(static_cast(radix))); int64_t temp = util64_pow(radix, tempResult + 1); if (temp <= baseValue) { tempResult += 1; @@ -764,7 +765,7 @@ NFRule::doFormat(int64_t number, UnicodeString& toInsertInto, int32_t pos, int32 toInsertInto.insert(pos, fRuleText.tempSubString(pluralRuleEnd + 2)); } toInsertInto.insert(pos, - rulePatternFormat->format((int32_t)(number/util64_pow(radix, exponent)), status)); + rulePatternFormat->format(static_cast(number / util64_pow(radix, exponent)), status)); if (pluralRuleStart > 0) { toInsertInto.insert(pos, fRuleText.tempSubString(0, pluralRuleStart)); } @@ -818,7 +819,7 @@ NFRule::doFormat(double number, UnicodeString& toInsertInto, int32_t pos, int32_ else { pluralVal = pluralVal / util64_pow(radix, exponent); } - toInsertInto.insert(pos, rulePatternFormat->format((int32_t)(pluralVal), status)); + toInsertInto.insert(pos, rulePatternFormat->format(static_cast(pluralVal), status)); if (pluralRuleStart > 0) { toInsertInto.insert(pos, fRuleText.tempSubString(0, pluralRuleStart)); } @@ -998,7 +999,7 @@ NFRule::doParse(const UnicodeString& text, int highWaterMark = 0; double result = 0; int start = 0; - double tempBaseValue = (double)(baseValue <= 0 ? 0 : baseValue); + double tempBaseValue = static_cast(baseValue <= 0 ? 0 : baseValue); UnicodeString temp; do { diff --git a/icu4c/source/i18n/nfrule.h b/icu4c/source/i18n/nfrule.h index 2ae074cd8600..dd604085aecd 100644 --- a/icu4c/source/i18n/nfrule.h +++ b/icu4c/source/i18n/nfrule.h @@ -57,8 +57,8 @@ class NFRule : public UMemory { bool operator==(const NFRule& rhs) const; bool operator!=(const NFRule& rhs) const { return !operator==(rhs); } - ERuleType getType() const { return (ERuleType)(baseValue <= kNoBase ? (ERuleType)baseValue : kOtherRule); } - void setType(ERuleType ruleType) { baseValue = (int32_t)ruleType; } + ERuleType getType() const { return (baseValue <= kNoBase ? static_cast(baseValue) : kOtherRule); } + void setType(ERuleType ruleType) { baseValue = static_cast(ruleType); } int64_t getBaseValue() const { return baseValue; } void setBaseValue(int64_t value, UErrorCode& status); diff --git a/icu4c/source/i18n/nfsubs.cpp b/icu4c/source/i18n/nfsubs.cpp index ecd3b7b68fc2..7dfba6f369fd 100644 --- a/icu4c/source/i18n/nfsubs.cpp +++ b/icu4c/source/i18n/nfsubs.cpp @@ -62,7 +62,7 @@ class SameValueSubstitution : public NFSubstitution { virtual double transformNumber(double number) const override { return number; } virtual double composeRuleValue(double newRuleValue, double /*oldRuleValue*/) const override { return newRuleValue; } virtual double calcUpperBound(double oldUpperBound) const override { return oldUpperBound; } - virtual char16_t tokenChar() const override { return (char16_t)0x003d; } // '=' + virtual char16_t tokenChar() const override { return static_cast(0x003d); } // '=' public: static UClassID getStaticClassID(); @@ -132,7 +132,7 @@ class MultiplierSubstitution : public NFSubstitution { virtual double calcUpperBound(double /*oldUpperBound*/) const override { return static_cast(divisor); } - virtual char16_t tokenChar() const override { return (char16_t)0x003c; } // '<' + virtual char16_t tokenChar() const override { return static_cast(0x003c); } // '<' public: static UClassID getStaticClassID(); @@ -185,7 +185,7 @@ class ModulusSubstitution : public NFSubstitution { virtual UBool isModulusSubstitution() const override { return true; } - virtual char16_t tokenChar() const override { return (char16_t)0x003e; } // '>' + virtual char16_t tokenChar() const override { return static_cast(0x003e); } // '>' virtual void toString(UnicodeString& result) const override; @@ -209,7 +209,7 @@ class IntegralPartSubstitution : public NFSubstitution { virtual double transformNumber(double number) const override { return uprv_floor(number); } virtual double composeRuleValue(double newRuleValue, double oldRuleValue) const override { return newRuleValue + oldRuleValue; } virtual double calcUpperBound(double /*oldUpperBound*/) const override { return DBL_MAX; } - virtual char16_t tokenChar() const override { return (char16_t)0x003c; } // '<' + virtual char16_t tokenChar() const override { return static_cast(0x003c); } // '<' public: static UClassID getStaticClassID(); @@ -246,7 +246,7 @@ class FractionalPartSubstitution : public NFSubstitution { virtual double composeRuleValue(double newRuleValue, double oldRuleValue) const override { return newRuleValue + oldRuleValue; } virtual double calcUpperBound(double /*oldUpperBound*/) const override { return 0.0; } - virtual char16_t tokenChar() const override { return (char16_t)0x003e; } // '>' + virtual char16_t tokenChar() const override { return static_cast(0x003e); } // '>' public: static UClassID getStaticClassID(); @@ -268,7 +268,7 @@ class AbsoluteValueSubstitution : public NFSubstitution { virtual double transformNumber(double number) const override { return uprv_fabs(number); } virtual double composeRuleValue(double newRuleValue, double /*oldRuleValue*/) const override { return -newRuleValue; } virtual double calcUpperBound(double /*oldUpperBound*/) const override { return DBL_MAX; } - virtual char16_t tokenChar() const override { return (char16_t)0x003e; } // '>' + virtual char16_t tokenChar() const override { return static_cast(0x003e); } // '>' public: static UClassID getStaticClassID(); @@ -318,7 +318,7 @@ class NumeratorSubstitution : public NFSubstitution { virtual double composeRuleValue(double newRuleValue, double oldRuleValue) const override { return newRuleValue / oldRuleValue; } virtual double calcUpperBound(double /*oldUpperBound*/) const override { return denominator; } - virtual char16_t tokenChar() const override { return (char16_t)0x003c; } // '<' + virtual char16_t tokenChar() const override { return static_cast(0x003c); } // '<' private: static const char16_t LTLT[2]; @@ -365,7 +365,7 @@ NFSubstitution::makeSubstitution(int32_t pos, // if the rule set containing the rule is a fraction // rule set, return a NumeratorSubstitution else if (ruleSet->isFractionRuleSet()) { - return new NumeratorSubstitution(pos, (double)rule->getBaseValue(), + return new NumeratorSubstitution(pos, static_cast(rule->getBaseValue()), formatter->getDefaultRuleSet(), description, status); } @@ -600,7 +600,7 @@ NFSubstitution::doSubstitution(int64_t number, UnicodeString& toInsertInto, int3 // then use that formatter's format() method // to format the result UnicodeString temp; - numberFormat->format(transformNumber((double)number), temp, status); + numberFormat->format(transformNumber(static_cast(number)), temp, status); toInsertInto.insert(_pos + this->pos, temp); } else { @@ -1031,7 +1031,7 @@ FractionalPartSubstitution::FractionalPartSubstitution(int32_t _pos, } } else { // cast away const - ((NFRuleSet*)getRuleSet())->makeIntoFractionRuleSet(); + const_cast(getRuleSet())->makeIntoFractionRuleSet(); } } @@ -1103,7 +1103,7 @@ FractionalPartSubstitution::doSubstitution(double number, UnicodeString& toInser if (!pad) { // hack around lack of precision in digitlist. if we would end up with // "foo point" make sure we add a " zero" to the end. - getRuleSet()->format((int64_t)0, toInsertInto, _pos + getPos(), recursionCount, status); + getRuleSet()->format(static_cast(0), toInsertInto, _pos + getPos(), recursionCount, status); } } } @@ -1240,7 +1240,7 @@ NumeratorSubstitution::doSubstitution(double number, UnicodeString& toInsertInto int32_t len = toInsertInto.length(); while ((nf *= 10) < denominator) { toInsertInto.insert(apos + getPos(), gSpace); - aruleSet->format((int64_t)0, toInsertInto, apos + getPos(), recursionCount, status); + aruleSet->format(static_cast(0), toInsertInto, apos + getPos(), recursionCount, status); } apos += toInsertInto.length() - len; } @@ -1306,7 +1306,7 @@ NumeratorSubstitution::doParse(const UnicodeString& text, } workText = text; - workText.remove(0, (int32_t)parsePosition.getIndex()); + workText.remove(0, parsePosition.getIndex()); parsePosition.setIndex(0); } @@ -1329,7 +1329,7 @@ NumeratorSubstitution::doParse(const UnicodeString& text, --zeroCount; } // d is now our true denominator - result.setDouble((double)n/(double)d); + result.setDouble(static_cast(n) / static_cast(d)); } return true; diff --git a/icu4c/source/i18n/nortrans.cpp b/icu4c/source/i18n/nortrans.cpp index e2452cd37c9f..c57418dfdd2e 100644 --- a/icu4c/source/i18n/nortrans.cpp +++ b/icu4c/source/i18n/nortrans.cpp @@ -59,8 +59,8 @@ void NormalizationTransliterator::registerIDs() { */ Transliterator* NormalizationTransliterator::_create(const UnicodeString& ID, Token context) { - const char *name = (const char *)context.pointer; - UNormalization2Mode mode = (UNormalization2Mode)uprv_strchr(name, 0)[1]; + const char* name = static_cast(context.pointer); + UNormalization2Mode mode = static_cast(uprv_strchr(name, 0)[1]); UErrorCode errorCode = U_ZERO_ERROR; const Normalizer2 *norm2 = Normalizer2::getInstance(nullptr, name, mode, errorCode); if(U_SUCCESS(errorCode)) { diff --git a/icu4c/source/i18n/number_decimalquantity.cpp b/icu4c/source/i18n/number_decimalquantity.cpp index 227ead4e20b6..a8c033261d09 100644 --- a/icu4c/source/i18n/number_decimalquantity.cpp +++ b/icu4c/source/i18n/number_decimalquantity.cpp @@ -1113,7 +1113,7 @@ int8_t DecimalQuantity::getDigitPos(int32_t position) const { return fBCD.bcdBytes.ptr[position]; } else { if (position < 0 || position >= 16) { return 0; } - return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf); + return static_cast((fBCD.bcdLong >> (position * 4)) & 0xf); } } @@ -1128,7 +1128,7 @@ void DecimalQuantity::setDigitPos(int32_t position, int8_t value) { fBCD.bcdBytes.ptr[position] = value; } else { int shift = position * 4; - fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift); + fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | (static_cast(value) << shift); } } diff --git a/icu4c/source/i18n/number_grouping.cpp b/icu4c/source/i18n/number_grouping.cpp index 54aeffee811d..4ad16df2a298 100644 --- a/icu4c/source/i18n/number_grouping.cpp +++ b/icu4c/source/i18n/number_grouping.cpp @@ -78,7 +78,7 @@ void Grouper::setLocaleData(const impl::ParsedPatternInfo &patternInfo, const Lo auto grouping2 = static_cast ((patternInfo.positive.groupingSizes >> 16) & 0xffff); auto grouping3 = static_cast ((patternInfo.positive.groupingSizes >> 32) & 0xffff); if (grouping2 == -1) { - grouping1 = fGrouping1 == -4 ? (short) 3 : (short) -1; + grouping1 = fGrouping1 == -4 ? static_cast(3) : static_cast(-1); } if (grouping3 == -1) { grouping2 = grouping1; diff --git a/icu4c/source/i18n/number_usageprefs.cpp b/icu4c/source/i18n/number_usageprefs.cpp index 6f7fdaa9dcad..5c15c1cc3fb8 100644 --- a/icu4c/source/i18n/number_usageprefs.cpp +++ b/icu4c/source/i18n/number_usageprefs.cpp @@ -49,7 +49,7 @@ StringProp &StringProp::operator=(const StringProp &other) { // copying an errored StringProp. return *this; } - fValue = (char *)uprv_malloc(other.fLength + 1); + fValue = static_cast(uprv_malloc(other.fLength + 1)); if (fValue == nullptr) { fError = U_MEMORY_ALLOCATION_ERROR; return *this; @@ -96,7 +96,7 @@ void StringProp::set(StringPiece value) { fValue = nullptr; } fLength = value.length(); - fValue = (char *)uprv_malloc(fLength + 1); + fValue = static_cast(uprv_malloc(fLength + 1)); if (fValue == nullptr) { fLength = 0; fError = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/numfmt.cpp b/icu4c/source/i18n/numfmt.cpp index 74689e1363a8..7c877a33ab84 100644 --- a/icu4c/source/i18n/numfmt.cpp +++ b/icu4c/source/i18n/numfmt.cpp @@ -661,7 +661,7 @@ NumberFormat::format(int64_t number, FieldPosition& pos) const { // default so we don't introduce a new abstract method - return format((int32_t)number, appendTo, pos); + return format(static_cast(number), appendTo, pos); } // ------------------------------------- @@ -861,7 +861,7 @@ class ICUNumberFormatFactory : public ICUResourceBundleFactory { virtual ~ICUNumberFormatFactory(); protected: virtual UObject* handleCreate(const Locale& loc, int32_t kind, const ICUService* /* service */, UErrorCode& status) const override { - return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status); + return NumberFormat::makeInstance(loc, static_cast(kind), status); } }; @@ -893,7 +893,7 @@ class NFFactory : public LocaleKeyFactory { lkey->canonicalLocale(loc); int32_t kind = lkey->kind(); - UObject* result = _delegate->createFormat(loc, (UNumberFormatStyle)kind); + UObject* result = _delegate->createFormat(loc, static_cast(kind)); if (result == nullptr) { result = service->getKey(const_cast(key) /* cast away const */, nullptr, this, status); } @@ -914,7 +914,7 @@ class NFFactory : public LocaleKeyFactory { if (!_ids) { int32_t count = 0; const UnicodeString * const idlist = _delegate->getSupportedIDs(count, status); - ((NFFactory*)this)->_ids = new Hashtable(status); /* cast away const */ + const_cast(this)->_ids = new Hashtable(status); /* cast away const */ if (_ids) { for (int i = 0; i < count; ++i) { _ids->put(idlist[i], (void*)this, status); @@ -954,7 +954,7 @@ class ICUNumberFormatService : public ICULocaleService { int32_t kind = lkey->kind(); Locale loc; lkey->currentLocale(loc); - return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status); + return NumberFormat::makeInstance(loc, static_cast(kind), status); } virtual UBool isDefault() const override { @@ -1216,7 +1216,7 @@ void NumberFormat::setContext(UDisplayContext value, UErrorCode& status) { if (U_FAILURE(status)) return; - if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) { + if (static_cast(static_cast(value) >> 8) == UDISPCTX_TYPE_CAPITALIZATION) { fCapitalizationContext = value; } else { status = U_ILLEGAL_ARGUMENT_ERROR; @@ -1227,10 +1227,10 @@ void NumberFormat::setContext(UDisplayContext value, UErrorCode& status) UDisplayContext NumberFormat::getContext(UDisplayContextType type, UErrorCode& status) const { if (U_FAILURE(status)) - return (UDisplayContext)0; + return static_cast(0); if (type != UDISPCTX_TYPE_CAPITALIZATION) { status = U_ILLEGAL_ARGUMENT_ERROR; - return (UDisplayContext)0; + return static_cast(0); } return fCapitalizationContext; } @@ -1378,7 +1378,7 @@ NumberFormat::makeInstance(const Locale& desiredLocale, static UMutex nscacheMutex; Mutex lock(&nscacheMutex); - ns = (NumberingSystem *)uhash_iget(NumberingSystem_cache, hashKey); + ns = static_cast(uhash_iget(NumberingSystem_cache, hashKey)); if (ns == nullptr) { ns = NumberingSystem::createInstance(desiredLocale,status); uhash_iput(NumberingSystem_cache, hashKey, (void*)ns, &status); diff --git a/icu4c/source/i18n/numsys.cpp b/icu4c/source/i18n/numsys.cpp index 4fb1b5af3710..3123a5c8da39 100644 --- a/icu4c/source/i18n/numsys.cpp +++ b/icu4c/source/i18n/numsys.cpp @@ -258,7 +258,7 @@ void NumberingSystem::setDesc(const UnicodeString &d) { } void NumberingSystem::setName(const char *n) { if ( n == nullptr ) { - name[0] = (char) 0; + name[0] = static_cast(0); } else { uprv_strncpy(name,n,kInternalNumSysNameCapacity); name[kInternalNumSysNameCapacity] = '\0'; // Make sure it is null terminated. @@ -337,7 +337,7 @@ NumsysNameEnumeration::NumsysNameEnumeration(UErrorCode& status) : pos(0) { const UnicodeString* NumsysNameEnumeration::snext(UErrorCode& status) { if (U_SUCCESS(status) && (gNumsysNames != nullptr) && (pos < gNumsysNames->size())) { - return (const UnicodeString*)gNumsysNames->elementAt(pos++); + return static_cast(gNumsysNames->elementAt(pos++)); } return nullptr; } diff --git a/icu4c/source/i18n/olsontz.cpp b/icu4c/source/i18n/olsontz.cpp index cac3612c540b..9d9770dd4224 100644 --- a/icu4c/source/i18n/olsontz.cpp +++ b/icu4c/source/i18n/olsontz.cpp @@ -181,7 +181,7 @@ OlsonTimeZone::OlsonTimeZone(const UResourceBundle* top, if (U_SUCCESS(ec) && (len < 2 || len > 0x7FFE || (len & 1) != 0)) { ec = U_INVALID_FORMAT_ERROR; } - typeCount = (int16_t) len >> 1; + typeCount = static_cast(len) >> 1; // Type map data must be of the same size as the transition count typeMapData = nullptr; @@ -212,12 +212,12 @@ OlsonTimeZone::OlsonTimeZone(const UResourceBundle* top, finalZone = new SimpleTimeZone( ruleRaw * U_MILLIS_PER_SECOND, emptyStr, - (int8_t)ruleData[0], (int8_t)ruleData[1], (int8_t)ruleData[2], + static_cast(ruleData[0]), static_cast(ruleData[1]), static_cast(ruleData[2]), ruleData[3] * U_MILLIS_PER_SECOND, - (SimpleTimeZone::TimeMode) ruleData[4], - (int8_t)ruleData[5], (int8_t)ruleData[6], (int8_t)ruleData[7], + static_cast(ruleData[4]), + static_cast(ruleData[5]), static_cast(ruleData[6]), static_cast(ruleData[7]), ruleData[8] * U_MILLIS_PER_SECOND, - (SimpleTimeZone::TimeMode) ruleData[9], + static_cast(ruleData[9]), ruleData[10] * U_MILLIS_PER_SECOND, ec); if (finalZone == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; @@ -379,7 +379,7 @@ int32_t OlsonTimeZone::getOffset(uint8_t era, int32_t year, int32_t month, } // Compute local epoch millis from input fields - UDate date = (UDate)(Grego::fieldsToDay(year, month, dom) * U_MILLIS_PER_DAY + millis); + UDate date = static_cast(Grego::fieldsToDay(year, month, dom) * U_MILLIS_PER_DAY + millis); int32_t rawoff, dstoff; getHistoricalOffset(date, true, kDaylight, kStandard, rawoff, dstoff); return rawoff + dstoff; @@ -451,18 +451,18 @@ OlsonTimeZone::transitionTimeInSeconds(int16_t transIdx) const { U_ASSERT(transIdx >= 0 && transIdx < transitionCount()); if (transIdx < transitionCountPre32) { - return (((int64_t)((uint32_t)transitionTimesPre32[transIdx << 1])) << 32) - | ((int64_t)((uint32_t)transitionTimesPre32[(transIdx << 1) + 1])); + return (static_cast(static_cast(transitionTimesPre32[transIdx << 1])) << 32) + | static_cast(static_cast(transitionTimesPre32[(transIdx << 1) + 1])); } transIdx -= transitionCountPre32; if (transIdx < transitionCount32) { - return (int64_t)transitionTimes32[transIdx]; + return static_cast(transitionTimes32[transIdx]); } transIdx -= transitionCount32; - return (((int64_t)((uint32_t)transitionTimesPost32[transIdx << 1])) << 32) - | ((int64_t)((uint32_t)transitionTimesPost32[(transIdx << 1) + 1])); + return (static_cast(static_cast(transitionTimesPost32[transIdx << 1])) << 32) + | static_cast(static_cast(transitionTimesPost32[(transIdx << 1) + 1])); } // Maximum absolute offset in seconds (86400 seconds = 1 day) @@ -581,7 +581,7 @@ UBool OlsonTimeZone::useDaylightTime() const { // Return true if DST is observed at any time during the current // year. for (int16_t i = 0; i < transitionCount(); ++i) { - double transition = (double)transitionTimeInSeconds(i); + double transition = static_cast(transitionTimeInSeconds(i)); if (transition >= limit) { break; } @@ -739,7 +739,7 @@ OlsonTimeZone::initTransitionRules(UErrorCode& status) { // Actually no transitions... } else { // Build historic rule array - UDate* times = (UDate*)uprv_malloc(sizeof(UDate)*transCount); /* large enough to store all transition times */ + UDate* times = static_cast(uprv_malloc(sizeof(UDate) * transCount)); /* large enough to store all transition times */ if (times == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); @@ -749,8 +749,8 @@ OlsonTimeZone::initTransitionRules(UErrorCode& status) { // Gather all start times for each pair of offsets int32_t nTimes = 0; for (transitionIdx = firstTZTransitionIdx; transitionIdx < transCount; transitionIdx++) { - if (typeIdx == (int16_t)typeMapData[transitionIdx]) { - UDate tt = (UDate)transitionTime(transitionIdx); + if (typeIdx == static_cast(typeMapData[transitionIdx])) { + UDate tt = static_cast(transitionTime(transitionIdx)); if (finalZone == nullptr || tt <= finalStartMillis) { // Exclude transitions after finalMillis times[nTimes++] = tt; @@ -763,7 +763,7 @@ OlsonTimeZone::initTransitionRules(UErrorCode& status) { dst = typeOffsets[(typeIdx << 1) + 1] * U_MILLIS_PER_SECOND; if (historicRules == nullptr) { historicRuleCount = typeCount; - historicRules = (TimeArrayTimeZoneRule**)uprv_malloc(sizeof(TimeArrayTimeZoneRule*)*historicRuleCount); + historicRules = static_cast(uprv_malloc(sizeof(TimeArrayTimeZoneRule*) * historicRuleCount)); if (historicRules == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; deleteTransitionRules(); @@ -788,8 +788,8 @@ OlsonTimeZone::initTransitionRules(UErrorCode& status) { uprv_free(times); // Create initial transition - typeIdx = (int16_t)typeMapData[firstTZTransitionIdx]; - firstTZTransition = new TimeZoneTransition((UDate)transitionTime(firstTZTransitionIdx), + typeIdx = static_cast(typeMapData[firstTZTransitionIdx]); + firstTZTransition = new TimeZoneTransition(static_cast(transitionTime(firstTZTransitionIdx)), *initialRule, *historicRules[typeIdx]); // Check to make sure firstTZTransition was created. if (firstTZTransition == nullptr) { @@ -801,7 +801,7 @@ OlsonTimeZone::initTransitionRules(UErrorCode& status) { } if (finalZone != nullptr) { // Get the first occurrence of final rule starts - UDate startTime = (UDate)finalStartMillis; + UDate startTime = static_cast(finalStartMillis); TimeZoneRule *firstFinalRule = nullptr; if (finalZone->useDaylightTime()) { @@ -898,7 +898,7 @@ OlsonTimeZone::getNextTransition(UDate base, UBool inclusive, TimeZoneTransition int16_t transCount = transitionCount(); int16_t ttidx = transCount - 1; for (; ttidx >= firstTZTransitionIdx; ttidx--) { - UDate t = (UDate)transitionTime(ttidx); + UDate t = static_cast(transitionTime(ttidx)); if (base > t || (!inclusive && base == t)) { break; } @@ -917,7 +917,7 @@ OlsonTimeZone::getNextTransition(UDate base, UBool inclusive, TimeZoneTransition // Create a TimeZoneTransition TimeZoneRule *to = historicRules[typeMapData[ttidx + 1]]; TimeZoneRule *from = historicRules[typeMapData[ttidx]]; - UDate startTime = (UDate)transitionTime(ttidx+1); + UDate startTime = static_cast(transitionTime(ttidx + 1)); // The transitions loaded from zoneinfo.res may contain non-transition data UnicodeString fromName, toName; @@ -963,7 +963,7 @@ OlsonTimeZone::getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransi // Find a historical transition int16_t ttidx = transitionCount() - 1; for (; ttidx >= firstTZTransitionIdx; ttidx--) { - UDate t = (UDate)transitionTime(ttidx); + UDate t = static_cast(transitionTime(ttidx)); if (base > t || (inclusive && base == t)) { break; } @@ -978,7 +978,7 @@ OlsonTimeZone::getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransi // Create a TimeZoneTransition TimeZoneRule *to = historicRules[typeMapData[ttidx]]; TimeZoneRule *from = historicRules[typeMapData[ttidx-1]]; - UDate startTime = (UDate)transitionTime(ttidx); + UDate startTime = static_cast(transitionTime(ttidx)); // The transitions loaded from zoneinfo.res may contain non-transition data UnicodeString fromName, toName; diff --git a/icu4c/source/i18n/olsontz.h b/icu4c/source/i18n/olsontz.h index 9fe0d5dfed1b..1ca0455ee18a 100644 --- a/icu4c/source/i18n/olsontz.h +++ b/icu4c/source/i18n/olsontz.h @@ -410,7 +410,7 @@ OlsonTimeZone::transitionCount() const { inline double OlsonTimeZone::transitionTime(int16_t transIdx) const { - return (double)transitionTimeInSeconds(transIdx) * U_MILLIS_PER_SECOND; + return static_cast(transitionTimeInSeconds(transIdx)) * U_MILLIS_PER_SECOND; } inline int32_t diff --git a/icu4c/source/i18n/plurfmt.cpp b/icu4c/source/i18n/plurfmt.cpp index 7b225bcc8aa3..8effc71dff62 100644 --- a/icu4c/source/i18n/plurfmt.cpp +++ b/icu4c/source/i18n/plurfmt.cpp @@ -234,7 +234,7 @@ PluralFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos, UErrorCode& status) const { - return format(Formattable(number), (double)number, appendTo, pos, status); + return format(Formattable(number), static_cast(number), appendTo, pos, status); } UnicodeString& @@ -242,7 +242,7 @@ PluralFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos, UErrorCode& status) const { - return format(Formattable(number), (double)number, appendTo, pos, status); + return format(Formattable(number), number, appendTo, pos, status); } UnicodeString& diff --git a/icu4c/source/i18n/plurrule.cpp b/icu4c/source/i18n/plurrule.cpp index 2ded25d60064..cfb50a83fbba 100644 --- a/icu4c/source/i18n/plurrule.cpp +++ b/icu4c/source/i18n/plurrule.cpp @@ -1599,7 +1599,7 @@ PluralKeywordEnumeration::PluralKeywordEnumeration(RuleChain *header, UErrorCode const UnicodeString* PluralKeywordEnumeration::snext(UErrorCode& status) { if (U_SUCCESS(status) && pos < fKeywordNames.size()) { - return (const UnicodeString*)fKeywordNames.elementAt(pos++); + return static_cast(fKeywordNames.elementAt(pos++)); } return nullptr; } @@ -1783,7 +1783,7 @@ void FixedDecimal::init(double n, int32_t v, int64_t f, int32_t e, int32_t c) { intValue = 0; _hasIntegerValue = false; } else { - intValue = (int64_t)source; + intValue = static_cast(source); _hasIntegerValue = (source == intValue); } @@ -1867,17 +1867,17 @@ int64_t FixedDecimal::getFractionalDigits(double n, int32_t v) { n = fabs(n); double fract = n - floor(n); switch (v) { - case 1: return (int64_t)(fract*10.0 + 0.5); - case 2: return (int64_t)(fract*100.0 + 0.5); - case 3: return (int64_t)(fract*1000.0 + 0.5); + case 1: return static_cast(fract * 10.0 + 0.5); + case 2: return static_cast(fract * 100.0 + 0.5); + case 3: return static_cast(fract * 1000.0 + 0.5); default: - double scaled = floor(fract * pow(10.0, (double)v) + 0.5); + double scaled = floor(fract * pow(10.0, static_cast(v)) + 0.5); if (scaled >= static_cast(U_INT64_MAX)) { // Note: a double cannot accurately represent U_INT64_MAX. Casting it to double // will round up to the next representable value, which is U_INT64_MAX + 1. return U_INT64_MAX; } else { - return (int64_t)scaled; + return static_cast(scaled); } } } @@ -1902,7 +1902,7 @@ void FixedDecimal::adjustForMinFractionDigits(int32_t minFractionDigits) { double FixedDecimal::getPluralOperand(PluralOperand operand) const { switch(operand) { case PLURAL_OPERAND_N: return (exponent == 0 ? source : source * pow(10.0, exponent)); - case PLURAL_OPERAND_I: return (double) longValue(); + case PLURAL_OPERAND_I: return static_cast(longValue()); case PLURAL_OPERAND_F: return static_cast(decimalDigits); case PLURAL_OPERAND_T: return static_cast(decimalDigitsWithoutTrailingZeros); case PLURAL_OPERAND_V: return visibleDecimalDigitCount; @@ -1959,7 +1959,7 @@ int64_t FixedDecimal::longValue() const { if (exponent == 0) { return intValue; } else { - return (long) (pow(10.0, exponent) * intValue); + return static_cast(pow(10.0, exponent) * intValue); } } diff --git a/icu4c/source/i18n/plurrule_impl.h b/icu4c/source/i18n/plurrule_impl.h index 4de6d6460aaa..e57f931af3c4 100644 --- a/icu4c/source/i18n/plurrule_impl.h +++ b/icu4c/source/i18n/plurrule_impl.h @@ -50,67 +50,67 @@ namespace pluralimpl { // TODO: Remove this and replace with u"" literals. Was for EBCDIC compatibility. -static const char16_t DOT = ((char16_t) 0x002E); -static const char16_t SINGLE_QUOTE = ((char16_t) 0x0027); -static const char16_t SLASH = ((char16_t) 0x002F); -static const char16_t BACKSLASH = ((char16_t) 0x005C); -static const char16_t SPACE = ((char16_t) 0x0020); -static const char16_t EXCLAMATION = ((char16_t) 0x0021); -static const char16_t QUOTATION_MARK = ((char16_t) 0x0022); -static const char16_t NUMBER_SIGN = ((char16_t) 0x0023); -static const char16_t PERCENT_SIGN = ((char16_t) 0x0025); -static const char16_t ASTERISK = ((char16_t) 0x002A); -static const char16_t COMMA = ((char16_t) 0x002C); -static const char16_t HYPHEN = ((char16_t) 0x002D); -static const char16_t U_ZERO = ((char16_t) 0x0030); -static const char16_t U_ONE = ((char16_t) 0x0031); -static const char16_t U_TWO = ((char16_t) 0x0032); -static const char16_t U_THREE = ((char16_t) 0x0033); -static const char16_t U_FOUR = ((char16_t) 0x0034); -static const char16_t U_FIVE = ((char16_t) 0x0035); -static const char16_t U_SIX = ((char16_t) 0x0036); -static const char16_t U_SEVEN = ((char16_t) 0x0037); -static const char16_t U_EIGHT = ((char16_t) 0x0038); -static const char16_t U_NINE = ((char16_t) 0x0039); -static const char16_t COLON = ((char16_t) 0x003A); -static const char16_t SEMI_COLON = ((char16_t) 0x003B); -static const char16_t EQUALS = ((char16_t) 0x003D); -static const char16_t AT = ((char16_t) 0x0040); -static const char16_t CAP_A = ((char16_t) 0x0041); -static const char16_t CAP_B = ((char16_t) 0x0042); -static const char16_t CAP_R = ((char16_t) 0x0052); -static const char16_t CAP_Z = ((char16_t) 0x005A); -static const char16_t LOWLINE = ((char16_t) 0x005F); -static const char16_t LEFTBRACE = ((char16_t) 0x007B); -static const char16_t RIGHTBRACE = ((char16_t) 0x007D); -static const char16_t TILDE = ((char16_t) 0x007E); -static const char16_t ELLIPSIS = ((char16_t) 0x2026); - -static const char16_t LOW_A = ((char16_t) 0x0061); -static const char16_t LOW_B = ((char16_t) 0x0062); -static const char16_t LOW_C = ((char16_t) 0x0063); -static const char16_t LOW_D = ((char16_t) 0x0064); -static const char16_t LOW_E = ((char16_t) 0x0065); -static const char16_t LOW_F = ((char16_t) 0x0066); -static const char16_t LOW_G = ((char16_t) 0x0067); -static const char16_t LOW_H = ((char16_t) 0x0068); -static const char16_t LOW_I = ((char16_t) 0x0069); -static const char16_t LOW_J = ((char16_t) 0x006a); -static const char16_t LOW_K = ((char16_t) 0x006B); -static const char16_t LOW_L = ((char16_t) 0x006C); -static const char16_t LOW_M = ((char16_t) 0x006D); -static const char16_t LOW_N = ((char16_t) 0x006E); -static const char16_t LOW_O = ((char16_t) 0x006F); -static const char16_t LOW_P = ((char16_t) 0x0070); -static const char16_t LOW_Q = ((char16_t) 0x0071); -static const char16_t LOW_R = ((char16_t) 0x0072); -static const char16_t LOW_S = ((char16_t) 0x0073); -static const char16_t LOW_T = ((char16_t) 0x0074); -static const char16_t LOW_U = ((char16_t) 0x0075); -static const char16_t LOW_V = ((char16_t) 0x0076); -static const char16_t LOW_W = ((char16_t) 0x0077); -static const char16_t LOW_Y = ((char16_t) 0x0079); -static const char16_t LOW_Z = ((char16_t) 0x007A); +static const char16_t DOT = static_cast(0x002E); +static const char16_t SINGLE_QUOTE = static_cast(0x0027); +static const char16_t SLASH = static_cast(0x002F); +static const char16_t BACKSLASH = static_cast(0x005C); +static const char16_t SPACE = static_cast(0x0020); +static const char16_t EXCLAMATION = static_cast(0x0021); +static const char16_t QUOTATION_MARK = static_cast(0x0022); +static const char16_t NUMBER_SIGN = static_cast(0x0023); +static const char16_t PERCENT_SIGN = static_cast(0x0025); +static const char16_t ASTERISK = static_cast(0x002A); +static const char16_t COMMA = static_cast(0x002C); +static const char16_t HYPHEN = static_cast(0x002D); +static const char16_t U_ZERO = static_cast(0x0030); +static const char16_t U_ONE = static_cast(0x0031); +static const char16_t U_TWO = static_cast(0x0032); +static const char16_t U_THREE = static_cast(0x0033); +static const char16_t U_FOUR = static_cast(0x0034); +static const char16_t U_FIVE = static_cast(0x0035); +static const char16_t U_SIX = static_cast(0x0036); +static const char16_t U_SEVEN = static_cast(0x0037); +static const char16_t U_EIGHT = static_cast(0x0038); +static const char16_t U_NINE = static_cast(0x0039); +static const char16_t COLON = static_cast(0x003A); +static const char16_t SEMI_COLON = static_cast(0x003B); +static const char16_t EQUALS = static_cast(0x003D); +static const char16_t AT = static_cast(0x0040); +static const char16_t CAP_A = static_cast(0x0041); +static const char16_t CAP_B = static_cast(0x0042); +static const char16_t CAP_R = static_cast(0x0052); +static const char16_t CAP_Z = static_cast(0x005A); +static const char16_t LOWLINE = static_cast(0x005F); +static const char16_t LEFTBRACE = static_cast(0x007B); +static const char16_t RIGHTBRACE = static_cast(0x007D); +static const char16_t TILDE = static_cast(0x007E); +static const char16_t ELLIPSIS = static_cast(0x2026); + +static const char16_t LOW_A = static_cast(0x0061); +static const char16_t LOW_B = static_cast(0x0062); +static const char16_t LOW_C = static_cast(0x0063); +static const char16_t LOW_D = static_cast(0x0064); +static const char16_t LOW_E = static_cast(0x0065); +static const char16_t LOW_F = static_cast(0x0066); +static const char16_t LOW_G = static_cast(0x0067); +static const char16_t LOW_H = static_cast(0x0068); +static const char16_t LOW_I = static_cast(0x0069); +static const char16_t LOW_J = static_cast(0x006a); +static const char16_t LOW_K = static_cast(0x006B); +static const char16_t LOW_L = static_cast(0x006C); +static const char16_t LOW_M = static_cast(0x006D); +static const char16_t LOW_N = static_cast(0x006E); +static const char16_t LOW_O = static_cast(0x006F); +static const char16_t LOW_P = static_cast(0x0070); +static const char16_t LOW_Q = static_cast(0x0071); +static const char16_t LOW_R = static_cast(0x0072); +static const char16_t LOW_S = static_cast(0x0073); +static const char16_t LOW_T = static_cast(0x0074); +static const char16_t LOW_U = static_cast(0x0075); +static const char16_t LOW_V = static_cast(0x0076); +static const char16_t LOW_W = static_cast(0x0077); +static const char16_t LOW_Y = static_cast(0x0079); +static const char16_t LOW_Z = static_cast(0x007A); } diff --git a/icu4c/source/i18n/quant.cpp b/icu4c/source/i18n/quant.cpp index 4a45db1bf5c2..a4c21c8e721b 100644 --- a/icu4c/source/i18n/quant.cpp +++ b/icu4c/source/i18n/quant.cpp @@ -103,21 +103,21 @@ UnicodeString& Quantifier::toPattern(UnicodeString& result, matcher->toMatcher()->toPattern(result, escapeUnprintable); if (minCount == 0) { if (maxCount == 1) { - return result.append((char16_t)63); /*?*/ + return result.append(static_cast(63)); /*?*/ } else if (maxCount == MAX) { - return result.append((char16_t)42); /***/ + return result.append(static_cast(42)); /***/ } // else fall through } else if (minCount == 1 && maxCount == MAX) { - return result.append((char16_t)43); /*+*/ + return result.append(static_cast(43)); /*+*/ } - result.append((char16_t)123); /*{*/ + result.append(static_cast(123)); /*{*/ ICU_Utility::appendNumber(result, minCount); - result.append((char16_t)44); /*,*/ + result.append(static_cast(44)); /*,*/ if (maxCount != MAX) { ICU_Utility::appendNumber(result, maxCount); } - result.append((char16_t)125); /*}*/ + result.append(static_cast(125)); /*}*/ return result; } diff --git a/icu4c/source/i18n/quantityformatter.cpp b/icu4c/source/i18n/quantityformatter.cpp index 0a1982e3d4c8..f350c521f819 100644 --- a/icu4c/source/i18n/quantityformatter.cpp +++ b/icu4c/source/i18n/quantityformatter.cpp @@ -166,7 +166,7 @@ StandardPlural::Form QuantityFormatter::selectPlural( } else if (number.getType() == Formattable::kLong) { pluralKeyword = rules.select(number.getLong()); } else if (number.getType() == Formattable::kInt64) { - pluralKeyword = rules.select((double) number.getInt64()); + pluralKeyword = rules.select(static_cast(number.getInt64())); } else { status = U_ILLEGAL_ARGUMENT_ERROR; return StandardPlural::OTHER; diff --git a/icu4c/source/i18n/rbnf.cpp b/icu4c/source/i18n/rbnf.cpp index a30b945909cc..099e636b1ea7 100644 --- a/icu4c/source/i18n/rbnf.cpp +++ b/icu4c/source/i18n/rbnf.cpp @@ -226,9 +226,9 @@ class VArray { cap += 256; } if (buf == nullptr) { - buf = (void**)uprv_malloc(cap * sizeof(void*)); + buf = static_cast(uprv_malloc(cap * sizeof(void*))); } else { - buf = (void**)uprv_realloc(buf, cap * sizeof(void*)); + buf = static_cast(uprv_realloc(buf, cap * sizeof(void*))); } if (buf == nullptr) { // if we couldn't realloc, we leak the memory we've already allocated, but we're in deep trouble anyway @@ -460,7 +460,7 @@ LocDataParser::doParse() { array.add(nullptr, ec); if (U_SUCCESS(ec)) { int32_t numLocs = array.length() - 2; // subtract first, nullptr - char16_t*** result = (char16_t***)array.release(); + char16_t*** result = reinterpret_cast(array.release()); return new StringLocalizationInfo(data, result, requiredLength-2, numLocs); // subtract first, nullptr } @@ -515,7 +515,7 @@ LocDataParser::nextArray(int32_t& requiredLength) { ERROR("Array not of required length"); } - return (char16_t**)array.release(); + return reinterpret_cast(array.release()); } ERROR("Unknown Error"); } @@ -583,11 +583,11 @@ void LocDataParser::parseError(const char* EXPLANATION_ARG) if (limit > e) { limit = e; } - u_strncpy(pe.preContext, start, (int32_t)(p-start)); + u_strncpy(pe.preContext, start, static_cast(p - start)); pe.preContext[p-start] = 0; - u_strncpy(pe.postContext, p, (int32_t)(limit-p)); + u_strncpy(pe.postContext, p, static_cast(limit - p)); pe.postContext[limit-p] = 0; - pe.offset = (int32_t)(p - data); + pe.offset = static_cast(p - data); #ifdef RBNF_DEBUG fprintf(stderr, "%s at or near character %ld: ", EXPLANATION_ARG, p-data); @@ -632,7 +632,7 @@ StringLocalizationInfo::create(const UnicodeString& info, UParseError& perror, U return nullptr; // no error; } - char16_t* p = (char16_t*)uprv_malloc(len * sizeof(char16_t)); + char16_t* p = static_cast(uprv_malloc(len * sizeof(char16_t))); if (!p) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -647,7 +647,7 @@ StringLocalizationInfo::create(const UnicodeString& info, UParseError& perror, U } StringLocalizationInfo::~StringLocalizationInfo() { - for (char16_t*** p = (char16_t***)data; *p; ++p) { + for (char16_t*** p = data; *p; ++p) { // remaining data is simply pointer into our unicode string data. if (*p) uprv_free(*p); } @@ -990,7 +990,7 @@ UnicodeString RuleBasedNumberFormat::getRuleSetName(int32_t index) const { if (localizations) { - UnicodeString string(true, localizations->getRuleSetName(index), (int32_t)-1); + UnicodeString string(true, localizations->getRuleSetName(index), static_cast(-1)); return string; } else if (fRuleSets) { @@ -1045,7 +1045,7 @@ RuleBasedNumberFormat::getRuleSetDisplayNameLocale(int32_t index, UErrorCode& st int32_t cap = name.length() + 1; char* bp = buffer; if (cap > 64) { - bp = (char *)uprv_malloc(cap); + bp = static_cast(uprv_malloc(cap)); if (bp == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return {""}; @@ -1159,7 +1159,7 @@ RuleBasedNumberFormat::format(int32_t number, UnicodeString& toAppendTo, FieldPosition& pos) const { - return format((int64_t)number, toAppendTo, pos); + return format(static_cast(number), toAppendTo, pos); } @@ -1196,7 +1196,7 @@ RuleBasedNumberFormat::format(int32_t number, FieldPosition& pos, UErrorCode& status) const { - return format((int64_t)number, ruleSetName, toAppendTo, pos, status); + return format(static_cast(number), ruleSetName, toAppendTo, pos, status); } @@ -1555,7 +1555,7 @@ RuleBasedNumberFormat::init(const UnicodeString& rules, LocalizationInfo* locali ++numRuleSets; // our rule list is an array of the appropriate size - fRuleSets = (NFRuleSet **)uprv_malloc((numRuleSets + 1) * sizeof(NFRuleSet *)); + fRuleSets = static_cast(uprv_malloc((numRuleSets + 1) * sizeof(NFRuleSet*))); /* test for nullptr */ if (fRuleSets == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -1829,7 +1829,7 @@ RuleBasedNumberFormat::getCollator() const if (U_SUCCESS(status)) { newCollator->setAttribute(UCOL_DECOMPOSITION_MODE, UCOL_ON, status); // cast away const - ((RuleBasedNumberFormat*)this)->collator = newCollator; + const_cast(this)->collator = newCollator; } else { delete newCollator; } diff --git a/icu4c/source/i18n/rbt.cpp b/icu4c/source/i18n/rbt.cpp index 1ff04fd95b00..f34ddc9c3854 100644 --- a/icu4c/source/i18n/rbt.cpp +++ b/icu4c/source/i18n/rbt.cpp @@ -52,7 +52,7 @@ void RuleBasedTransliterator::_construct(const UnicodeString& rules, return; } - fData = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0); + fData = static_cast(parser.dataVector.orphanElementAt(0)); setMaximumContextLength(fData->ruleSet.getMaximumContextLength()); } @@ -142,7 +142,7 @@ RuleBasedTransliterator::RuleBasedTransliterator(const UnicodeString& id, const TransliterationRuleData* theData, UnicodeFilter* adoptedFilter) : Transliterator(id, adoptedFilter), - fData((TransliterationRuleData*)theData), // cast away const + fData(const_cast(theData)), // cast away const isDataOwned(false) { setMaximumContextLength(fData->ruleSet.getMaximumContextLength()); } diff --git a/icu4c/source/i18n/rbt_data.cpp b/icu4c/source/i18n/rbt_data.cpp index 0a08f9205400..6079e70caf9b 100644 --- a/icu4c/source/i18n/rbt_data.cpp +++ b/icu4c/source/i18n/rbt_data.cpp @@ -48,17 +48,17 @@ TransliterationRuleData::TransliterationRuleData(const TransliterationRuleData& const UHashElement *e; while ((e = other.variableNames.nextElement(pos)) != nullptr) { UnicodeString* value = - new UnicodeString(*(const UnicodeString*)e->value.pointer); + new UnicodeString(*static_cast(e->value.pointer)); // Exit out if value could not be created. if (value == nullptr) { return; } - variableNames.put(*(UnicodeString*)e->key.pointer, value, status); + variableNames.put(*static_cast(e->key.pointer), value, status); } variables = nullptr; if (other.variables != nullptr) { - variables = (UnicodeFunctor **)uprv_malloc(variablesLength * sizeof(UnicodeFunctor *)); + variables = static_cast(uprv_malloc(variablesLength * sizeof(UnicodeFunctor*))); /* test for nullptr */ if (variables == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/rbt_pars.cpp b/icu4c/source/i18n/rbt_pars.cpp index 880014b59bca..6d0d22724324 100644 --- a/icu4c/source/i18n/rbt_pars.cpp +++ b/icu4c/source/i18n/rbt_pars.cpp @@ -182,7 +182,7 @@ ParseData::~ParseData() {} * Implement SymbolTable API. */ const UnicodeString* ParseData::lookup(const UnicodeString& name) const { - return (const UnicodeString*) variableNames->get(name); + return static_cast(variableNames->get(name)); } /** @@ -196,7 +196,7 @@ const UnicodeFunctor* ParseData::lookupMatcher(UChar32 ch) const { if (i >= 0 && i < variablesVector->size()) { int32_t j = ch - data->variablesBase; set = (j < variablesVector->size()) ? - (UnicodeFunctor*) variablesVector->elementAt(j) : nullptr; + static_cast(variablesVector->elementAt(j)) : nullptr; } return set; } @@ -230,7 +230,7 @@ UBool ParseData::isMatcher(UChar32 ch) { // set array has not been constructed yet. int32_t i = ch - data->variablesBase; if (i >= 0 && i < variablesVector->size()) { - UnicodeFunctor *f = (UnicodeFunctor*) variablesVector->elementAt(i); + UnicodeFunctor* f = static_cast(variablesVector->elementAt(i)); return f != nullptr && f->toMatcher() != nullptr; } return true; @@ -245,7 +245,7 @@ UBool ParseData::isReplacer(UChar32 ch) { // set array has not been constructed yet. int i = ch - data->variablesBase; if (i >= 0 && i < variablesVector->size()) { - UnicodeFunctor *f = (UnicodeFunctor*) variablesVector->elementAt(i); + UnicodeFunctor* f = static_cast(variablesVector->elementAt(i)); return f != nullptr && f->toReplacer() != nullptr; } return true; @@ -446,7 +446,7 @@ int32_t RuleHalf::parseSection(const UnicodeString& rule, int32_t pos, int32_t l return syntaxError(U_TRAILING_BACKSLASH, rule, start, status); } UChar32 escaped = rule.unescapeAt(pos); // pos is already past '\\' - if (escaped == (UChar32) -1) { + if (escaped == static_cast(-1)) { return syntaxError(U_MALFORMED_UNICODE_ESCAPE, rule, start, status); } if (!parser.checkVariableRange(escaped)) { @@ -844,11 +844,11 @@ segmentObjects(statusReturn) */ TransliteratorParser::~TransliteratorParser() { while (!dataVector.isEmpty()) - delete (TransliterationRuleData*)(dataVector.orphanElementAt(0)); + delete static_cast(dataVector.orphanElementAt(0)); delete compoundFilter; delete parseData; while (!variablesVector.isEmpty()) - delete (UnicodeFunctor*)variablesVector.orphanElementAt(0); + delete static_cast(variablesVector.orphanElementAt(0)); } void @@ -895,7 +895,7 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, int32_t ruleCount = 0; while (!dataVector.isEmpty()) { - delete (TransliterationRuleData*)(dataVector.orphanElementAt(0)); + delete static_cast(dataVector.orphanElementAt(0)); } if (U_FAILURE(status)) { return; @@ -910,7 +910,7 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, compoundFilter = nullptr; while (!variablesVector.isEmpty()) { - delete (UnicodeFunctor*)variablesVector.orphanElementAt(0); + delete static_cast(variablesVector.orphanElementAt(0)); } variableNames.removeAll(); parseData = new ParseData(nullptr, &variablesVector, &variableNames); @@ -919,7 +919,7 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, return; } - dotStandIn = (char16_t) -1; + dotStandIn = static_cast(-1); UnicodeString *tempstr = nullptr; // used for memory allocation error checking UnicodeString str; // scratch @@ -943,7 +943,7 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, } // Skip lines starting with the comment character if (c == RULE_COMMENT_CHAR) { - pos = rule.indexOf((char16_t)0x000A /*\n*/, pos) + 1; + pos = rule.indexOf(static_cast(0x000A) /*\n*/, pos) + 1; if (pos == 0) { break; // No "\n" found; rest of rule is a comment } @@ -1106,12 +1106,12 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, // Convert the set vector to an array int32_t i, dataVectorSize = dataVector.size(); for (i = 0; i < dataVectorSize; i++) { - TransliterationRuleData* data = (TransliterationRuleData*)dataVector.elementAt(i); + TransliterationRuleData* data = static_cast(dataVector.elementAt(i)); data->variablesLength = variablesVector.size(); if (data->variablesLength == 0) { data->variables = nullptr; } else { - data->variables = (UnicodeFunctor**)uprv_malloc(data->variablesLength * sizeof(UnicodeFunctor*)); + data->variables = static_cast(uprv_malloc(data->variablesLength * sizeof(UnicodeFunctor*))); // nullptr pointer check if (data->variables == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; @@ -1129,12 +1129,12 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, int32_t p = UHASH_FIRST; const UHashElement* he = variableNames.nextElement(p); while (he != nullptr) { - UnicodeString* tempus = ((UnicodeString*)(he->value.pointer))->clone(); + UnicodeString* tempus = static_cast(he->value.pointer)->clone(); if (tempus == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; } - data->variableNames.put(*((UnicodeString*)(he->key.pointer)), + data->variableNames.put(*static_cast(he->key.pointer), tempus, status); he = variableNames.nextElement(p); } @@ -1150,10 +1150,10 @@ void TransliteratorParser::parseRules(const UnicodeString& rule, } for (i = 0; i < dataVectorSize; i++) { - TransliterationRuleData* data = (TransliterationRuleData*)dataVector.elementAt(i); + TransliterationRuleData* data = static_cast(dataVector.elementAt(i)); data->ruleSet.freeze(parseError, status); } - if (idBlockVector.size() == 1 && ((UnicodeString*)idBlockVector.elementAt(0))->isEmpty()) { + if (idBlockVector.size() == 1 && static_cast(idBlockVector.elementAt(0))->isEmpty()) { idBlockVector.removeElementAt(0); } } @@ -1168,10 +1168,10 @@ void TransliteratorParser::setVariableRange(int32_t start, int32_t end, UErrorCo return; } - curData->variablesBase = (char16_t) start; + curData->variablesBase = static_cast(start); if (dataVector.size() == 0) { - variableNext = (char16_t) start; - variableLimit = (char16_t) (end + 1); + variableNext = static_cast(start); + variableLimit = static_cast(end + 1); } } @@ -1453,12 +1453,12 @@ int32_t TransliteratorParser::parseRule(const UnicodeString& rule, int32_t pos, // Flatten segment objects vector to an array UnicodeFunctor** segmentsArray = nullptr; if (segmentObjects.size() > 0) { - segmentsArray = (UnicodeFunctor **)uprv_malloc(segmentObjects.size() * sizeof(UnicodeFunctor *)); + segmentsArray = static_cast(uprv_malloc(segmentObjects.size() * sizeof(UnicodeFunctor*))); // Null pointer check if (segmentsArray == nullptr) { return syntaxError(U_MEMORY_ALLOCATION_ERROR, rule, start, status); } - segmentObjects.toArray((void**) segmentsArray); + segmentObjects.toArray(reinterpret_cast(segmentsArray)); } TransliterationRule* temptr = new TransliterationRule( left->text, left->ante, left->post, @@ -1513,7 +1513,7 @@ int32_t TransliteratorParser::syntaxError(UErrorCode parseErrorCode, //null terminate the buffer parseError.postContext[stop-start]= 0; - status = (UErrorCode)parseErrorCode; + status = parseErrorCode; return pos; } @@ -1529,7 +1529,7 @@ char16_t TransliteratorParser::parseSet(const UnicodeString& rule, // Null pointer check if (set == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; - return (char16_t)0x0000; // Return empty character with error. + return static_cast(0x0000); // Return empty character with error. } set->compact(); return generateStandInFor(set, status); @@ -1546,7 +1546,7 @@ char16_t TransliteratorParser::generateStandInFor(UnicodeFunctor* adopted, UErro // (typical n is 0, 1, or 2); linear search is optimal. for (int32_t i=0; ivariablesBase + i); + return static_cast(curData->variablesBase + i); } } @@ -1619,12 +1619,12 @@ void TransliteratorParser::setSegmentObject(int32_t seg, StringMatcher* adopted, * time and reused thereafter. */ char16_t TransliteratorParser::getDotStandIn(UErrorCode& status) { - if (dotStandIn == (char16_t) -1) { + if (dotStandIn == static_cast(-1)) { UnicodeSet* tempus = new UnicodeSet(UnicodeString(true, DOT_SET, -1), status); // Null pointer check. if (tempus == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; - return (char16_t)0x0000; + return static_cast(0x0000); } dotStandIn = generateStandInFor(tempus, status); } @@ -1638,7 +1638,7 @@ char16_t TransliteratorParser::getDotStandIn(UErrorCode& status) { void TransliteratorParser::appendVariableDef(const UnicodeString& name, UnicodeString& buf, UErrorCode& status) { - const UnicodeString* s = (const UnicodeString*) variableNames.get(name); + const UnicodeString* s = static_cast(variableNames.get(name)); if (s == nullptr) { // We allow one undefined variable so that variable definition // statements work. For the first undefined variable we return @@ -1651,7 +1651,7 @@ void TransliteratorParser::appendVariableDef(const UnicodeString& name, status = U_ILLEGAL_ARGUMENT_ERROR; return; } - buf.append((char16_t) --variableLimit); + buf.append(--variableLimit); } else { //throw new IllegalArgumentException("Undefined variable $" // + name); diff --git a/icu4c/source/i18n/rbt_rule.cpp b/icu4c/source/i18n/rbt_rule.cpp index 4cf557e04d87..fb71f0f9b908 100644 --- a/icu4c/source/i18n/rbt_rule.cpp +++ b/icu4c/source/i18n/rbt_rule.cpp @@ -175,7 +175,7 @@ TransliterationRule::TransliterationRule(TransliterationRule& other) : segments = nullptr; segmentsCount = 0; if (other.segmentsCount > 0) { - segments = (UnicodeFunctor **)uprv_malloc(other.segmentsCount * sizeof(UnicodeFunctor *)); + segments = static_cast(uprv_malloc(other.segmentsCount * sizeof(UnicodeFunctor*))); uprv_memcpy(segments, other.segments, (size_t)other.segmentsCount*sizeof(segments[0])); } @@ -225,7 +225,7 @@ int16_t TransliterationRule::getIndexValue() const { return -1; } UChar32 c = pattern.char32At(anteContextLength); - return (int16_t)(data->lookupMatcher(c) == nullptr ? (c & 0xFF) : -1); + return static_cast(data->lookupMatcher(c) == nullptr ? (c & 0xFF) : -1); } /** @@ -481,27 +481,27 @@ UnicodeString& TransliterationRule::toRule(UnicodeString& rule, // Emit start anchor if ((flags & ANCHOR_START) != 0) { - rule.append((char16_t)94/*^*/); + rule.append(static_cast(94)/*^*/); } // Emit the input pattern ICU_Utility::appendToRule(rule, anteContext, escapeUnprintable, quoteBuf); if (emitBraces) { - ICU_Utility::appendToRule(rule, (char16_t) 0x007B /*{*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x007B) /*{*/, true, escapeUnprintable, quoteBuf); } ICU_Utility::appendToRule(rule, key, escapeUnprintable, quoteBuf); if (emitBraces) { - ICU_Utility::appendToRule(rule, (char16_t) 0x007D /*}*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x007D) /*}*/, true, escapeUnprintable, quoteBuf); } ICU_Utility::appendToRule(rule, postContext, escapeUnprintable, quoteBuf); // Emit end anchor if ((flags & ANCHOR_END) != 0) { - rule.append((char16_t)36/*$*/); + rule.append(static_cast(36)/*$*/); } ICU_Utility::appendToRule(rule, UnicodeString(true, FORWARD_OP, 3), true, escapeUnprintable, quoteBuf); @@ -511,7 +511,7 @@ UnicodeString& TransliterationRule::toRule(UnicodeString& rule, ICU_Utility::appendToRule(rule, output->toReplacer()->toReplacerPattern(str, escapeUnprintable), true, escapeUnprintable, quoteBuf); - ICU_Utility::appendToRule(rule, (char16_t) 0x003B /*;*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x003B) /*;*/, true, escapeUnprintable, quoteBuf); return rule; } diff --git a/icu4c/source/i18n/rbt_set.cpp b/icu4c/source/i18n/rbt_set.cpp index 23577f489f24..93852d9af976 100644 --- a/icu4c/source/i18n/rbt_set.cpp +++ b/icu4c/source/i18n/rbt_set.cpp @@ -193,7 +193,7 @@ TransliterationRuleSet::TransliterationRuleSet(const TransliterationRuleSet& oth len = other.ruleVector->size(); for (i=0; i tempTranslitRule( - new TransliterationRule(*(TransliterationRule*)other.ruleVector->elementAt(i)), status); + new TransliterationRule(*static_cast(other.ruleVector->elementAt(i))), status); ruleVector->adoptElement(tempTranslitRule.orphan(), status); } } @@ -295,14 +295,14 @@ void TransliterationRuleSet::freeze(UParseError& parseError,UErrorCode& status) /* Precompute the index values. This saves a LOT of time. * Be careful not to call malloc(0). */ - int16_t* indexValue = (int16_t*) uprv_malloc( sizeof(int16_t) * (n > 0 ? n : 1) ); + int16_t* indexValue = static_cast(uprv_malloc(sizeof(int16_t) * (n > 0 ? n : 1))); /* test for nullptr */ if (indexValue == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; } for (j=0; jelementAt(j); + TransliterationRule* r = static_cast(ruleVector->elementAt(j)); indexValue[j] = r->getIndexValue(); } for (x=0; x<256; ++x) { @@ -317,8 +317,8 @@ void TransliterationRuleSet::freeze(UParseError& parseError,UErrorCode& status) // a set, and we must use the more time-consuming // matchesIndexValue check. In practice this happens // rarely, so we seldom treat this code path. - TransliterationRule* r = (TransliterationRule*) ruleVector->elementAt(j); - if (r->matchesIndexValue((uint8_t)x)) { + TransliterationRule* r = static_cast(ruleVector->elementAt(j)); + if (r->matchesIndexValue(static_cast(x))) { v.addElement(r, status); } } @@ -339,14 +339,14 @@ void TransliterationRuleSet::freeze(UParseError& parseError,UErrorCode& status) rules = nullptr; return; } - rules = (TransliterationRule **)uprv_malloc(v.size() * sizeof(TransliterationRule *)); + rules = static_cast(uprv_malloc(v.size() * sizeof(TransliterationRule*))); /* test for nullptr */ if (rules == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; } for (j=0; j(v.elementAt(j)); } // TODO Add error reporting that indicates the rules that @@ -401,7 +401,7 @@ void TransliterationRuleSet::freeze(UParseError& parseError,UErrorCode& status) UBool TransliterationRuleSet::transliterate(Replaceable& text, UTransPosition& pos, UBool incremental) { - int16_t indexByte = (int16_t) (text.char32At(pos.start) & 0xFF); + int16_t indexByte = static_cast(text.char32At(pos.start) & 0xFF); for (int32_t i=index[indexByte]; imatchAndReplace(text, pos, incremental); switch (m) { @@ -431,10 +431,10 @@ UnicodeString& TransliterationRuleSet::toRules(UnicodeString& ruleSource, ruleSource.truncate(0); for (i=0; i(0x000A) /*\n*/); } TransliterationRule *r = - (TransliterationRule*) ruleVector->elementAt(i); + static_cast(ruleVector->elementAt(i)); r->toRule(ruleSource, escapeUnprintable); } return ruleSource; @@ -451,7 +451,7 @@ UnicodeSet& TransliterationRuleSet::getSourceTargetSet(UnicodeSet& result, int32_t count = ruleVector->size(); for (int32_t i=0; ielementAt(i); + static_cast(ruleVector->elementAt(i)); if (getTarget) { r->addTargetSetTo(result); } else { diff --git a/icu4c/source/i18n/rbtz.cpp b/icu4c/source/i18n/rbtz.cpp index 6bee2aa04baf..ad79bd60b164 100644 --- a/icu4c/source/i18n/rbtz.cpp +++ b/icu4c/source/i18n/rbtz.cpp @@ -49,8 +49,8 @@ static UBool compareRules(UVector* rules1, UVector* rules2) { return false; } for (int32_t i = 0; i < size; i++) { - TimeZoneRule *r1 = (TimeZoneRule*)rules1->elementAt(i); - TimeZoneRule *r2 = (TimeZoneRule*)rules2->elementAt(i); + TimeZoneRule* r1 = static_cast(rules1->elementAt(i)); + TimeZoneRule* r2 = static_cast(rules2->elementAt(i)); if (*r1 != *r2) { return false; } @@ -195,7 +195,7 @@ RuleBasedTimeZone::complete(UErrorCode& status) { if (fHistoricRules != nullptr && fHistoricRules->size() > 0) { int32_t i; int32_t historicCount = fHistoricRules->size(); - LocalMemory done((bool *)uprv_malloc(sizeof(bool) * historicCount)); + LocalMemory done(static_cast(uprv_malloc(sizeof(bool) * historicCount))); if (done == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; goto cleanup; @@ -218,7 +218,7 @@ RuleBasedTimeZone::complete(UErrorCode& status) { if (done[i]) { continue; } - r = (TimeZoneRule*)fHistoricRules->elementAt(i); + r = static_cast(fHistoricRules->elementAt(i)); avail = r->getNextStart(lastTransitionTime, curStdOffset, curDstSavings, false, tt); if (!avail) { // No more transitions from this rule - skip this rule next time @@ -254,11 +254,11 @@ RuleBasedTimeZone::complete(UErrorCode& status) { if (fFinalRules != nullptr) { // Check if one of final rules has earlier transition date for (i = 0; i < 2 /* fFinalRules->size() */; i++) { - TimeZoneRule *fr = (TimeZoneRule*)fFinalRules->elementAt(i); + TimeZoneRule* fr = static_cast(fFinalRules->elementAt(i)); if (*fr == *curRule) { continue; } - r = (TimeZoneRule*)fFinalRules->elementAt(i); + r = static_cast(fFinalRules->elementAt(i)); avail = r->getNextStart(lastTransitionTime, curStdOffset, curDstSavings, false, tt); if (avail) { if (tt < nextTransitionTime) { @@ -307,8 +307,8 @@ RuleBasedTimeZone::complete(UErrorCode& status) { fHistoricTransitions = lpHistoricTransitions.orphan(); } // Append the first transition for each - TimeZoneRule *rule0 = (TimeZoneRule*)fFinalRules->elementAt(0); - TimeZoneRule *rule1 = (TimeZoneRule*)fFinalRules->elementAt(1); + TimeZoneRule* rule0 = static_cast(fFinalRules->elementAt(0)); + TimeZoneRule* rule1 = static_cast(fFinalRules->elementAt(1)); UDate tt0, tt1; UBool avail0 = rule0->getNextStart(lastTransitionTime, curRule->getRawOffset(), curRule->getDSTSavings(), false, tt0); UBool avail1 = rule1->getNextStart(lastTransitionTime, curRule->getRawOffset(), curRule->getDSTSavings(), false, tt1); @@ -385,7 +385,7 @@ RuleBasedTimeZone::getOffset(uint8_t era, int32_t year, int32_t month, int32_t d year = 1 - year; } int32_t rawOffset, dstOffset; - UDate time = (UDate)Grego::fieldsToDay(year, month, day) * U_MILLIS_PER_DAY + millis; + UDate time = static_cast(Grego::fieldsToDay(year, month, day)) * U_MILLIS_PER_DAY + millis; getOffsetInternal(time, true, kDaylight, kStandard, rawOffset, dstOffset, status); if (U_FAILURE(status)) { return 0; @@ -431,13 +431,13 @@ RuleBasedTimeZone::getOffsetInternal(UDate date, UBool local, if (fHistoricTransitions == nullptr) { rule = fInitialRule; } else { - UDate tstart = getTransitionTime((Transition*)fHistoricTransitions->elementAt(0), + UDate tstart = getTransitionTime(static_cast(fHistoricTransitions->elementAt(0)), local, NonExistingTimeOpt, DuplicatedTimeOpt); if (date < tstart) { rule = fInitialRule; } else { int32_t idx = fHistoricTransitions->size() - 1; - UDate tend = getTransitionTime((Transition*)fHistoricTransitions->elementAt(idx), + UDate tend = getTransitionTime(static_cast(fHistoricTransitions->elementAt(idx)), local, NonExistingTimeOpt, DuplicatedTimeOpt); if (date > tend) { if (fFinalRules != nullptr) { @@ -446,18 +446,18 @@ RuleBasedTimeZone::getOffsetInternal(UDate date, UBool local, if (rule == nullptr) { // no final rules or the given time is before the first transition // specified by the final rules -> use the last rule - rule = ((Transition*)fHistoricTransitions->elementAt(idx))->to; + rule = static_cast(fHistoricTransitions->elementAt(idx))->to; } } else { // Find a historical transition while (idx >= 0) { - if (date >= getTransitionTime((Transition*)fHistoricTransitions->elementAt(idx), + if (date >= getTransitionTime(static_cast(fHistoricTransitions->elementAt(idx)), local, NonExistingTimeOpt, DuplicatedTimeOpt)) { break; } idx--; } - rule = ((Transition*)fHistoricTransitions->elementAt(idx))->to; + rule = static_cast(fHistoricTransitions->elementAt(idx))->to; } } } @@ -605,14 +605,14 @@ RuleBasedTimeZone::getTimeZoneRules(const InitialTimeZoneRule*& initial, int32_t historicCount = fHistoricRules->size(); idx = 0; while (cnt < trscount && idx < historicCount) { - trsrules[cnt++] = (const TimeZoneRule*)fHistoricRules->elementAt(idx++); + trsrules[cnt++] = static_cast(fHistoricRules->elementAt(idx++)); } } if (fFinalRules != nullptr && cnt < trscount) { int32_t finalCount = fFinalRules->size(); idx = 0; while (cnt < trscount && idx < finalCount) { - trsrules[cnt++] = (const TimeZoneRule*)fFinalRules->elementAt(idx++); + trsrules[cnt++] = static_cast(fFinalRules->elementAt(idx++)); } } // Set the result length @@ -652,7 +652,7 @@ RuleBasedTimeZone::copyRules(UVector* source) { } int32_t i; for (i = 0; i < size; i++) { - LocalPointer rule(((TimeZoneRule*)source->elementAt(i))->clone(), ec); + LocalPointer rule(static_cast(source->elementAt(i))->clone(), ec); rules->adoptElement(rule.orphan(), ec); if (U_FAILURE(ec)) { return nullptr; @@ -668,8 +668,8 @@ RuleBasedTimeZone::findRuleInFinal(UDate date, UBool local, return nullptr; } - AnnualTimeZoneRule* fr0 = (AnnualTimeZoneRule*)fFinalRules->elementAt(0); - AnnualTimeZoneRule* fr1 = (AnnualTimeZoneRule*)fFinalRules->elementAt(1); + AnnualTimeZoneRule* fr0 = static_cast(fFinalRules->elementAt(0)); + AnnualTimeZoneRule* fr1 = static_cast(fFinalRules->elementAt(1)); if (fr0 == nullptr || fr1 == nullptr) { return nullptr; } @@ -718,14 +718,14 @@ RuleBasedTimeZone::findNext(UDate base, UBool inclusive, UDate& transitionTime, UBool isFinal = false; UBool found = false; Transition result; - Transition *tzt = (Transition*)fHistoricTransitions->elementAt(0); + Transition* tzt = static_cast(fHistoricTransitions->elementAt(0)); UDate tt = tzt->time; if (tt > base || (inclusive && tt == base)) { result = *tzt; found = true; } else { int32_t idx = fHistoricTransitions->size() - 1; - tzt = (Transition*)fHistoricTransitions->elementAt(idx); + tzt = static_cast(fHistoricTransitions->elementAt(idx)); tt = tzt->time; if (inclusive && tt == base) { result = *tzt; @@ -733,8 +733,8 @@ RuleBasedTimeZone::findNext(UDate base, UBool inclusive, UDate& transitionTime, } else if (tt <= base) { if (fFinalRules != nullptr) { // Find a transion time with finalRules - TimeZoneRule *r0 = (TimeZoneRule*)fFinalRules->elementAt(0); - TimeZoneRule *r1 = (TimeZoneRule*)fFinalRules->elementAt(1); + TimeZoneRule* r0 = static_cast(fFinalRules->elementAt(0)); + TimeZoneRule* r1 = static_cast(fFinalRules->elementAt(1)); UDate start0, start1; UBool avail0 = r0->getNextStart(base, r1->getRawOffset(), r1->getDSTSavings(), inclusive, start0); UBool avail1 = r1->getNextStart(base, r0->getRawOffset(), r0->getDSTSavings(), inclusive, start1); @@ -759,7 +759,7 @@ RuleBasedTimeZone::findNext(UDate base, UBool inclusive, UDate& transitionTime, idx--; Transition *prev = tzt; while (idx > 0) { - tzt = (Transition*)fHistoricTransitions->elementAt(idx); + tzt = static_cast(fHistoricTransitions->elementAt(idx)); tt = tzt->time; if (tt < base || (!inclusive && tt == base)) { break; @@ -801,14 +801,14 @@ RuleBasedTimeZone::findPrev(UDate base, UBool inclusive, UDate& transitionTime, } UBool found = false; Transition result; - Transition *tzt = (Transition*)fHistoricTransitions->elementAt(0); + Transition* tzt = static_cast(fHistoricTransitions->elementAt(0)); UDate tt = tzt->time; if (inclusive && tt == base) { result = *tzt; found = true; } else if (tt < base) { int32_t idx = fHistoricTransitions->size() - 1; - tzt = (Transition*)fHistoricTransitions->elementAt(idx); + tzt = static_cast(fHistoricTransitions->elementAt(idx)); tt = tzt->time; if (inclusive && tt == base) { result = *tzt; @@ -816,8 +816,8 @@ RuleBasedTimeZone::findPrev(UDate base, UBool inclusive, UDate& transitionTime, } else if (tt < base) { if (fFinalRules != nullptr) { // Find a transion time with finalRules - TimeZoneRule *r0 = (TimeZoneRule*)fFinalRules->elementAt(0); - TimeZoneRule *r1 = (TimeZoneRule*)fFinalRules->elementAt(1); + TimeZoneRule* r0 = static_cast(fFinalRules->elementAt(0)); + TimeZoneRule* r1 = static_cast(fFinalRules->elementAt(1)); UDate start0, start1; UBool avail0 = r0->getPreviousStart(base, r1->getRawOffset(), r1->getDSTSavings(), inclusive, start0); UBool avail1 = r1->getPreviousStart(base, r0->getRawOffset(), r0->getDSTSavings(), inclusive, start1); @@ -842,7 +842,7 @@ RuleBasedTimeZone::findPrev(UDate base, UBool inclusive, UDate& transitionTime, // Find a transition within the historic transitions idx--; while (idx >= 0) { - tzt = (Transition*)fHistoricTransitions->elementAt(idx); + tzt = static_cast(fHistoricTransitions->elementAt(idx)); tt = tzt->time; if (tt < base || (inclusive && tt == base)) { break; diff --git a/icu4c/source/i18n/regexcmp.cpp b/icu4c/source/i18n/regexcmp.cpp index 1e599cd4e584..cfce4d76f09c 100644 --- a/icu4c/source/i18n/regexcmp.cpp +++ b/icu4c/source/i18n/regexcmp.cpp @@ -207,14 +207,14 @@ void RegexCompile::compile( // Table row specified "quoted" and the char was quoted. break; } - if (tableEl->fCharClass == 253 && fC.fChar == (UChar32)-1) { + if (tableEl->fCharClass == 253 && fC.fChar == static_cast(-1)) { // Table row specified eof and we hit eof on the input. break; } if (tableEl->fCharClass >= 128 && tableEl->fCharClass < 240 && // Table specs a char class && fC.fQuoted == false && // char is not escaped && - fC.fChar != (UChar32)-1) { // char is not EOF + fC.fChar != static_cast(-1)) { // char is not EOF U_ASSERT(tableEl->fCharClass <= 137); if (RegexStaticSets::gStaticSets->fRuleSets[tableEl->fCharClass-128].contains(fC.fChar)) { // Table row specified a character class, or set of characters, @@ -323,7 +323,7 @@ void RegexCompile::compile( } int32_t i; for (i=0; ifSets->elementAt(i); + UnicodeSet* s = static_cast(fRXPat->fSets->elementAt(i)); fRXPat->fSets8[i].init(s); } @@ -347,7 +347,7 @@ UBool RegexCompile::doParseActions(int32_t action) { UBool returnVal = true; - switch ((Regex_PatternParseAction)action) { + switch (static_cast(action)) { case doPatStart: // Start of pattern compiles to: @@ -403,7 +403,7 @@ UBool RegexCompile::doParseActions(int32_t action) // side fails to match and backtracks. Locate the position for the // save from the location on the top of the parentheses stack. int32_t savePosition = fParenStack.popi(); - int32_t op = (int32_t)fRXPat->fCompiledPat->elementAti(savePosition); + int32_t op = static_cast(fRXPat->fCompiledPat->elementAti(savePosition)); U_ASSERT(URX_TYPE(op) == URX_NOP); // original contents of reserved location op = buildOp(URX_STATE_SAVE, fRXPat->fCompiledPat->size()+1); fRXPat->fCompiledPat->setElementAt(op, savePosition); @@ -793,7 +793,7 @@ UBool RegexCompile::doParseActions(int32_t action) // Check for simple constructs, which may get special optimized code. if (topLoc == fRXPat->fCompiledPat->size() - 1) { - int32_t repeatedOp = (int32_t)fRXPat->fCompiledPat->elementAti(topLoc); + int32_t repeatedOp = static_cast(fRXPat->fCompiledPat->elementAti(topLoc)); if (URX_TYPE(repeatedOp) == URX_SETREF) { // Emit optimized code for [char set]+ @@ -925,7 +925,7 @@ UBool RegexCompile::doParseActions(int32_t action) // Check for simple *, where the construct being repeated // compiled to single opcode, and might be optimizable. if (topLoc == fRXPat->fCompiledPat->size() - 1) { - int32_t repeatedOp = (int32_t)fRXPat->fCompiledPat->elementAti(topLoc); + int32_t repeatedOp = static_cast(fRXPat->fCompiledPat->elementAti(topLoc)); if (URX_TYPE(repeatedOp) == URX_SETREF) { // Emit optimized code for a [char set]* @@ -1015,11 +1015,11 @@ UBool RegexCompile::doParseActions(int32_t action) { int32_t digitValue = u_charDigitValue(fC.fChar); U_ASSERT(digitValue >= 0); - int64_t val = (int64_t)fIntervalLow*10 + digitValue; + int64_t val = static_cast(fIntervalLow) * 10 + digitValue; if (val > INT32_MAX) { error(U_REGEX_NUMBER_TOO_BIG); } else { - fIntervalLow = (int32_t)val; + fIntervalLow = static_cast(val); } } break; @@ -1032,11 +1032,11 @@ UBool RegexCompile::doParseActions(int32_t action) } int32_t digitValue = u_charDigitValue(fC.fChar); U_ASSERT(digitValue >= 0); - int64_t val = (int64_t)fIntervalUpper*10 + digitValue; + int64_t val = static_cast(fIntervalUpper) * 10 + digitValue; if (val > INT32_MAX) { error(U_REGEX_NUMBER_TOO_BIG); } else { - fIntervalUpper = (int32_t)val; + fIntervalUpper = static_cast(val); } } break; @@ -1075,7 +1075,7 @@ UBool RegexCompile::doParseActions(int32_t action) int32_t op = buildOp(URX_STO_SP, varLoc); fRXPat->fCompiledPat->setElementAt(op, topLoc); - int32_t loopOp = (int32_t)fRXPat->fCompiledPat->popi(); + int32_t loopOp = static_cast(fRXPat->fCompiledPat->popi()); U_ASSERT(URX_TYPE(loopOp) == URX_CTR_LOOP && URX_VAL(loopOp) == topLoc); loopOp++; // point LoopOp after the just-inserted STO_SP fRXPat->fCompiledPat->push(loopOp, *fStatus); @@ -1545,28 +1545,28 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetAddAmp: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); set->add(chAmp); } break; case doSetAddDash: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); set->add(chDash); } break; case doSetBackslash_s: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); set->addAll(RegexStaticSets::gStaticSets->fPropSets[URX_ISSPACE_SET]); break; } case doSetBackslash_S: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet SSet; SSet.addAll(RegexStaticSets::gStaticSets->fPropSets[URX_ISSPACE_SET]).complement(); set->addAll(SSet); @@ -1575,7 +1575,7 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetBackslash_d: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); // TODO - make a static set, ticket 6058. addCategory(set, U_GC_ND_MASK, *fStatus); break; @@ -1583,7 +1583,7 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetBackslash_D: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet digits; // TODO - make a static set, ticket 6058. digits.applyIntPropertyValue(UCHAR_GENERAL_CATEGORY_MASK, U_GC_ND_MASK, *fStatus); @@ -1594,20 +1594,20 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetBackslash_h: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet h; h.applyIntPropertyValue(UCHAR_GENERAL_CATEGORY_MASK, U_GC_ZS_MASK, *fStatus); - h.add((UChar32)9); // Tab + h.add(static_cast(9)); // Tab set->addAll(h); break; } case doSetBackslash_H: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet h; h.applyIntPropertyValue(UCHAR_GENERAL_CATEGORY_MASK, U_GC_ZS_MASK, *fStatus); - h.add((UChar32)9); // Tab + h.add(static_cast(9)); // Tab h.complement(); set->addAll(h); break; @@ -1615,20 +1615,20 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetBackslash_v: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); - set->add((UChar32)0x0a, (UChar32)0x0d); // add range - set->add((UChar32)0x85); - set->add((UChar32)0x2028, (UChar32)0x2029); + UnicodeSet* set = static_cast(fSetStack.peek()); + set->add(static_cast(0x0a), static_cast(0x0d)); // add range + set->add(static_cast(0x85)); + set->add(static_cast(0x2028), static_cast(0x2029)); break; } case doSetBackslash_V: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet v; - v.add((UChar32)0x0a, (UChar32)0x0d); // add range - v.add((UChar32)0x85); - v.add((UChar32)0x2028, (UChar32)0x2029); + v.add(static_cast(0x0a), static_cast(0x0d)); // add range + v.add(static_cast(0x85)); + v.add(static_cast(0x2028), static_cast(0x2029)); v.complement(); set->addAll(v); break; @@ -1636,14 +1636,14 @@ UBool RegexCompile::doParseActions(int32_t action) case doSetBackslash_w: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); set->addAll(RegexStaticSets::gStaticSets->fPropSets[URX_ISWORD_SET]); break; } case doSetBackslash_W: { - UnicodeSet *set = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* set = static_cast(fSetStack.peek()); UnicodeSet SSet; SSet.addAll(RegexStaticSets::gStaticSets->fPropSets[URX_ISWORD_SET]).complement(); set->addAll(SSet); @@ -1716,7 +1716,7 @@ UBool RegexCompile::doParseActions(int32_t action) // the operator stack should be empty and the operand stack should have just // one entry, the result set. U_ASSERT(fSetOpStack.empty()); - UnicodeSet *theSet = (UnicodeSet *)fSetStack.pop(); + UnicodeSet* theSet = static_cast(fSetStack.pop()); U_ASSERT(fSetStack.empty()); compileSet(theSet); break; @@ -1735,7 +1735,7 @@ UBool RegexCompile::doParseActions(int32_t action) // as union-ing in a literal' { setEval(setUnion); - UnicodeSet *s = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* s = static_cast(fSetStack.peek()); s->add(fC.fChar); fLastSetLiteral = fC.fChar; break; @@ -1752,7 +1752,7 @@ UBool RegexCompile::doParseActions(int32_t action) error(U_REGEX_BAD_ESCAPE_SEQUENCE); } setEval(setUnion); - UnicodeSet *s = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* s = static_cast(fSetStack.peek()); s->add(fC.fChar); fLastSetLiteral = fC.fChar; break; @@ -1765,7 +1765,7 @@ UBool RegexCompile::doParseActions(int32_t action) { UChar32 c = scanNamedChar(); setEval(setUnion); - UnicodeSet *s = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* s = static_cast(fSetStack.peek()); s->add(c); fLastSetLiteral = c; break; @@ -1782,7 +1782,7 @@ UBool RegexCompile::doParseActions(int32_t action) if (U_SUCCESS(*fStatus) && (fLastSetLiteral == U_SENTINEL || fLastSetLiteral > c)) { error(U_REGEX_INVALID_RANGE); } - UnicodeSet *s = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* s = static_cast(fSetStack.peek()); s->add(fLastSetLiteral, c); fLastSetLiteral = c; break; @@ -1821,7 +1821,7 @@ UBool RegexCompile::doParseActions(int32_t action) { UnicodeSet *s = scanPosixProp(); if (s != nullptr) { - UnicodeSet *tos = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* tos = static_cast(fSetStack.peek()); tos->addAll(*s); delete s; } // else error. scanProp() reported the error status already. @@ -1833,7 +1833,7 @@ UBool RegexCompile::doParseActions(int32_t action) { UnicodeSet *s = scanProp(); if (s != nullptr) { - UnicodeSet *tos = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* tos = static_cast(fSetStack.peek()); tos->addAll(*s); delete s; } // else error. scanProp() reported the error status already. @@ -1852,7 +1852,7 @@ UBool RegexCompile::doParseActions(int32_t action) if (fLastSetLiteral == U_SENTINEL || fLastSetLiteral > fC.fChar) { error(U_REGEX_INVALID_RANGE); } - UnicodeSet *s = (UnicodeSet *)fSetStack.peek(); + UnicodeSet* s = static_cast(fSetStack.peek()); s->add(fLastSetLiteral, fC.fChar); break; } @@ -2026,7 +2026,7 @@ void RegexCompile::insertOp(int32_t where) { // were moved down by the insert. Fix them. int32_t loc; for (loc=0; locsize(); loc++) { - int32_t op = (int32_t)code->elementAti(loc); + int32_t op = static_cast(code->elementAti(loc)); int32_t opType = URX_TYPE(op); int32_t opValue = URX_VAL(op); if ((opType == URX_JMP || @@ -2152,7 +2152,7 @@ int32_t RegexCompile::blockTopLoc(UBool reserveLoc) { // No slot for STATE_SAVE was pre-reserved in the compiled code. // We need to make space now. theLoc = fRXPat->fCompiledPat->size()-1; - int32_t opAtTheLoc = (int32_t)fRXPat->fCompiledPat->elementAti(theLoc); + int32_t opAtTheLoc = static_cast(fRXPat->fCompiledPat->elementAti(theLoc)); if (URX_TYPE(opAtTheLoc) == URX_STRING_LEN) { // Strings take two opcode, we want the position of the first one. // We can have a string at this point if a single character case-folded to two. @@ -2202,7 +2202,7 @@ void RegexCompile::handleCloseParen() { break; } U_ASSERT(patIdx>0 && patIdx <= fRXPat->fCompiledPat->size()); - patOp = (int32_t)fRXPat->fCompiledPat->elementAti(patIdx); + patOp = static_cast(fRXPat->fCompiledPat->elementAti(patIdx)); U_ASSERT(URX_VAL(patOp) == 0); // Branch target for JMP should not be set. patOp |= fRXPat->fCompiledPat->size(); // Set it now. fRXPat->fCompiledPat->setElementAt(patOp, patIdx); @@ -2230,7 +2230,7 @@ void RegexCompile::handleCloseParen() { // The frame offset of the variables for this cg is obtained from the // start capture op and put it into the end-capture op. { - int32_t captureOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen+1); + int32_t captureOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen + 1)); U_ASSERT(URX_TYPE(captureOp) == URX_START_CAPTURE); int32_t frameVarLocation = URX_VAL(captureOp); @@ -2242,7 +2242,7 @@ void RegexCompile::handleCloseParen() { // Insert a LD_SP operation to restore the state stack to the position // it was when the atomic parens were entered. { - int32_t stoOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen+1); + int32_t stoOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen + 1)); U_ASSERT(URX_TYPE(stoOp) == URX_STO_SP); int32_t stoLoc = URX_VAL(stoOp); appendOp(URX_LD_SP, stoLoc); @@ -2251,7 +2251,7 @@ void RegexCompile::handleCloseParen() { case lookAhead: { - int32_t startOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen-5); + int32_t startOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen - 5)); U_ASSERT(URX_TYPE(startOp) == URX_LA_START); int32_t dataLoc = URX_VAL(startOp); appendOp(URX_LA_END, dataLoc); @@ -2261,7 +2261,7 @@ void RegexCompile::handleCloseParen() { case negLookAhead: { // See comment at doOpenLookAheadNeg - int32_t startOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen-1); + int32_t startOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen - 1)); U_ASSERT(URX_TYPE(startOp) == URX_LA_START); int32_t dataLoc = URX_VAL(startOp); appendOp(URX_LA_END, dataLoc); @@ -2270,7 +2270,7 @@ void RegexCompile::handleCloseParen() { // Patch the URX_SAVE near the top of the block. // The destination of the SAVE is the final LA_END that was just added. - int32_t saveOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen); + int32_t saveOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen)); U_ASSERT(URX_TYPE(saveOp) == URX_STATE_SAVE); int32_t dest = fRXPat->fCompiledPat->size()-1; saveOp = buildOp(URX_STATE_SAVE, dest); @@ -2283,7 +2283,7 @@ void RegexCompile::handleCloseParen() { // See comment at doOpenLookBehind. // Append the URX_LB_END and URX_LA_END to the compiled pattern. - int32_t startOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen-4); + int32_t startOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen - 4)); U_ASSERT(URX_TYPE(startOp) == URX_LB_START); int32_t dataLoc = URX_VAL(startOp); appendOp(URX_LB_END, dataLoc); @@ -2327,7 +2327,7 @@ void RegexCompile::handleCloseParen() { // See comment at doOpenLookBehindNeg. // Append the URX_LBN_END to the compiled pattern. - int32_t startOp = (int32_t)fRXPat->fCompiledPat->elementAti(fMatchOpenParen-5); + int32_t startOp = static_cast(fRXPat->fCompiledPat->elementAti(fMatchOpenParen - 5)); U_ASSERT(URX_TYPE(startOp) == URX_LB_START); int32_t dataLoc = URX_VAL(startOp); appendOp(URX_LBN_END, dataLoc); @@ -2535,7 +2535,7 @@ UBool RegexCompile::compileInlineInterval() { // Pick up the opcode that is to be repeated // - int32_t op = (int32_t)fRXPat->fCompiledPat->elementAti(topOfBlock); + int32_t op = static_cast(fRXPat->fCompiledPat->elementAti(topOfBlock)); // Compute the pattern location where the inline sequence // will end, and set up the state save op that will be needed. @@ -2718,7 +2718,7 @@ void RegexCompile::matchStartType() { } for (loc = 3; locfCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); opType = URX_TYPE(op); // The loop is advancing linearly through the pattern. @@ -2785,7 +2785,7 @@ void RegexCompile::matchStartType() { if (currentLen == 0) { int32_t sn = URX_VAL(op); U_ASSERT(sn > 0 && sn < fRXPat->fSets->size()); - const UnicodeSet *s = (UnicodeSet *)fRXPat->fSets->elementAt(sn); + const UnicodeSet* s = static_cast(fRXPat->fSets->elementAt(sn)); fRXPat->fInitialChars->addAll(*s); numInitialStrings += 2; } @@ -2799,7 +2799,7 @@ void RegexCompile::matchStartType() { if (currentLen == 0) { int32_t sn = URX_VAL(op); U_ASSERT(sn > 0 && sn < fRXPat->fSets->size()); - const UnicodeSet *s = (UnicodeSet *)fRXPat->fSets->elementAt(sn); + const UnicodeSet* s = static_cast(fRXPat->fSets->elementAt(sn)); fRXPat->fInitialChars->addAll(*s); numInitialStrings += 2; } @@ -2867,7 +2867,7 @@ void RegexCompile::matchStartType() { if (currentLen == 0) { UnicodeSet s; s.applyIntPropertyValue(UCHAR_GENERAL_CATEGORY_MASK, U_GC_ZS_MASK, *fStatus); - s.add((UChar32)9); // Tab + s.add(static_cast(9)); // Tab if (URX_VAL(op) != 0) { s.complement(); } @@ -2883,9 +2883,9 @@ void RegexCompile::matchStartType() { case URX_BACKSLASH_V: // Any line ending code point, with optional negation if (currentLen == 0) { UnicodeSet s; - s.add((UChar32)0x0a, (UChar32)0x0d); // add range - s.add((UChar32)0x85); - s.add((UChar32)0x2028, (UChar32)0x2029); + s.add(static_cast(0x0a), static_cast(0x0d)); // add range + s.add(static_cast(0x85)); + s.add(static_cast(0x2028), static_cast(0x2029)); if (URX_VAL(op) != 0) { // Complement option applies to URX_BACKSLASH_V only. s.complement(); @@ -2995,7 +2995,7 @@ void RegexCompile::matchStartType() { case URX_STRING: { loc++; - int32_t stringLenOp = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + int32_t stringLenOp = static_cast(fRXPat->fCompiledPat->elementAti(loc)); int32_t stringLen = URX_VAL(stringLenOp); U_ASSERT(URX_TYPE(stringLenOp) == URX_STRING_LEN); U_ASSERT(stringLenOp >= 2); @@ -3024,7 +3024,7 @@ void RegexCompile::matchStartType() { // attempt a string search for possible match positions. But we // do update the set of possible starting characters. loc++; - int32_t stringLenOp = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + int32_t stringLenOp = static_cast(fRXPat->fCompiledPat->elementAti(loc)); int32_t stringLen = URX_VAL(stringLenOp); U_ASSERT(URX_TYPE(stringLenOp) == URX_STRING_LEN); U_ASSERT(stringLenOp >= 2); @@ -3053,9 +3053,9 @@ void RegexCompile::matchStartType() { // move loc forwards to the end of the loop, skipping over the body. // If the min count is > 0, // continue normal processing of the body of the loop. - int32_t loopEndLoc = (int32_t)fRXPat->fCompiledPat->elementAti(loc+1); + int32_t loopEndLoc = static_cast(fRXPat->fCompiledPat->elementAti(loc + 1)); loopEndLoc = URX_VAL(loopEndLoc); - int32_t minLoopCount = (int32_t)fRXPat->fCompiledPat->elementAti(loc+2); + int32_t minLoopCount = static_cast(fRXPat->fCompiledPat->elementAti(loc + 2)); if (minLoopCount == 0) { // Min Loop Count of 0, treat like a forward branch and // move the current minimum length up to the target @@ -3097,7 +3097,7 @@ void RegexCompile::matchStartType() { int32_t depth = (opType == URX_LA_START? 2: 1); for (;;) { loc++; - op = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); if (URX_TYPE(op) == URX_LA_START) { depth+=2; } @@ -3177,7 +3177,7 @@ void RegexCompile::matchStartType() { fRXPat->fStartType = START_CHAR; fRXPat->fInitialChar = fRXPat->fInitialChars->charAt(0); U_ASSERT(fRXPat->fInitialChar != (UChar32)-1); - } else if (fRXPat->fInitialChars->contains((UChar32)0, (UChar32)0x10ffff) == false && + } else if (fRXPat->fInitialChars->contains(static_cast(0), static_cast(0x10ffff)) == false && fRXPat->fMinMatchLen > 0) { // Matches start with a set of character smaller than the set of all chars. fRXPat->fStartType = START_SET; @@ -3230,7 +3230,7 @@ int32_t RegexCompile::minMatchLength(int32_t start, int32_t end) { } for (loc = start; loc<=end; loc++) { - op = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); opType = URX_TYPE(op); // The loop is advancing linearly through the pattern. @@ -3342,7 +3342,7 @@ int32_t RegexCompile::minMatchLength(int32_t start, int32_t end) { case URX_STRING: { loc++; - int32_t stringLenOp = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + int32_t stringLenOp = static_cast(fRXPat->fCompiledPat->elementAti(loc)); currentLen = safeIncrement(currentLen, URX_VAL(stringLenOp)); } break; @@ -3368,9 +3368,9 @@ int32_t RegexCompile::minMatchLength(int32_t start, int32_t end) { // move loc forwards to the end of the loop, skipping over the body. // If the min count is > 0, // continue normal processing of the body of the loop. - int32_t loopEndLoc = (int32_t)fRXPat->fCompiledPat->elementAti(loc+1); + int32_t loopEndLoc = static_cast(fRXPat->fCompiledPat->elementAti(loc + 1)); loopEndLoc = URX_VAL(loopEndLoc); - int32_t minLoopCount = (int32_t)fRXPat->fCompiledPat->elementAti(loc+2); + int32_t minLoopCount = static_cast(fRXPat->fCompiledPat->elementAti(loc + 2)); if (minLoopCount == 0) { loc = loopEndLoc; } else { @@ -3405,7 +3405,7 @@ int32_t RegexCompile::minMatchLength(int32_t start, int32_t end) { int32_t depth = (opType == URX_LA_START? 2: 1); for (;;) { loc++; - op = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); if (URX_TYPE(op) == URX_LA_START) { // The boilerplate for look-ahead includes two LA_END instructions, // Depth will be decremented by each one when it is seen. @@ -3499,7 +3499,7 @@ int32_t RegexCompile::maxMatchLength(int32_t start, int32_t end) { } for (loc = start; loc<=end; loc++) { - op = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); opType = URX_TYPE(op); // The loop is advancing linearly through the pattern. @@ -3628,7 +3628,7 @@ int32_t RegexCompile::maxMatchLength(int32_t start, int32_t end) { case URX_STRING: { loc++; - int32_t stringLenOp = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + int32_t stringLenOp = static_cast(fRXPat->fCompiledPat->elementAti(loc)); currentLen = safeIncrement(currentLen, URX_VAL(stringLenOp)); break; } @@ -3656,7 +3656,7 @@ int32_t RegexCompile::maxMatchLength(int32_t start, int32_t end) { // { loc++; - int32_t stringLenOp = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + int32_t stringLenOp = static_cast(fRXPat->fCompiledPat->elementAti(loc)); currentLen = safeIncrement(currentLen, URX_VAL(stringLenOp)); } break; @@ -3683,12 +3683,12 @@ int32_t RegexCompile::maxMatchLength(int32_t start, int32_t end) { U_ASSERT(loopEndLoc >= loc+4); int64_t blockLen = maxMatchLength(loc+4, loopEndLoc-1); // Recursive call. - int64_t updatedLen = (int64_t)currentLen + blockLen * maxLoopCount; + int64_t updatedLen = static_cast(currentLen) + blockLen * maxLoopCount; if (updatedLen >= INT32_MAX) { currentLen = INT32_MAX; break; } - currentLen = (int32_t)updatedLen; + currentLen = static_cast(updatedLen); loc = loopEndLoc; break; } @@ -3725,7 +3725,7 @@ int32_t RegexCompile::maxMatchLength(int32_t start, int32_t end) { // without processing the look-behind block. int32_t dataLoc = URX_VAL(op); for (loc = loc + 1; loc <= end; ++loc) { - op = (int32_t)fRXPat->fCompiledPat->elementAti(loc); + op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); int32_t opType = URX_TYPE(op); if ((opType == URX_LA_END || opType == URX_LBN_END) && (URX_VAL(op) == dataLoc)) { break; @@ -3779,7 +3779,7 @@ void RegexCompile::stripNOPs() { int32_t d = 0; for (loc=0; locfCompiledPat->elementAti(loc); + int32_t op = static_cast(fRXPat->fCompiledPat->elementAti(loc)); if (URX_TYPE(op) == URX_NOP) { d++; } @@ -3794,7 +3794,7 @@ void RegexCompile::stripNOPs() { int32_t src; int32_t dst = 0; for (src=0; srcfCompiledPat->elementAti(src); + int32_t op = static_cast(fRXPat->fCompiledPat->elementAti(src)); int32_t opType = URX_TYPE(op); switch (opType) { case URX_NOP: @@ -3918,11 +3918,11 @@ void RegexCompile::error(UErrorCode e) { fParseErr->line = 0; fParseErr->offset = -1; } else if (fCharNum > 0x7FFFFFFF) { - fParseErr->line = (int32_t)fLineNum; + fParseErr->line = static_cast(fLineNum); fParseErr->offset = -1; } else { - fParseErr->line = (int32_t)fLineNum; - fParseErr->offset = (int32_t)fCharNum; + fParseErr->line = static_cast(fLineNum); + fParseErr->offset = static_cast(fCharNum); } UErrorCode status = U_ZERO_ERROR; // throwaway status for extracting context @@ -4034,8 +4034,8 @@ void RegexCompile::nextChar(RegexPatternChar &c) { if (fQuoteMode) { c.fQuoted = true; - if ((c.fChar==chBackSlash && peekCharLL()==chE && ((fModeFlags & UREGEX_LITERAL) == 0)) || - c.fChar == (UChar32)-1) { + if ((c.fChar == chBackSlash && peekCharLL() == chE && ((fModeFlags & UREGEX_LITERAL) == 0)) || + c.fChar == static_cast(-1)) { fQuoteMode = false; // Exit quote mode, nextCharLL(); // discard the E // nextChar(c); // recurse to get the real next char @@ -4060,14 +4060,14 @@ void RegexCompile::nextChar(RegexPatternChar &c) { // Scan through any white space and comments, until we // reach a significant character or the end of input. for (;;) { - if (c.fChar == (UChar32)-1) { + if (c.fChar == static_cast(-1)) { break; // End of Input } if (c.fChar == chPound && fEOLComments) { // Start of a comment. Consume the rest of it, until EOF or a new line for (;;) { c.fChar = nextCharLL(); - if (c.fChar == (UChar32)-1 || // EOF + if (c.fChar == static_cast(-1) || // EOF c.fChar == chCR || c.fChar == chLF || c.fChar == chNEL || @@ -4099,8 +4099,8 @@ void RegexCompile::nextChar(RegexPatternChar &c) { c.fQuoted = true; if (UTEXT_FULL_TEXT_IN_CHUNK(fRXPat->fPattern, fPatternLength)) { - int32_t endIndex = (int32_t)pos; - c.fChar = u_unescapeAt(uregex_ucstr_unescape_charAt, &endIndex, (int32_t)fPatternLength, (void *)fRXPat->fPattern->chunkContents); + int32_t endIndex = static_cast(pos); + c.fChar = u_unescapeAt(uregex_ucstr_unescape_charAt, &endIndex, static_cast(fPatternLength), const_cast(fRXPat->fPattern->chunkContents)); if (endIndex == pos) { error(U_REGEX_BAD_ESCAPE_SEQUENCE); @@ -4220,7 +4220,7 @@ UChar32 RegexCompile::scanNamedChar() { char name[100]; if (!uprv_isInvariantUString(charName.getBuffer(), charName.length()) || - (uint32_t)charName.length()>=sizeof(name)) { + static_cast(charName.length()) >= sizeof(name)) { // All Unicode character names have only invariant characters. // The API to get a character, given a name, accepts only char *, forcing us to convert, // which requires this error check @@ -4618,7 +4618,7 @@ void RegexCompile::setEval(int32_t nextOp) { } fSetOpStack.popi(); U_ASSERT(fSetStack.empty() == false); - rightOperand = (UnicodeSet *)fSetStack.peek(); + rightOperand = static_cast(fSetStack.peek()); // ICU 70 adds emoji properties of strings, but createSetForProperty() removes all strings // (see comments there). // We also do not yet support string literals in character classes, @@ -4638,20 +4638,20 @@ void RegexCompile::setEval(int32_t nextOp) { case setDifference1: case setDifference2: fSetStack.pop(); - leftOperand = (UnicodeSet *)fSetStack.peek(); + leftOperand = static_cast(fSetStack.peek()); leftOperand->removeAll(*rightOperand); delete rightOperand; break; case setIntersection1: case setIntersection2: fSetStack.pop(); - leftOperand = (UnicodeSet *)fSetStack.peek(); + leftOperand = static_cast(fSetStack.peek()); leftOperand->retainAll(*rightOperand); delete rightOperand; break; case setUnion: fSetStack.pop(); - leftOperand = (UnicodeSet *)fSetStack.peek(); + leftOperand = static_cast(fSetStack.peek()); leftOperand->addAll(*rightOperand); delete rightOperand; break; diff --git a/icu4c/source/i18n/regeximp.cpp b/icu4c/source/i18n/regeximp.cpp index 86e238c0f715..59dba630482a 100644 --- a/icu4c/source/i18n/regeximp.cpp +++ b/icu4c/source/i18n/regeximp.cpp @@ -41,7 +41,7 @@ UChar32 CaseFoldingUTextIterator::next() { if (fFoldLength < 0) { fFoldLength = ~fFoldLength; } - foldedC = (UChar32)fFoldLength; + foldedC = static_cast(fFoldLength); fFoldChars = nullptr; return foldedC; } @@ -89,7 +89,7 @@ UChar32 CaseFoldingUCharIterator::next() { if (fFoldLength < 0) { fFoldLength = ~fFoldLength; } - foldedC = (UChar32)fFoldLength; + foldedC = static_cast(fFoldLength); fFoldChars = nullptr; return foldedC; } diff --git a/icu4c/source/i18n/region.cpp b/icu4c/source/i18n/region.cpp index 839a252e120a..ad5bdbe0115d 100644 --- a/icu4c/source/i18n/region.cpp +++ b/icu4c/source/i18n/region.cpp @@ -172,7 +172,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { if ( U_FAILURE(status) ) { return; } - UnicodeString *regionName = (UnicodeString *)allRegions->elementAt(i); + UnicodeString* regionName = static_cast(allRegions->elementAt(i)); r->idStr = *regionName; r->idStr.extract(0,r->idStr.length(),r->id,sizeof(r->id),US_INV); @@ -203,7 +203,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { if (U_FAILURE(status)) { break; } - Region *grouping = (Region *) uhash_get(newRegionIDMap.getAlias(), groupingName); + Region* grouping = static_cast(uhash_get(newRegionIDMap.getAlias(), groupingName)); if (grouping != nullptr) { for (int32_t i = 0; i < ures_getSize(groupingBundle) && U_SUCCESS(status); i++) { UnicodeString child = ures_getUnicodeStringByIndex(groupingBundle, i, &status); @@ -232,8 +232,8 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { UnicodeString aliasTo = ures_getUnicodeStringByKey(res.getAlias(),"replacement",&status); res.adoptInstead(nullptr); - const Region *aliasToRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),&aliasTo); - Region *aliasFromRegion = (Region *)uhash_get(newRegionIDMap.getAlias(),aliasFromStr.getAlias()); + const Region* aliasToRegion = static_cast(uhash_get(newRegionIDMap.getAlias(), &aliasTo)); + Region* aliasFromRegion = static_cast(uhash_get(newRegionIDMap.getAlias(), aliasFromStr.getAlias())); if ( aliasToRegion != nullptr && aliasFromRegion == nullptr ) { // This is just an alias from some string to a region uhash_put(newRegionAliases.getAlias(),(void *)aliasFromStr.orphan(), (void *)aliasToRegion,&status); @@ -275,7 +275,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { currentRegion.append(aliasTo.charAt(i)); } if ( aliasTo.charAt(i) == 0x0020 || i+1 == aliasTo.length() ) { - Region *target = (Region *)uhash_get(newRegionIDMap.getAlias(),(void *)¤tRegion); + Region* target = static_cast(uhash_get(newRegionIDMap.getAlias(), ¤tRegion)); if (target) { LocalPointer preferredValue(new UnicodeString(target->idStr), status); aliasFromRegion->preferredValues->adoptElement(preferredValue.orphan(),status); // may add null if err @@ -294,7 +294,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { UnicodeString codeMappingNumber = ures_getUnicodeStringByIndex(mapping,1,&status); UnicodeString codeMapping3Letter = ures_getUnicodeStringByIndex(mapping,2,&status); - Region *r = (Region *)uhash_get(newRegionIDMap.getAlias(),(void *)&codeMappingID); + Region* r = static_cast(uhash_get(newRegionIDMap.getAlias(), &codeMappingID)); if ( r ) { int32_t pos = 0; int32_t result = ICU_Utility::parseAsciiInteger(codeMappingNumber, pos); @@ -312,26 +312,26 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { // Now fill in the special cases for WORLD, UNKNOWN, CONTINENTS, and GROUPINGS Region *r; UnicodeString WORLD_ID_STRING(WORLD_ID); - r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&WORLD_ID_STRING); + r = static_cast(uhash_get(newRegionIDMap.getAlias(), &WORLD_ID_STRING)); if ( r ) { r->fType = URGN_WORLD; } UnicodeString UNKNOWN_REGION_ID_STRING(UNKNOWN_REGION_ID); - r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&UNKNOWN_REGION_ID_STRING); + r = static_cast(uhash_get(newRegionIDMap.getAlias(), &UNKNOWN_REGION_ID_STRING)); if ( r ) { r->fType = URGN_UNKNOWN; } for ( int32_t i = 0 ; i < continents->size() ; i++ ) { - r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)continents->elementAt(i)); + r = static_cast(uhash_get(newRegionIDMap.getAlias(), continents->elementAt(i))); if ( r ) { r->fType = URGN_CONTINENT; } } for ( int32_t i = 0 ; i < groupings->size() ; i++ ) { - r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)groupings->elementAt(i)); + r = static_cast(uhash_get(newRegionIDMap.getAlias(), groupings->elementAt(i))); if ( r ) { r->fType = URGN_GROUPING; } @@ -341,7 +341,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { // even though it looks like a territory code. Need to handle it here. UnicodeString OUTLYING_OCEANIA_REGION_ID_STRING(OUTLYING_OCEANIA_REGION_ID); - r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&OUTLYING_OCEANIA_REGION_ID_STRING); + r = static_cast(uhash_get(newRegionIDMap.getAlias(), &OUTLYING_OCEANIA_REGION_ID_STRING)); if ( r ) { r->fType = URGN_SUBCONTINENT; } @@ -358,11 +358,11 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { // #11232 is to do something useful with these. } UnicodeString parentStr = UnicodeString(parent, -1 , US_INV); - Region *parentRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&parentStr); + Region* parentRegion = static_cast(uhash_get(newRegionIDMap.getAlias(), &parentStr)); for ( int j = 0 ; j < ures_getSize(mapping.getAlias()); j++ ) { UnicodeString child = ures_getUnicodeStringByIndex(mapping.getAlias(),j,&status); - Region *childRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&child); + Region* childRegion = static_cast(uhash_get(newRegionIDMap.getAlias(), &child)); if ( parentRegion != nullptr && childRegion != nullptr ) { // Add the child region to the set of regions contained by the parent @@ -398,7 +398,7 @@ void U_CALLCONV Region::loadRegionData(UErrorCode &status) { // Create the availableRegions lists int32_t pos = UHASH_FIRST; while ( const UHashElement* element = uhash_nextElement(newRegionIDMap.getAlias(),&pos)) { - Region *ar = (Region *)element->value.pointer; + Region* ar = static_cast(element->value.pointer); if ( availableRegions[ar->fType] == nullptr ) { LocalPointer newAr(new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status), status); availableRegions[ar->fType] = newAr.orphan(); @@ -497,10 +497,10 @@ Region::getInstance(const char *region_code, UErrorCode &status) { } UnicodeString regionCodeString = UnicodeString(region_code, -1, US_INV); - Region *r = (Region *)uhash_get(regionIDMap,(void *)®ionCodeString); + Region* r = static_cast(uhash_get(regionIDMap, ®ionCodeString)); if ( !r ) { - r = (Region *)uhash_get(regionAliases,(void *)®ionCodeString); + r = static_cast(uhash_get(regionAliases, ®ionCodeString)); } if ( !r ) { // Unknown region code @@ -512,7 +512,7 @@ Region::getInstance(const char *region_code, UErrorCode &status) { StringEnumeration *pv = r->getPreferredValues(status); pv->reset(status); const UnicodeString *ustr = pv->snext(status); - r = (Region *)uhash_get(regionIDMap,(void *)ustr); + r = static_cast(uhash_get(regionIDMap, ustr)); delete pv; } @@ -532,12 +532,12 @@ Region::getInstance (int32_t code, UErrorCode &status) { return nullptr; } - Region *r = (Region *)uhash_iget(numericCodeMap,code); + Region* r = static_cast(uhash_iget(numericCodeMap, code)); if ( !r ) { // Just in case there's an alias that's numeric, try to find it. UnicodeString id; ICU_Utility::appendNumber(id, code, 10, 1); - r = (Region *)uhash_get(regionAliases,&id); + r = static_cast(uhash_get(regionAliases, &id)); } if( U_FAILURE(status) ) { @@ -553,7 +553,7 @@ Region::getInstance (int32_t code, UErrorCode &status) { StringEnumeration *pv = r->getPreferredValues(status); pv->reset(status); const UnicodeString *ustr = pv->snext(status); - r = (Region *)uhash_get(regionIDMap,(void *)ustr); + r = static_cast(uhash_get(regionIDMap, ustr)); delete pv; } @@ -670,8 +670,8 @@ Region::contains(const Region &other) const { return true; } else { for ( int32_t i = 0 ; i < containedRegions->size() ; i++ ) { - UnicodeString *crStr = (UnicodeString *)containedRegions->elementAt(i); - Region *cr = (Region *) uhash_get(regionIDMap,(void *)crStr); + UnicodeString* crStr = static_cast(containedRegions->elementAt(i)); + Region* cr = static_cast(uhash_get(regionIDMap, crStr)); if ( cr && cr->contains(other) ) { return true; } @@ -725,7 +725,7 @@ RegionNameEnumeration::RegionNameEnumeration(UVector *nameList, UErrorCode& stat LocalPointer regionNames( new UVector(uprv_deleteUObject, uhash_compareUnicodeString, nameList->size(), status), status); for ( int32_t i = 0 ; U_SUCCESS(status) && i < nameList->size() ; i++ ) { - UnicodeString* this_region_name = (UnicodeString *)nameList->elementAt(i); + UnicodeString* this_region_name = static_cast(nameList->elementAt(i)); LocalPointer new_region_name(new UnicodeString(*this_region_name), status); regionNames->adoptElement(new_region_name.orphan(), status); } @@ -740,7 +740,7 @@ RegionNameEnumeration::snext(UErrorCode& status) { if (U_FAILURE(status) || (fRegionNames==nullptr)) { return nullptr; } - const UnicodeString* nextStr = (const UnicodeString *)fRegionNames->elementAt(pos); + const UnicodeString* nextStr = static_cast(fRegionNames->elementAt(pos)); if (nextStr!=nullptr) { pos++; } diff --git a/icu4c/source/i18n/reldatefmt.cpp b/icu4c/source/i18n/reldatefmt.cpp index c3c450f376c2..ced477ac5de5 100644 --- a/icu4c/source/i18n/reldatefmt.cpp +++ b/icu4c/source/i18n/reldatefmt.cpp @@ -1161,7 +1161,8 @@ void RelativeDateTimeFormatter::formatRelativeImpl( if (offset > -2.1 && offset < 2.1) { // Allow a 1% epsilon, so offsets in -1.01..-0.99 map to LAST double offsetx100 = offset * 100.0; - int32_t intoffset = (offsetx100 < 0)? (int32_t)(offsetx100-0.5) : (int32_t)(offsetx100+0.5); + int32_t intoffset = offsetx100 < 0 ? static_cast(offsetx100 - 0.5) + : static_cast(offsetx100 + 0.5); switch (intoffset) { case -200/*-2*/: direction = UDAT_DIRECTION_LAST_2; break; case -100/*-1*/: direction = UDAT_DIRECTION_LAST; break; diff --git a/icu4c/source/i18n/reldtfmt.cpp b/icu4c/source/i18n/reldtfmt.cpp index 7015c1308998..2725cc15e9a7 100644 --- a/icu4c/source/i18n/reldtfmt.cpp +++ b/icu4c/source/i18n/reldtfmt.cpp @@ -57,7 +57,7 @@ RelativeDateFormat::RelativeDateFormat(const RelativeDateFormat& other) : fCombinedFormat = new SimpleFormatter(*other.fCombinedFormat); } if (fDatesLen > 0) { - fDates = (URelativeString*) uprv_malloc(sizeof(fDates[0])*(size_t)fDatesLen); + fDates = static_cast(uprv_malloc(sizeof(fDates[0]) * static_cast(fDatesLen))); uprv_memcpy(fDates, other.fDates, sizeof(fDates[0])*(size_t)fDatesLen); } #if !UCONFIG_NO_BREAK_ITERATION @@ -92,12 +92,12 @@ RelativeDateFormat::RelativeDateFormat( UDateFormatStyle timeStyle, UDateFormatS status = U_ILLEGAL_ARGUMENT_ERROR; return; } - UDateFormatStyle baseDateStyle = (dateStyle > UDAT_SHORT)? (UDateFormatStyle)(dateStyle & ~UDAT_RELATIVE): dateStyle; + UDateFormatStyle baseDateStyle = (dateStyle > UDAT_SHORT) ? static_cast(dateStyle & ~UDAT_RELATIVE) : dateStyle; DateFormat * df; // Get fDateTimeFormatter from either date or time style (does not matter, we will override the pattern). // We do need to get separate patterns for the date & time styles. if (baseDateStyle != UDAT_NONE) { - df = createDateInstance((EStyle)baseDateStyle, locale); + df = createDateInstance(static_cast(baseDateStyle), locale); fDateTimeFormatter=dynamic_cast(df); if (fDateTimeFormatter == nullptr) { status = U_UNSUPPORTED_ERROR; @@ -105,7 +105,7 @@ RelativeDateFormat::RelativeDateFormat( UDateFormatStyle timeStyle, UDateFormatS } fDateTimeFormatter->toPattern(fDatePattern); if (timeStyle != UDAT_NONE) { - df = createTimeInstance((EStyle)timeStyle, locale); + df = createTimeInstance(static_cast(timeStyle), locale); SimpleDateFormat *sdf = dynamic_cast(df); if (sdf != nullptr) { sdf->toPattern(fTimePattern); @@ -114,7 +114,7 @@ RelativeDateFormat::RelativeDateFormat( UDateFormatStyle timeStyle, UDateFormatS } } else { // does not matter whether timeStyle is UDAT_NONE, we need something for fDateTimeFormatter - df = createTimeInstance((EStyle)timeStyle, locale); + df = createTimeInstance(static_cast(timeStyle), locale); fDateTimeFormatter=dynamic_cast(df); if (fDateTimeFormatter == nullptr) { status = U_UNSUPPORTED_ERROR; @@ -157,7 +157,7 @@ bool RelativeDateFormat::operator==(const Format& other) const { return false; } -static const char16_t APOSTROPHE = (char16_t)0x0027; +static const char16_t APOSTROPHE = static_cast(0x0027); UnicodeString& RelativeDateFormat::format( Calendar& cal, UnicodeString& appendTo, @@ -536,8 +536,8 @@ void RelativeDateFormat::loadDates(UErrorCode &status) { int32_t glueIndex = kDateTime; if (patternsSize >= (kDateTimeOffset + kShort + 1)) { int32_t offsetIncrement = (fDateStyle & ~kRelative); // Remove relative bit. - if (offsetIncrement >= (int32_t)kFull && - offsetIncrement <= (int32_t)kShortRelative) { + if (offsetIncrement >= static_cast(kFull) && + offsetIncrement <= static_cast(kShortRelative)) { glueIndex = kDateTimeOffset + offsetIncrement; } } @@ -552,7 +552,7 @@ void RelativeDateFormat::loadDates(UErrorCode &status) { // Data loading for relative names, e.g., "yesterday", "today", "tomorrow". fDatesLen = UDAT_DIRECTION_COUNT; // Maximum defined by data. - fDates = (URelativeString*) uprv_malloc(sizeof(fDates[0])*fDatesLen); + fDates = static_cast(uprv_malloc(sizeof(fDates[0]) * fDatesLen)); RelDateFmtDataSink sink(fDates, fDatesLen); ures_getAllItemsWithFallback(rb, "fields/day/relative", sink, status); diff --git a/icu4c/source/i18n/rematch.cpp b/icu4c/source/i18n/rematch.cpp index c76f0c55bcbe..7864dffa4631 100644 --- a/icu4c/source/i18n/rematch.cpp +++ b/icu4c/source/i18n/rematch.cpp @@ -242,7 +242,7 @@ void RegexMatcher::init2(UText *input, UErrorCode &status) { } if (fPattern->fDataSize > UPRV_LENGTHOF(fSmallData)) { - fData = (int64_t *)uprv_malloc(fPattern->fDataSize * sizeof(int64_t)); + fData = static_cast(uprv_malloc(fPattern->fDataSize * sizeof(int64_t))); if (fData == nullptr) { status = fDeferredStatus = U_MEMORY_ALLOCATION_ERROR; return; @@ -317,16 +317,16 @@ RegexMatcher &RegexMatcher::appendReplacement(UText *dest, if (fMatchStart > fAppendPosition) { if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { destLen += utext_replace(dest, destLen, destLen, fInputText->chunkContents+fAppendPosition, - (int32_t)(fMatchStart-fAppendPosition), &status); + static_cast(fMatchStart - fAppendPosition), &status); } else { int32_t len16; if (UTEXT_USES_U16(fInputText)) { - len16 = (int32_t)(fMatchStart-fAppendPosition); + len16 = static_cast(fMatchStart - fAppendPosition); } else { UErrorCode lengthStatus = U_ZERO_ERROR; len16 = utext_extract(fInputText, fAppendPosition, fMatchStart, nullptr, 0, &lengthStatus); } - char16_t *inputChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(len16+1)); + char16_t* inputChars = static_cast(uprv_malloc(sizeof(char16_t) * (len16 + 1))); if (inputChars == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return *this; @@ -360,9 +360,9 @@ RegexMatcher &RegexMatcher::appendReplacement(UText *dest, int32_t offset = 0; struct URegexUTextUnescapeCharContext context = U_REGEX_UTEXT_UNESCAPE_CONTEXT(replacement); UChar32 escapedChar = u_unescapeAt(uregex_utext_unescape_charAt, &offset, INT32_MAX, &context); - if (escapedChar != (UChar32)0xFFFFFFFF) { + if (escapedChar != static_cast(0xFFFFFFFF)) { if (U_IS_BMP(escapedChar)) { - char16_t c16 = (char16_t)escapedChar; + char16_t c16 = static_cast(escapedChar); destLen += utext_replace(dest, destLen, destLen, &c16, 1, &status); } else { char16_t surrogate[2]; @@ -384,7 +384,7 @@ RegexMatcher &RegexMatcher::appendReplacement(UText *dest, (void)UTEXT_NEXT32(replacement); // Plain backslash escape. Just put out the escaped character. if (U_IS_BMP(c)) { - char16_t c16 = (char16_t)c; + char16_t c16 = static_cast(c); destLen += utext_replace(dest, destLen, destLen, &c16, 1, &status); } else { char16_t surrogate[2]; @@ -398,7 +398,7 @@ RegexMatcher &RegexMatcher::appendReplacement(UText *dest, } else if (c != DOLLARSIGN) { // Normal char, not a $. Copy it out without further checks. if (U_IS_BMP(c)) { - char16_t c16 = (char16_t)c; + char16_t c16 = static_cast(c); destLen += utext_replace(dest, destLen, destLen, &c16, 1, &status); } else { char16_t surrogate[2]; @@ -516,17 +516,17 @@ UText *RegexMatcher::appendTail(UText *dest, UErrorCode &status) { if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { int64_t destLen = utext_nativeLength(dest); utext_replace(dest, destLen, destLen, fInputText->chunkContents+fAppendPosition, - (int32_t)(fInputLength-fAppendPosition), &status); + static_cast(fInputLength - fAppendPosition), &status); } else { int32_t len16; if (UTEXT_USES_U16(fInputText)) { - len16 = (int32_t)(fInputLength-fAppendPosition); + len16 = static_cast(fInputLength - fAppendPosition); } else { len16 = utext_extract(fInputText, fAppendPosition, fInputLength, nullptr, 0, &status); status = U_ZERO_ERROR; // buffer overflow } - char16_t *inputChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(len16)); + char16_t* inputChars = static_cast(uprv_malloc(sizeof(char16_t) * (len16))); if (inputChars == nullptr) { fDeferredStatus = U_MEMORY_ALLOCATION_ERROR; } else { @@ -583,7 +583,7 @@ int64_t RegexMatcher::end64(int32_t group, UErrorCode &err) const { } int32_t RegexMatcher::end(int32_t group, UErrorCode &err) const { - return (int32_t)end64(group, err); + return static_cast(end64(group, err)); } //-------------------------------------------------------------------------------- @@ -926,9 +926,9 @@ UBool RegexMatcher::findUsingChunk(UErrorCode &status) { // matcher has been reset. // - int32_t startPos = (int32_t)fMatchEnd; + int32_t startPos = static_cast(fMatchEnd); if (startPos==0) { - startPos = (int32_t)fActiveStart; + startPos = static_cast(fActiveStart); } const char16_t *inputBuf = fInputText->chunkContents; @@ -963,7 +963,7 @@ UBool RegexMatcher::findUsingChunk(UErrorCode &status) { // Note: some patterns that cannot match anything will have fMinMatchLength==Max Int. // Be aware of possible overflows if making changes here. // Note: a match can begin at inputBuf + testLen; it is an inclusive limit. - int32_t testLen = (int32_t)(fActiveLimit - fPattern->fMinMatchLen); + int32_t testLen = static_cast(fActiveLimit - fPattern->fMinMatchLen); if (startPos > testLen) { fMatch = false; fHitEnd = true; @@ -1283,16 +1283,16 @@ int64_t RegexMatcher::appendGroup(int32_t groupNum, UText *dest, UErrorCode &sta int64_t deltaLen; if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { U_ASSERT(e <= fInputLength); - deltaLen = utext_replace(dest, destLen, destLen, fInputText->chunkContents+s, (int32_t)(e-s), &status); + deltaLen = utext_replace(dest, destLen, destLen, fInputText->chunkContents + s, static_cast(e - s), &status); } else { int32_t len16; if (UTEXT_USES_U16(fInputText)) { - len16 = (int32_t)(e-s); + len16 = static_cast(e - s); } else { UErrorCode lengthStatus = U_ZERO_ERROR; len16 = utext_extract(fInputText, s, e, nullptr, 0, &lengthStatus); } - char16_t *groupChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(len16+1)); + char16_t* groupChars = static_cast(uprv_malloc(sizeof(char16_t) * (len16 + 1))); if (groupChars == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return 0; @@ -1357,7 +1357,7 @@ const UnicodeString &RegexMatcher::input() const { UErrorCode status = U_ZERO_ERROR; int32_t len16; if (UTEXT_USES_U16(fInputText)) { - len16 = (int32_t)fInputLength; + len16 = static_cast(fInputLength); } else { len16 = utext_extract(fInputText, 0, fInputLength, nullptr, 0, &status); status = U_ZERO_ERROR; // overflow, length status @@ -1368,7 +1368,7 @@ const UnicodeString &RegexMatcher::input() const { utext_extract(fInputText, 0, fInputLength, inputChars, len16, &status); // unterminated warning result->releaseBuffer(len16); - (*(const UnicodeString **)&fInput) = result; // pointer assignment, rather than operator= + *const_cast(&fInput) = result; // pointer assignment, rather than operator= } return *fInput; @@ -1400,16 +1400,16 @@ UText *RegexMatcher::getInput (UText *dest, UErrorCode &status) const { if (dest) { if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { - utext_replace(dest, 0, utext_nativeLength(dest), fInputText->chunkContents, (int32_t)fInputLength, &status); + utext_replace(dest, 0, utext_nativeLength(dest), fInputText->chunkContents, static_cast(fInputLength), &status); } else { int32_t input16Len; if (UTEXT_USES_U16(fInputText)) { - input16Len = (int32_t)fInputLength; + input16Len = static_cast(fInputLength); } else { UErrorCode lengthStatus = U_ZERO_ERROR; input16Len = utext_extract(fInputText, 0, fInputLength, nullptr, 0, &lengthStatus); // buffer overflow error } - char16_t *inputChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(input16Len)); + char16_t* inputChars = static_cast(uprv_malloc(sizeof(char16_t) * (input16Len))); if (inputChars == nullptr) { return dest; } @@ -1478,7 +1478,7 @@ UBool RegexMatcher::lookingAt(UErrorCode &status) { resetPreserveRegion(); } if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { - MatchChunkAt((int32_t)fActiveStart, false, status); + MatchChunkAt(static_cast(fActiveStart), false, status); } else { MatchAt(fActiveStart, false, status); } @@ -1516,7 +1516,7 @@ UBool RegexMatcher::lookingAt(int64_t start, UErrorCode &status) { } if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { - MatchChunkAt((int32_t)nativeStart, false, status); + MatchChunkAt(static_cast(nativeStart), false, status); } else { MatchAt(nativeStart, false, status); } @@ -1550,7 +1550,7 @@ UBool RegexMatcher::matches(UErrorCode &status) { } if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { - MatchChunkAt((int32_t)fActiveStart, true, status); + MatchChunkAt(static_cast(fActiveStart), true, status); } else { MatchAt(fActiveStart, true, status); } @@ -1588,7 +1588,7 @@ UBool RegexMatcher::matches(int64_t start, UErrorCode &status) { } if (UTEXT_FULL_TEXT_IN_CHUNK(fInputText, fInputLength)) { - MatchChunkAt((int32_t)nativeStart, true, status); + MatchChunkAt(static_cast(nativeStart), true, status); } else { MatchAt(nativeStart, true, status); } @@ -1666,7 +1666,7 @@ RegexMatcher &RegexMatcher::region(int64_t start, int64_t limit, UErrorCode &sta // //-------------------------------------------------------------------------------- int32_t RegexMatcher::regionEnd() const { - return (int32_t)fRegionLimit; + return static_cast(fRegionLimit); } int64_t RegexMatcher::regionEnd64() const { @@ -1679,7 +1679,7 @@ int64_t RegexMatcher::regionEnd64() const { // //-------------------------------------------------------------------------------- int32_t RegexMatcher::regionStart() const { - return (int32_t)fRegionStart; + return static_cast(fRegionStart); } int64_t RegexMatcher::regionStart64() const { @@ -2050,7 +2050,7 @@ int32_t RegexMatcher::split(const UnicodeString &input, return 0; } - UText **destText = (UText **)uprv_malloc(sizeof(UText*)*destCapacity); + UText** destText = static_cast(uprv_malloc(sizeof(UText*) * destCapacity)); if (destText == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return 0; @@ -2119,7 +2119,7 @@ int32_t RegexMatcher::split(UText *input, if (dest[i]) { utext_replace(dest[i], 0, utext_nativeLength(dest[i]), input->chunkContents+nextOutputStringStart, - (int32_t)(fActiveLimit-nextOutputStringStart), &status); + static_cast(fActiveLimit - nextOutputStringStart), &status); } else { UText remainingText = UTEXT_INITIALIZER; utext_openUChars(&remainingText, input->chunkContents+nextOutputStringStart, @@ -2131,7 +2131,7 @@ int32_t RegexMatcher::split(UText *input, UErrorCode lengthStatus = U_ZERO_ERROR; int32_t remaining16Length = utext_extract(input, nextOutputStringStart, fActiveLimit, nullptr, 0, &lengthStatus); - char16_t *remainingChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(remaining16Length+1)); + char16_t* remainingChars = static_cast(uprv_malloc(sizeof(char16_t) * (remaining16Length + 1))); if (remainingChars == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; break; @@ -2159,7 +2159,7 @@ int32_t RegexMatcher::split(UText *input, if (dest[i]) { utext_replace(dest[i], 0, utext_nativeLength(dest[i]), input->chunkContents+nextOutputStringStart, - (int32_t)(fMatchStart-nextOutputStringStart), &status); + static_cast(fMatchStart - nextOutputStringStart), &status); } else { UText remainingText = UTEXT_INITIALIZER; utext_openUChars(&remainingText, input->chunkContents+nextOutputStringStart, @@ -2170,7 +2170,7 @@ int32_t RegexMatcher::split(UText *input, } else { UErrorCode lengthStatus = U_ZERO_ERROR; int32_t remaining16Length = utext_extract(input, nextOutputStringStart, fMatchStart, nullptr, 0, &lengthStatus); - char16_t *remainingChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(remaining16Length+1)); + char16_t* remainingChars = static_cast(uprv_malloc(sizeof(char16_t) * (remaining16Length + 1))); if (remainingChars == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; break; @@ -2213,7 +2213,7 @@ int32_t RegexMatcher::split(UText *input, if (dest[i] == nullptr) { dest[i] = utext_openUChars(nullptr, nullptr, 0, &status); } else { - static const char16_t emptyString[] = {(char16_t)0}; + static const char16_t emptyString[] = {static_cast(0)}; utext_replace(dest[i], 0, utext_nativeLength(dest[i]), emptyString, 0, &status); } } @@ -2229,7 +2229,7 @@ int32_t RegexMatcher::split(UText *input, if (dest[i]) { utext_replace(dest[i], 0, utext_nativeLength(dest[i]), input->chunkContents+nextOutputStringStart, - (int32_t)(fActiveLimit-nextOutputStringStart), &status); + static_cast(fActiveLimit - nextOutputStringStart), &status); } else { UText remainingText = UTEXT_INITIALIZER; utext_openUChars(&remainingText, input->chunkContents+nextOutputStringStart, @@ -2240,7 +2240,7 @@ int32_t RegexMatcher::split(UText *input, } else { UErrorCode lengthStatus = U_ZERO_ERROR; int32_t remaining16Length = utext_extract(input, nextOutputStringStart, fActiveLimit, nullptr, 0, &lengthStatus); - char16_t *remainingChars = (char16_t *)uprv_malloc(sizeof(char16_t)*(remaining16Length+1)); + char16_t* remainingChars = static_cast(uprv_malloc(sizeof(char16_t) * (remaining16Length + 1))); if (remainingChars == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; break; @@ -2318,7 +2318,7 @@ int64_t RegexMatcher::start64(int32_t group, UErrorCode &status) const { int32_t RegexMatcher::start(int32_t group, UErrorCode &status) const { - return (int32_t)start64(group, status); + return static_cast(start64(group, status)); } //-------------------------------------------------------------------------------- @@ -2512,7 +2512,7 @@ REStackFrame *RegexMatcher::resetStack() { // where they indicate that a group has not yet matched anything. fStack->removeAllElements(); - REStackFrame *iFrame = (REStackFrame *)fStack->reserveBlock(fPattern->fFrameSize, fDeferredStatus); + REStackFrame* iFrame = reinterpret_cast(fStack->reserveBlock(fPattern->fFrameSize, fDeferredStatus)); if(U_FAILURE(fDeferredStatus)) { return nullptr; } @@ -2650,7 +2650,7 @@ UBool RegexMatcher::isUWordBoundary(int64_t pos, UErrorCode &status) { // words are not boundaries. All non-word chars stand by themselves, // with word boundaries on both sides. } else { - returnVal = fWordBreakItr->isBoundary((int32_t)pos); + returnVal = fWordBreakItr->isBoundary(static_cast(pos)); } #endif return returnVal; @@ -2743,10 +2743,10 @@ inline REStackFrame *RegexMatcher::StateSave(REStackFrame *fp, int64_t savePatId // be looked at again. return fp; } - fp = (REStackFrame *)(newFP - fFrameSize); // in case of realloc of stack. + fp = reinterpret_cast(newFP - fFrameSize); // in case of realloc of stack. // New stack frame = copy of old top frame. - int64_t *source = (int64_t *)fp; + int64_t* source = reinterpret_cast(fp); int64_t *dest = newFP; for (;;) { *dest++ = *source++; @@ -2760,7 +2760,7 @@ inline REStackFrame *RegexMatcher::StateSave(REStackFrame *fp, int64_t savePatId IncrementTime(status); // Re-initializes fTickCounter } fp->fPatIdx = savePatIdx; - return (REStackFrame *)newFP; + return reinterpret_cast(newFP); } #if defined(REGEX_DEBUG) @@ -2833,7 +2833,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // One iteration of the loop per pattern operation performed. // for (;;) { - op = (int32_t)pat[fp->fPatIdx]; + op = static_cast(pat[fp->fPatIdx]); opType = URX_TYPE(op); opValue = URX_VAL(op); #ifdef REGEX_RUN_DEBUG @@ -2857,7 +2857,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Force a backtrack. In some circumstances, the pattern compiler // will notice that the pattern can't possibly match anything, and will // emit one of these at that point. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -2872,7 +2872,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } else { fHitEnd = true; } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -2883,7 +2883,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // offset to the string text, and one for the length. int32_t stringStartIdx = opValue; - op = (int32_t)pat[fp->fPatIdx]; // Fetch the second operand + op = static_cast(pat[fp->fPatIdx]); // Fetch the second operand fp->fPatIdx++; opType = URX_TYPE(op); int32_t stringLen = URX_VAL(op); @@ -2913,7 +2913,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -2929,7 +2929,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // when we reach the end of the pattern. if (toEnd && fp->fInputIdx != fActiveLimit) { // The pattern matched, but not to the end of input. Try some more. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } isMatch = true; @@ -2990,7 +2990,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3013,7 +3013,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } // Not at end of input. Back-track out. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -3038,7 +3038,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } } // not at a new line. Fail. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3055,7 +3055,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // It makes no difference where the new-line is within the input. UTEXT_SETNATIVEINDEX(fInputText, fp->fInputIdx); if (UTEXT_CURRENT32(fInputText) != 0x0a) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3063,7 +3063,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_CARET: // ^, test for start of line if (fp->fInputIdx != fAnchorStart) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3084,7 +3084,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { break; } // Not at the start of a line. Fail. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3102,7 +3102,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { UChar32 c = UTEXT_PREVIOUS32(fInputText); if (c != 0x0a) { // Not at the start of a line. Back-track out. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3110,9 +3110,9 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_BACKSLASH_B: // Test for word boundaries { UBool success = isWordBoundary(fp->fInputIdx); - success ^= (UBool)(opValue != 0); // flip sense for \B + success ^= static_cast(opValue != 0); // flip sense for \B if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3121,9 +3121,9 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_BACKSLASH_BU: // Test for word boundaries, Unicode-style { UBool success = isUWordBoundary(fp->fInputIdx, status); - success ^= (UBool)(opValue != 0); // flip sense for \B + success ^= static_cast(opValue != 0); // flip sense for \B if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3133,7 +3133,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3142,11 +3142,11 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { UChar32 c = UTEXT_NEXT32(fInputText); int8_t ctype = u_charType(c); // TODO: make a unicode set for this. Will be faster. UBool success = (ctype == U_DECIMAL_DIGIT_NUMBER); - success ^= (UBool)(opValue != 0); // flip sense for \D + success ^= static_cast(opValue != 0); // flip sense for \D if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3154,7 +3154,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_BACKSLASH_G: // Test for position at end of previous match if (!((fMatch && fp->fInputIdx==fMatchEnd) || (fMatch==false && fp->fInputIdx==fActiveStart))) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3163,18 +3163,18 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UTEXT_SETNATIVEINDEX(fInputText, fp->fInputIdx); UChar32 c = UTEXT_NEXT32(fInputText); int8_t ctype = u_charType(c); UBool success = (ctype == U_SPACE_SEPARATOR || c == 9); // SPACE_SEPARATOR || TAB - success ^= (UBool)(opValue != 0); // flip sense for \H + success ^= static_cast(opValue != 0); // flip sense for \H if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3184,7 +3184,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UTEXT_SETNATIVEINDEX(fInputText, fp->fInputIdx); @@ -3195,7 +3195,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3205,17 +3205,17 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UTEXT_SETNATIVEINDEX(fInputText, fp->fInputIdx); UChar32 c = UTEXT_NEXT32(fInputText); UBool success = isLineTerminator(c); - success ^= (UBool)(opValue != 0); // flip sense for \V + success ^= static_cast(opValue != 0); // flip sense for \V if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3227,7 +3227,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Fail if at end of input if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3241,7 +3241,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_BACKSLASH_Z: // Test for end of Input if (fp->fInputIdx < fAnchorLimit) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } else { fHitEnd = true; fRequireEnd = true; @@ -3259,7 +3259,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // 1: success if input char is not in set. if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3284,7 +3284,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { // the character wasn't in the set. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3296,7 +3296,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // the predefined sets (Word Characters, for example) if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3319,7 +3319,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } } // the character wasn't in the set. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3327,7 +3327,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_SETREF: if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } else { UTEXT_SETNATIVEINDEX(fInputText, fp->fInputIdx); @@ -3342,7 +3342,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { break; } } else { - UnicodeSet *s = (UnicodeSet *)fSets->elementAt(opValue); + UnicodeSet* s = static_cast(fSets->elementAt(opValue)); if (s->contains(c)) { // The character is in the set. A Match. fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); @@ -3351,7 +3351,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { } // the character wasn't in the set. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -3362,7 +3362,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3372,7 +3372,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { UChar32 c = UTEXT_NEXT32(fInputText); if (isLineTerminator(c)) { // End of line in normal mode. . does not match. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); @@ -3386,7 +3386,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3416,7 +3416,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3426,7 +3426,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { UChar32 c = UTEXT_NEXT32(fInputText); if (c == 0x0a) { // End of line in normal mode. '.' does not match the \n - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } else { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } @@ -3455,7 +3455,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // data address of the input position at the start of the loop. { U_ASSERT(opValue > 0 && opValue < fPattern->fCompiledPat->size()); - int32_t stoOp = (int32_t)pat[opValue-1]; + int32_t stoOp = static_cast(pat[opValue - 1]); U_ASSERT(URX_TYPE(stoOp) == URX_STO_INP_LOC); int32_t frameLoc = URX_VAL(stoOp); U_ASSERT(frameLoc >= 0 && frameLoc < fFrameSize); @@ -3479,11 +3479,11 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Pick up the three extra operands that CTR_INIT has, and // skip the pattern location counter past - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 3; int32_t loopLoc = URX_VAL(pat[instrOperandLoc]); - int32_t minCount = (int32_t)pat[instrOperandLoc+1]; - int32_t maxCount = (int32_t)pat[instrOperandLoc+2]; + int32_t minCount = static_cast(pat[instrOperandLoc + 1]); + int32_t maxCount = static_cast(pat[instrOperandLoc + 2]); U_ASSERT(minCount>=0); U_ASSERT(maxCount>=minCount || maxCount==-1); U_ASSERT(loopLoc>=fp->fPatIdx); @@ -3494,7 +3494,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (maxCount == -1) { fp->fExtra[opValue+1] = fp->fInputIdx; // For loop breaking. } else if (maxCount == 0) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3502,13 +3502,13 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_CTR_LOOP: { U_ASSERT(opValue>0 && opValue < fp->fPatIdx-2); - int32_t initOp = (int32_t)pat[opValue]; + int32_t initOp = static_cast(pat[opValue]); U_ASSERT(URX_TYPE(initOp) == URX_CTR_INIT); int64_t *pCounter = &fp->fExtra[URX_VAL(initOp)]; - int32_t minCount = (int32_t)pat[opValue+2]; - int32_t maxCount = (int32_t)pat[opValue+3]; + int32_t minCount = static_cast(pat[opValue + 2]); + int32_t maxCount = static_cast(pat[opValue + 3]); (*pCounter)++; - if ((uint64_t)*pCounter >= (uint32_t)maxCount && maxCount != -1) { + if (static_cast(*pCounter) >= static_cast(maxCount) && maxCount != -1) { U_ASSERT(*pCounter == maxCount); break; } @@ -3544,11 +3544,11 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Pick up the three extra operands that CTR_INIT_NG has, and // skip the pattern location counter past - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 3; int32_t loopLoc = URX_VAL(pat[instrOperandLoc]); - int32_t minCount = (int32_t)pat[instrOperandLoc+1]; - int32_t maxCount = (int32_t)pat[instrOperandLoc+2]; + int32_t minCount = static_cast(pat[instrOperandLoc + 1]); + int32_t maxCount = static_cast(pat[instrOperandLoc + 2]); U_ASSERT(minCount>=0); U_ASSERT(maxCount>=minCount || maxCount==-1); U_ASSERT(loopLoc>fp->fPatIdx); @@ -3569,14 +3569,14 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { // Non-greedy {min, max} loops U_ASSERT(opValue>0 && opValue < fp->fPatIdx-2); - int32_t initOp = (int32_t)pat[opValue]; + int32_t initOp = static_cast(pat[opValue]); U_ASSERT(URX_TYPE(initOp) == URX_CTR_INIT_NG); int64_t *pCounter = &fp->fExtra[URX_VAL(initOp)]; - int32_t minCount = (int32_t)pat[opValue+2]; - int32_t maxCount = (int32_t)pat[opValue+3]; + int32_t minCount = static_cast(pat[opValue + 2]); + int32_t maxCount = static_cast(pat[opValue + 3]); (*pCounter)++; - if ((uint64_t)*pCounter >= (uint32_t)maxCount && maxCount != -1) { + if (static_cast(*pCounter) >= static_cast(maxCount) && maxCount != -1) { // The loop has matched the maximum permitted number of times. // Break out of here with no action. Matching will // continue with the following pattern. @@ -3623,17 +3623,17 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_LD_SP: { U_ASSERT(opValue >= 0 && opValue < fPattern->fDataSize); - int32_t newStackSize = (int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(newStackSize <= fStack->size()); int64_t *newFP = fStack->getBuffer() + newStackSize - fFrameSize; - if (newFP == (int64_t *)fp) { + if (newFP == reinterpret_cast(fp)) { break; } int32_t j; for (j=0; j(fp)[j]; } - fp = (REStackFrame *)newFP; + fp = reinterpret_cast(newFP); fStack->setSize(newStackSize); } break; @@ -3646,7 +3646,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { U_ASSERT(groupStartIdx <= groupEndIdx); if (groupStartIdx < 0) { // This capture group has not participated in the match thus far, - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no match. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no match. break; } UTEXT_SETNATIVEINDEX(fAltInputText, groupStartIdx); @@ -3678,7 +3678,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -3693,7 +3693,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { U_ASSERT(groupStartIdx <= groupEndIdx); if (groupStartIdx < 0) { // This capture group has not participated in the match thus far, - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no match. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no match. break; } utext_setNativeIndex(fAltInputText, groupStartIdx); @@ -3734,7 +3734,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } @@ -3749,7 +3749,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { case URX_JMPX: { - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 1; int32_t dataLoc = URX_VAL(pat[instrOperandLoc]); U_ASSERT(dataLoc >= 0 && dataLoc < fFrameSize); @@ -3758,7 +3758,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (savedInputIdx < fp->fInputIdx) { fp->fPatIdx = opValue; // JMP } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no progress in loop. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no progress in loop. } } break; @@ -3783,7 +3783,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // restore Stack Ptr, Input Pos to positions they had on entry to block. U_ASSERT(opValue>=0 && opValue+3fDataSize); int32_t stackSize = fStack->size(); - int32_t newStackSize =(int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(stackSize >= newStackSize); if (stackSize > newStackSize) { // Copy the current top frame back to the new (cut back) top frame. @@ -3792,9 +3792,9 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { int64_t *newFP = fStack->getBuffer() + newStackSize - fFrameSize; int32_t j; for (j=0; j(fp)[j]; } - fp = (REStackFrame *)newFP; + fp = reinterpret_cast(newFP); fStack->setSize(newStackSize); } fp->fInputIdx = fData[opValue+1]; @@ -3824,7 +3824,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { fHitEnd = true; } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; case URX_STRING_I: @@ -3837,7 +3837,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { const char16_t *patternString = litText + opValue; int32_t patternStringIdx = 0; - op = (int32_t)pat[fp->fPatIdx]; + op = static_cast(pat[fp->fPatIdx]); fp->fPatIdx++; opType = URX_TYPE(op); opValue = URX_VAL(op); @@ -3871,7 +3871,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (success) { fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } } @@ -3904,8 +3904,8 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Fetch the min and max possible match lengths. They are the operands // of this op in the pattern. - int32_t minML = (int32_t)pat[fp->fPatIdx++]; - int32_t maxML = (int32_t)pat[fp->fPatIdx++]; + int32_t minML = static_cast(pat[fp->fPatIdx++]); + int32_t maxML = static_cast(pat[fp->fPatIdx++]); if (!UTEXT_USES_U16(fInputText)) { // utf-8 fix to maximum match length. The pattern compiler assumes utf-16. // The max length need not be exact; it just needs to be >= actual maximum. @@ -3941,7 +3941,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // We have tried all potential match starting points without // getting a match. Backtrack out, and out of the // Look Behind altogether. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); fActiveStart = fData[opValue+2]; fActiveLimit = fData[opValue+3]; U_ASSERT(fActiveStart >= 0); @@ -3966,7 +3966,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // FAIL out of here, which will take us back to the LB_CONT, which // will retry the match starting at another position or fail // the look-behind altogether, whichever is appropriate. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -3987,14 +3987,14 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // at all possible input starting positions. // Fetch the extra parameters of this op. - int32_t minML = (int32_t)pat[fp->fPatIdx++]; - int32_t maxML = (int32_t)pat[fp->fPatIdx++]; + int32_t minML = static_cast(pat[fp->fPatIdx++]); + int32_t maxML = static_cast(pat[fp->fPatIdx++]); if (!UTEXT_USES_U16(fInputText)) { // utf-8 fix to maximum match length. The pattern compiler assumes utf-16. // The max length need not be exact; it just needs to be >= actual maximum. maxML *= 3; } - int32_t continueLoc = (int32_t)pat[fp->fPatIdx++]; + int32_t continueLoc = static_cast(pat[fp->fPatIdx++]); continueLoc = URX_VAL(continueLoc); U_ASSERT(minML <= maxML); U_ASSERT(minML >= 0); @@ -4052,7 +4052,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // FAIL out of here, which will take us back to the LB_CONT, which // will retry the match starting at another position or succeed // the look-behind altogether, whichever is appropriate. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4070,13 +4070,13 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Restore original stack position, discarding any state saved // by the successful pattern match. U_ASSERT(opValue>=0 && opValue+1fDataSize); - int32_t newStackSize = (int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(fStack->size() > newStackSize); fStack->setSize(newStackSize); // FAIL, which will take control back to someplace // prior to entering the look-behind test. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4089,7 +4089,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { { U_ASSERT(opValue > 0 && opValue < fSets->size()); Regex8BitSet *s8 = &fPattern->fSets8[opValue]; - UnicodeSet *s = (UnicodeSet *)fSets->elementAt(opValue); + UnicodeSet* s = static_cast(fSets->elementAt(opValue)); // Loop through input, until either the input is exhausted or // we reach a character that is not a member of the set. @@ -4123,7 +4123,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Peek ahead in the compiled pattern, to the URX_LOOP_C that // must follow. It's operand is the stack location // that holds the starting input index for the match of this [set]* - int32_t loopcOp = (int32_t)pat[fp->fPatIdx]; + int32_t loopcOp = static_cast(pat[fp->fPatIdx]); U_ASSERT(URX_TYPE(loopcOp) == URX_LOOP_C); int32_t stackLoc = URX_VAL(loopcOp); U_ASSERT(stackLoc >= 0 && stackLoc < fFrameSize); @@ -4184,7 +4184,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { // Peek ahead in the compiled pattern, to the URX_LOOP_C that // must follow. It's operand is the stack location // that holds the starting input index for the match of this .* - int32_t loopcOp = (int32_t)pat[fp->fPatIdx]; + int32_t loopcOp = static_cast(pat[fp->fPatIdx]); U_ASSERT(URX_TYPE(loopcOp) == URX_LOOP_C); int32_t stackLoc = URX_VAL(loopcOp); U_ASSERT(stackLoc >= 0 && stackLoc < fFrameSize); @@ -4225,7 +4225,7 @@ void RegexMatcher::MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status) { if (prevC == 0x0a && fp->fInputIdx > backSearchIndex && twoPrevC == 0x0d) { - int32_t prevOp = (int32_t)pat[fp->fPatIdx-2]; + int32_t prevOp = static_cast(pat[fp->fPatIdx - 2]); if (URX_TYPE(prevOp) == URX_LOOP_DOT_I) { // .*, stepping back over CRLF pair. fp->fInputIdx = UTEXT_GETNATIVEINDEX(fInputText); @@ -4342,7 +4342,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // One iteration of the loop per pattern operation performed. // for (;;) { - op = (int32_t)pat[fp->fPatIdx]; + op = static_cast(pat[fp->fPatIdx]); opType = URX_TYPE(op); opValue = URX_VAL(op); #ifdef REGEX_RUN_DEBUG @@ -4366,7 +4366,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Force a backtrack. In some circumstances, the pattern compiler // will notice that the pattern can't possibly match anything, and will // emit one of these at that point. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -4380,7 +4380,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } else { fHitEnd = true; } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -4392,7 +4392,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu int32_t stringStartIdx = opValue; int32_t stringLen; - op = (int32_t)pat[fp->fPatIdx]; // Fetch the second operand + op = static_cast(pat[fp->fPatIdx]); // Fetch the second operand fp->fPatIdx++; opType = URX_TYPE(op); stringLen = URX_VAL(op); @@ -4419,7 +4419,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (success) { fp->fInputIdx += stringLen; } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4435,7 +4435,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // when we reach the end of the pattern. if (toEnd && fp->fInputIdx != fActiveLimit) { // The pattern matched, but not to the end of input. Try some more. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } isMatch = true; @@ -4466,7 +4466,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (fp->fInputIdx < fAnchorLimit-2) { // We are no where near the end of input. Fail. // This is the common case. Keep it first. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } if (fp->fInputIdx >= fAnchorLimit) { @@ -4497,7 +4497,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu break; // At CR/LF at end of input. Success } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -4521,7 +4521,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } // Not at end of input. Back-track out. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; @@ -4545,7 +4545,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } } // not at a new line. Fail. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4561,7 +4561,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // If we are not positioned just before a new-line, the test fails; backtrack out. // It makes no difference where the new-line is within the input. if (inputBuf[fp->fInputIdx] != 0x0a) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4569,7 +4569,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_CARET: // ^, test for start of line if (fp->fInputIdx != fAnchorStart) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4590,7 +4590,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu break; } // Not at the start of a line. Fail. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4607,17 +4607,17 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu char16_t c = inputBuf[fp->fInputIdx - 1]; if (c != 0x0a) { // Not at the start of a line. Back-track out. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; case URX_BACKSLASH_B: // Test for word boundaries { - UBool success = isChunkWordBoundary((int32_t)fp->fInputIdx); - success ^= (UBool)(opValue != 0); // flip sense for \B + UBool success = isChunkWordBoundary(static_cast(fp->fInputIdx)); + success ^= static_cast(opValue != 0); // flip sense for \B if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4626,9 +4626,9 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_BACKSLASH_BU: // Test for word boundaries, Unicode-style { UBool success = isUWordBoundary(fp->fInputIdx, status); - success ^= (UBool)(opValue != 0); // flip sense for \B + success ^= static_cast(opValue != 0); // flip sense for \B if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4638,7 +4638,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4646,9 +4646,9 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu U16_NEXT(inputBuf, fp->fInputIdx, fActiveLimit, c); int8_t ctype = u_charType(c); // TODO: make a unicode set for this. Will be faster. UBool success = (ctype == U_DECIMAL_DIGIT_NUMBER); - success ^= (UBool)(opValue != 0); // flip sense for \D + success ^= static_cast(opValue != 0); // flip sense for \D if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4656,7 +4656,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_BACKSLASH_G: // Test for position at end of previous match if (!((fMatch && fp->fInputIdx==fMatchEnd) || (fMatch==false && fp->fInputIdx==fActiveStart))) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4665,16 +4665,16 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UChar32 c; U16_NEXT(inputBuf, fp->fInputIdx, fActiveLimit, c); int8_t ctype = u_charType(c); UBool success = (ctype == U_SPACE_SEPARATOR || c == 9); // SPACE_SEPARATOR || TAB - success ^= (UBool)(opValue != 0); // flip sense for \H + success ^= static_cast(opValue != 0); // flip sense for \H if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4684,7 +4684,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UChar32 c; @@ -4699,7 +4699,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } } } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4709,15 +4709,15 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } UChar32 c; U16_NEXT(inputBuf, fp->fInputIdx, fActiveLimit, c); UBool success = isLineTerminator(c); - success ^= (UBool)(opValue != 0); // flip sense for \V + success ^= static_cast(opValue != 0); // flip sense for \V if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4729,7 +4729,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Fail if at end of input if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4743,7 +4743,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_BACKSLASH_Z: // Test for end of Input if (fp->fInputIdx < fAnchorLimit) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } else { fHitEnd = true; fRequireEnd = true; @@ -4761,7 +4761,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // 1: success if input char is not in set. if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4783,7 +4783,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } } if (!success) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4795,7 +4795,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // the predefined sets (Word Characters, for example) if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4814,7 +4814,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu break; } } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4823,7 +4823,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { if (fp->fInputIdx >= fActiveLimit) { fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4839,7 +4839,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu break; } } else { - UnicodeSet *s = (UnicodeSet *)fSets->elementAt(opValue); + UnicodeSet* s = static_cast(fSets->elementAt(opValue)); if (s->contains(c)) { // The character is in the set. A Match. break; @@ -4847,7 +4847,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } // the character wasn't in the set. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -4858,7 +4858,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4867,7 +4867,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu U16_NEXT(inputBuf, fp->fInputIdx, fActiveLimit, c); if (isLineTerminator(c)) { // End of line in normal mode. . does not match. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } } @@ -4880,7 +4880,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4905,7 +4905,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (fp->fInputIdx >= fActiveLimit) { // At end of input. Match failed. Backtrack out. fHitEnd = true; - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -4914,7 +4914,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu U16_NEXT(inputBuf, fp->fInputIdx, fActiveLimit, c); if (c == 0x0a) { // End of line in normal mode. '.' does not match the \n - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4941,11 +4941,11 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // data address of the input position at the start of the loop. { U_ASSERT(opValue > 0 && opValue < fPattern->fCompiledPat->size()); - int32_t stoOp = (int32_t)pat[opValue-1]; + int32_t stoOp = static_cast(pat[opValue - 1]); U_ASSERT(URX_TYPE(stoOp) == URX_STO_INP_LOC); int32_t frameLoc = URX_VAL(stoOp); U_ASSERT(frameLoc >= 0 && frameLoc < fFrameSize); - int32_t prevInputIdx = (int32_t)fp->fExtra[frameLoc]; + int32_t prevInputIdx = static_cast(fp->fExtra[frameLoc]); U_ASSERT(prevInputIdx <= fp->fInputIdx); if (prevInputIdx < fp->fInputIdx) { // The match did make progress. Repeat the loop. @@ -4965,11 +4965,11 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Pick up the three extra operands that CTR_INIT has, and // skip the pattern location counter past - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 3; int32_t loopLoc = URX_VAL(pat[instrOperandLoc]); - int32_t minCount = (int32_t)pat[instrOperandLoc+1]; - int32_t maxCount = (int32_t)pat[instrOperandLoc+2]; + int32_t minCount = static_cast(pat[instrOperandLoc + 1]); + int32_t maxCount = static_cast(pat[instrOperandLoc + 2]); U_ASSERT(minCount>=0); U_ASSERT(maxCount>=minCount || maxCount==-1); U_ASSERT(loopLoc>=fp->fPatIdx); @@ -4980,7 +4980,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (maxCount == -1) { fp->fExtra[opValue+1] = fp->fInputIdx; // For loop breaking. } else if (maxCount == 0) { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -4988,13 +4988,13 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_CTR_LOOP: { U_ASSERT(opValue>0 && opValue < fp->fPatIdx-2); - int32_t initOp = (int32_t)pat[opValue]; + int32_t initOp = static_cast(pat[opValue]); U_ASSERT(URX_TYPE(initOp) == URX_CTR_INIT); int64_t *pCounter = &fp->fExtra[URX_VAL(initOp)]; - int32_t minCount = (int32_t)pat[opValue+2]; - int32_t maxCount = (int32_t)pat[opValue+3]; + int32_t minCount = static_cast(pat[opValue + 2]); + int32_t maxCount = static_cast(pat[opValue + 3]); (*pCounter)++; - if ((uint64_t)*pCounter >= (uint32_t)maxCount && maxCount != -1) { + if (static_cast(*pCounter) >= static_cast(maxCount) && maxCount != -1) { U_ASSERT(*pCounter == maxCount); break; } @@ -5029,11 +5029,11 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Pick up the three extra operands that CTR_INIT_NG has, and // skip the pattern location counter past - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 3; int32_t loopLoc = URX_VAL(pat[instrOperandLoc]); - int32_t minCount = (int32_t)pat[instrOperandLoc+1]; - int32_t maxCount = (int32_t)pat[instrOperandLoc+2]; + int32_t minCount = static_cast(pat[instrOperandLoc + 1]); + int32_t maxCount = static_cast(pat[instrOperandLoc + 2]); U_ASSERT(minCount>=0); U_ASSERT(maxCount>=minCount || maxCount==-1); U_ASSERT(loopLoc>fp->fPatIdx); @@ -5054,14 +5054,14 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { // Non-greedy {min, max} loops U_ASSERT(opValue>0 && opValue < fp->fPatIdx-2); - int32_t initOp = (int32_t)pat[opValue]; + int32_t initOp = static_cast(pat[opValue]); U_ASSERT(URX_TYPE(initOp) == URX_CTR_INIT_NG); int64_t *pCounter = &fp->fExtra[URX_VAL(initOp)]; - int32_t minCount = (int32_t)pat[opValue+2]; - int32_t maxCount = (int32_t)pat[opValue+3]; + int32_t minCount = static_cast(pat[opValue + 2]); + int32_t maxCount = static_cast(pat[opValue + 3]); (*pCounter)++; - if ((uint64_t)*pCounter >= (uint32_t)maxCount && maxCount != -1) { + if (static_cast(*pCounter) >= static_cast(maxCount) && maxCount != -1) { // The loop has matched the maximum permitted number of times. // Break out of here with no action. Matching will // continue with the following pattern. @@ -5107,17 +5107,17 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_LD_SP: { U_ASSERT(opValue >= 0 && opValue < fPattern->fDataSize); - int32_t newStackSize = (int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(newStackSize <= fStack->size()); int64_t *newFP = fStack->getBuffer() + newStackSize - fFrameSize; - if (newFP == (int64_t *)fp) { + if (newFP == reinterpret_cast(fp)) { break; } int32_t j; for (j=0; j(fp)[j]; } - fp = (REStackFrame *)newFP; + fp = reinterpret_cast(newFP); fStack->setSize(newStackSize); } break; @@ -5131,7 +5131,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu int64_t inputIndex = fp->fInputIdx; if (groupStartIdx < 0) { // This capture group has not participated in the match thus far, - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no match. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no match. break; } UBool success = true; @@ -5155,7 +5155,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (success) { fp->fInputIdx = inputIndex; } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -5168,7 +5168,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu U_ASSERT(groupStartIdx <= groupEndIdx); if (groupStartIdx < 0) { // This capture group has not participated in the match thus far, - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no match. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no match. break; } CaseFoldingUCharIterator captureGroupItr(inputBuf, groupStartIdx, groupEndIdx); @@ -5207,7 +5207,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (success) { fp->fInputIdx = inputItr.getIndex(); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -5221,16 +5221,16 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_JMPX: { - int32_t instrOperandLoc = (int32_t)fp->fPatIdx; + int32_t instrOperandLoc = static_cast(fp->fPatIdx); fp->fPatIdx += 1; int32_t dataLoc = URX_VAL(pat[instrOperandLoc]); U_ASSERT(dataLoc >= 0 && dataLoc < fFrameSize); - int32_t savedInputIdx = (int32_t)fp->fExtra[dataLoc]; + int32_t savedInputIdx = static_cast(fp->fExtra[dataLoc]); U_ASSERT(savedInputIdx <= fp->fInputIdx); if (savedInputIdx < fp->fInputIdx) { fp->fPatIdx = opValue; // JMP } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); // FAIL, no progress in loop. + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); // FAIL, no progress in loop. } } break; @@ -5255,7 +5255,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // restore Stack Ptr, Input Pos to positions they had on entry to block. U_ASSERT(opValue>=0 && opValue+3fDataSize); int32_t stackSize = fStack->size(); - int32_t newStackSize = (int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(stackSize >= newStackSize); if (stackSize > newStackSize) { // Copy the current top frame back to the new (cut back) top frame. @@ -5264,9 +5264,9 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu int64_t *newFP = fStack->getBuffer() + newStackSize - fFrameSize; int32_t j; for (j=0; j(fp)[j]; } - fp = (REStackFrame *)newFP; + fp = reinterpret_cast(newFP); fStack->setSize(newStackSize); } fp->fInputIdx = fData[opValue+1]; @@ -5290,7 +5290,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu } else { fHitEnd = true; } - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; case URX_STRING_I: @@ -5301,7 +5301,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { const char16_t *patternString = litText + opValue; - op = (int32_t)pat[fp->fPatIdx]; + op = static_cast(pat[fp->fPatIdx]); fp->fPatIdx++; opType = URX_TYPE(op); opValue = URX_VAL(op); @@ -5331,7 +5331,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (success) { fp->fInputIdx = inputIterator.getIndex(); } else { - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } } break; @@ -5363,8 +5363,8 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Fetch the min and max possible match lengths. They are the operands // of this op in the pattern. - int32_t minML = (int32_t)pat[fp->fPatIdx++]; - int32_t maxML = (int32_t)pat[fp->fPatIdx++]; + int32_t minML = static_cast(pat[fp->fPatIdx++]); + int32_t maxML = static_cast(pat[fp->fPatIdx++]); U_ASSERT(minML <= maxML); U_ASSERT(minML >= 0); @@ -5391,7 +5391,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // We have tried all potential match starting points without // getting a match. Backtrack out, and out of the // Look Behind altogether. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); fActiveStart = fData[opValue+2]; fActiveLimit = fData[opValue+3]; U_ASSERT(fActiveStart >= 0); @@ -5416,7 +5416,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // FAIL out of here, which will take us back to the LB_CONT, which // will retry the match starting at another position or fail // the look-behind altogether, whichever is appropriate. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -5437,9 +5437,9 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // at all possible input starting positions. // Fetch the extra parameters of this op. - int32_t minML = (int32_t)pat[fp->fPatIdx++]; - int32_t maxML = (int32_t)pat[fp->fPatIdx++]; - int32_t continueLoc = (int32_t)pat[fp->fPatIdx++]; + int32_t minML = static_cast(pat[fp->fPatIdx++]); + int32_t maxML = static_cast(pat[fp->fPatIdx++]); + int32_t continueLoc = static_cast(pat[fp->fPatIdx++]); continueLoc = URX_VAL(continueLoc); U_ASSERT(minML <= maxML); U_ASSERT(minML >= 0); @@ -5493,7 +5493,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // FAIL out of here, which will take us back to the LB_CONT, which // will retry the match starting at another position or succeed // the look-behind altogether, whichever is appropriate. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); break; } @@ -5511,13 +5511,13 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Restore original stack position, discarding any state saved // by the successful pattern match. U_ASSERT(opValue>=0 && opValue+1fDataSize); - int32_t newStackSize = (int32_t)fData[opValue]; + int32_t newStackSize = static_cast(fData[opValue]); U_ASSERT(fStack->size() > newStackSize); fStack->setSize(newStackSize); // FAIL, which will take control back to someplace // prior to entering the look-behind test. - fp = (REStackFrame *)fStack->popFrame(fFrameSize); + fp = reinterpret_cast(fStack->popFrame(fFrameSize)); } break; @@ -5530,11 +5530,11 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu { U_ASSERT(opValue > 0 && opValue < fSets->size()); Regex8BitSet *s8 = &fPattern->fSets8[opValue]; - UnicodeSet *s = (UnicodeSet *)fSets->elementAt(opValue); + UnicodeSet* s = static_cast(fSets->elementAt(opValue)); // Loop through input, until either the input is exhausted or // we reach a character that is not a member of the set. - int32_t ix = (int32_t)fp->fInputIdx; + int32_t ix = static_cast(fp->fInputIdx); for (;;) { if (ix >= fActiveLimit) { fHitEnd = true; @@ -5565,7 +5565,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Peek ahead in the compiled pattern, to the URX_LOOP_C that // must follow. It's operand is the stack location // that holds the starting input index for the match of this [set]* - int32_t loopcOp = (int32_t)pat[fp->fPatIdx]; + int32_t loopcOp = static_cast(pat[fp->fPatIdx]); U_ASSERT(URX_TYPE(loopcOp) == URX_LOOP_C); int32_t stackLoc = URX_VAL(loopcOp); U_ASSERT(stackLoc >= 0 && stackLoc < fFrameSize); @@ -5591,12 +5591,12 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu int32_t ix; if ((opValue & 1) == 1) { // Dot-matches-All mode. Jump straight to the end of the string. - ix = (int32_t)fActiveLimit; + ix = static_cast(fActiveLimit); fHitEnd = true; } else { // NOT DOT ALL mode. Line endings do not match '.' // Scan forward until a line ending or end of input. - ix = (int32_t)fp->fInputIdx; + ix = static_cast(fp->fInputIdx); for (;;) { if (ix >= fActiveLimit) { fHitEnd = true; @@ -5627,7 +5627,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu // Peek ahead in the compiled pattern, to the URX_LOOP_C that // must follow. It's operand is the stack location // that holds the starting input index for the match of this .* - int32_t loopcOp = (int32_t)pat[fp->fPatIdx]; + int32_t loopcOp = static_cast(pat[fp->fPatIdx]); U_ASSERT(URX_TYPE(loopcOp) == URX_LOOP_C); int32_t stackLoc = URX_VAL(loopcOp); U_ASSERT(stackLoc >= 0 && stackLoc < fFrameSize); @@ -5646,7 +5646,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu case URX_LOOP_C: { U_ASSERT(opValue>=0 && opValuefExtra[opValue]; + backSearchIndex = static_cast(fp->fExtra[opValue]); U_ASSERT(backSearchIndex <= fp->fInputIdx); if (backSearchIndex == fp->fInputIdx) { // We've backed up the input idx to the point that the loop started. @@ -5666,7 +5666,7 @@ void RegexMatcher::MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &statu if (prevC == 0x0a && fp->fInputIdx > backSearchIndex && inputBuf[fp->fInputIdx-1] == 0x0d) { - int32_t prevOp = (int32_t)pat[fp->fPatIdx-2]; + int32_t prevOp = static_cast(pat[fp->fPatIdx - 2]); if (URX_TYPE(prevOp) == URX_LOOP_DOT_I) { // .*, stepping back over CRLF pair. U16_BACK_1(inputBuf, 0, fp->fInputIdx); diff --git a/icu4c/source/i18n/repattrn.cpp b/icu4c/source/i18n/repattrn.cpp index 67577436e2ca..f0cc709e9739 100644 --- a/icu4c/source/i18n/repattrn.cpp +++ b/icu4c/source/i18n/repattrn.cpp @@ -125,7 +125,7 @@ RegexPattern &RegexPattern::operator = (const RegexPattern &other) { if (U_FAILURE(fDeferredStatus)) { return *this; } - UnicodeSet *sourceSet = (UnicodeSet *)other.fSets->elementAt(i); + UnicodeSet* sourceSet = static_cast(other.fSets->elementAt(i)); UnicodeSet *newSet = new UnicodeSet(*sourceSet); if (newSet == nullptr) { fDeferredStatus = U_MEMORY_ALLOCATION_ERROR; @@ -142,7 +142,7 @@ RegexPattern &RegexPattern::operator = (const RegexPattern &other) { if (U_FAILURE(fDeferredStatus)) { break; } - const UnicodeString *name = (const UnicodeString *)hashEl->key.pointer; + const UnicodeString* name = static_cast(hashEl->key.pointer); UnicodeString *key = new UnicodeString(*name); int32_t val = hashEl->value.integer; if (key == nullptr) { @@ -199,7 +199,7 @@ void RegexPattern::init() { } // Slot zero of the vector of sets is reserved. Fill it here. - fSets->addElement((int32_t)0, fDeferredStatus); + fSets->addElement(static_cast(0), fDeferredStatus); } @@ -232,7 +232,7 @@ void RegexPattern::zap() { int i; for (i=1; isize(); i++) { UnicodeSet *s; - s = (UnicodeSet *)fSets->elementAt(i); + s = static_cast(fSets->elementAt(i)); delete s; } delete fSets; diff --git a/icu4c/source/i18n/rulebasedcollator.cpp b/icu4c/source/i18n/rulebasedcollator.cpp index 685f44de3737..3d91b3c592b8 100644 --- a/icu4c/source/i18n/rulebasedcollator.cpp +++ b/icu4c/source/i18n/rulebasedcollator.cpp @@ -427,7 +427,7 @@ RuleBasedCollator::getAttribute(UColAttribute attr, UErrorCode &errorCode) const option = CollationSettings::CHECK_FCD; break; case UCOL_STRENGTH: - return (UColAttributeValue)settings->getStrength(); + return static_cast(settings->getStrength()); case UCOL_HIRAGANA_QUATERNARY_MODE: // Deprecated attribute, unsettable. return UCOL_OFF; @@ -539,7 +539,7 @@ RuleBasedCollator::setMaxVariable(UColReorderCode group, UErrorCode &errorCode) } if(group == UCOL_REORDER_CODE_DEFAULT) { - group = (UColReorderCode)( + group = static_cast( UCOL_REORDER_CODE_FIRST + int32_t{defaultSettings.getMaxVariable()}); } uint32_t varTop = data->getLastPrimaryForGroup(group); @@ -558,7 +558,7 @@ RuleBasedCollator::setMaxVariable(UColReorderCode group, UErrorCode &errorCode) UColReorderCode RuleBasedCollator::getMaxVariable() const { - return (UColReorderCode)(UCOL_REORDER_CODE_FIRST + int32_t{settings->getMaxVariable()}); + return static_cast(UCOL_REORDER_CODE_FIRST + int32_t{settings->getMaxVariable()}); } uint32_t @@ -593,7 +593,7 @@ RuleBasedCollator::setVariableTop(const char16_t *varTop, int32_t len, UErrorCod errorCode = U_CE_NOT_FOUND_ERROR; return 0; } - setVariableTop((uint32_t)(ce1 >> 32), errorCode); + setVariableTop(static_cast(ce1 >> 32), errorCode); return settings->variableTop; } @@ -862,7 +862,7 @@ class FCDUTF16NFDIterator : public UTF16NFDIterator { s = text; limit = spanLimit; } else { - str.setTo(text, (int32_t)(spanLimit - text)); + str.setTo(text, static_cast(spanLimit - text)); { ReorderingBuffer r_buffer(nfcImpl, str); if(r_buffer.init(str.length(), errorCode)) { @@ -1063,7 +1063,7 @@ RuleBasedCollator::doCompare(const char16_t *left, int32_t leftLength, } } if(result != UCOL_EQUAL || settings->getStrength() < UCOL_IDENTICAL || U_FAILURE(errorCode)) { - return (UCollationResult)result; + return static_cast(result); } // Note: If NUL-terminated, we could get the actual limits from the iterators now. @@ -1188,7 +1188,7 @@ RuleBasedCollator::doCompare(const uint8_t *left, int32_t leftLength, } } if(result != UCOL_EQUAL || settings->getStrength() < UCOL_IDENTICAL || U_FAILURE(errorCode)) { - return (UCollationResult)result; + return static_cast(result); } // Note: If NUL-terminated, we could get the actual limits from the iterators now. @@ -1364,13 +1364,13 @@ RuleBasedCollator::writeIdenticalLevel(const char16_t *s, const char16_t *limit, sink.Append(Collation::LEVEL_SEPARATOR_BYTE); UChar32 prev = 0; if(nfdQCYesLimit != s) { - prev = u_writeIdenticalLevelRun(prev, s, (int32_t)(nfdQCYesLimit - s), sink); + prev = u_writeIdenticalLevelRun(prev, s, static_cast(nfdQCYesLimit - s), sink); } // Is there non-NFD text? int32_t destLengthEstimate; if(limit != nullptr) { if(nfdQCYesLimit == limit) { return; } - destLengthEstimate = (int32_t)(limit - nfdQCYesLimit); + destLengthEstimate = static_cast(limit - nfdQCYesLimit); } else { // s is NUL-terminated if(*nfdQCYesLimit == 0) { return; } @@ -1432,10 +1432,10 @@ RuleBasedCollator::internalNextSortKeyPart(UCharIterator *iter, uint32_t state[2 if(count == 0) { return 0; } FixedSortKeyByteSink sink(reinterpret_cast(dest), count); - sink.IgnoreBytes((int32_t)state[1]); + sink.IgnoreBytes(static_cast(state[1])); iter->move(iter, 0, UITER_START); - Collation::Level level = (Collation::Level)state[0]; + Collation::Level level = static_cast(state[0]); if(level <= Collation::QUATERNARY_LEVEL) { UBool numeric = settings->isNumeric(); PartLevelCallback callback(sink); @@ -1450,8 +1450,8 @@ RuleBasedCollator::internalNextSortKeyPart(UCharIterator *iter, uint32_t state[2 } if(U_FAILURE(errorCode)) { return 0; } if(sink.NumberOfBytesAppended() > count) { - state[0] = (uint32_t)callback.getLevel(); - state[1] = (uint32_t)callback.getLevelCapacity(); + state[0] = static_cast(callback.getLevel()); + state[1] = static_cast(callback.getLevelCapacity()); return count; } // All of the normal levels are done. @@ -1468,20 +1468,20 @@ RuleBasedCollator::internalNextSortKeyPart(UCharIterator *iter, uint32_t state[2 for(;;) { UChar32 c = iter->next(iter); if(c < 0) { break; } - s.append((char16_t)c); + s.append(static_cast(c)); } const char16_t *sArray = s.getBuffer(); writeIdenticalLevel(sArray, sArray + s.length(), sink, errorCode); if(U_FAILURE(errorCode)) { return 0; } if(sink.NumberOfBytesAppended() > count) { - state[0] = (uint32_t)level; - state[1] = (uint32_t)levelCapacity; + state[0] = static_cast(level); + state[1] = static_cast(levelCapacity); return count; } } // ZERO_LEVEL: Fill the remainder of dest with 00 bytes. - state[0] = (uint32_t)Collation::ZERO_LEVEL; + state[0] = static_cast(Collation::ZERO_LEVEL); state[1] = 0; int32_t length = sink.NumberOfBytesAppended(); int32_t i = length; diff --git a/icu4c/source/i18n/scriptset.cpp b/icu4c/source/i18n/scriptset.cpp index 736a85cf8c1f..eec1eeb37daf 100644 --- a/icu4c/source/i18n/scriptset.cpp +++ b/icu4c/source/i18n/scriptset.cpp @@ -57,7 +57,7 @@ UBool ScriptSet::test(UScriptCode script, UErrorCode &status) const { if (U_FAILURE(status)) { return false; } - if (script < 0 || (int32_t)script >= SCRIPT_LIMIT) { + if (script < 0 || static_cast(script) >= SCRIPT_LIMIT) { status = U_ILLEGAL_ARGUMENT_ERROR; return false; } @@ -71,7 +71,7 @@ ScriptSet &ScriptSet::set(UScriptCode script, UErrorCode &status) { if (U_FAILURE(status)) { return *this; } - if (script < 0 || (int32_t)script >= SCRIPT_LIMIT) { + if (script < 0 || static_cast(script) >= SCRIPT_LIMIT) { status = U_ILLEGAL_ARGUMENT_ERROR; return *this; } @@ -85,7 +85,7 @@ ScriptSet &ScriptSet::reset(UScriptCode script, UErrorCode &status) { if (U_FAILURE(status)) { return *this; } - if (script < 0 || (int32_t)script >= SCRIPT_LIMIT) { + if (script < 0 || static_cast(script) >= SCRIPT_LIMIT) { status = U_ILLEGAL_ARGUMENT_ERROR; return *this; } @@ -178,7 +178,7 @@ int32_t ScriptSet::nextSetBit(int32_t fromIndex) const { } UErrorCode status = U_ZERO_ERROR; for (int32_t scriptIndex = fromIndex; scriptIndex < SCRIPT_LIMIT; scriptIndex++) { - if (test((UScriptCode)scriptIndex, status)) { + if (test(static_cast(scriptIndex), status)) { return scriptIndex; } } @@ -198,10 +198,10 @@ UnicodeString &ScriptSet::displayScripts(UnicodeString &dest) const { UBool firstTime = true; for (int32_t i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { if (!firstTime) { - dest.append((char16_t)0x20); + dest.append(static_cast(0x20)); } firstTime = false; - const char *scriptName = uscript_getShortName((UScriptCode(i))); + const char* scriptName = uscript_getShortName(static_cast(i)); dest.append(UnicodeString(scriptName, -1, US_INV)); } return dest; @@ -230,7 +230,7 @@ ScriptSet &ScriptSet::parseScripts(const UnicodeString &scriptString, UErrorCode if (sc == UCHAR_INVALID_CODE) { status = U_ILLEGAL_ARGUMENT_ERROR; } else { - this->set((UScriptCode)sc, status); + this->set(static_cast(sc), status); } if (U_FAILURE(status)) { return *this; diff --git a/icu4c/source/i18n/search.cpp b/icu4c/source/i18n/search.cpp index ec5028ca81b7..fd46f702a4cc 100644 --- a/icu4c/source/i18n/search.cpp +++ b/icu4c/source/i18n/search.cpp @@ -27,7 +27,7 @@ SearchIterator::SearchIterator(const SearchIterator &other) { m_breakiterator_ = other.m_breakiterator_; m_text_ = other.m_text_; - m_search_ = (USearch *)uprv_malloc(sizeof(USearch)); + m_search_ = static_cast(uprv_malloc(sizeof(USearch))); m_search_->breakIter = other.m_search_->breakIter; m_search_->isCanonicalMatch = other.m_search_->isCanonicalMatch; m_search_->isOverlap = other.m_search_->isOverlap; @@ -62,7 +62,7 @@ void SearchIterator::setAttribute(USearchAttribute attribute, break; case USEARCH_ELEMENT_COMPARISON : if (value == USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD || value == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD) { - m_search_->elementComparisonType = (int16_t)value; + m_search_->elementComparisonType = static_cast(value); } else { m_search_->elementComparisonType = 0; } @@ -88,7 +88,7 @@ USearchAttributeValue SearchIterator::getAttribute( { int16_t value = m_search_->elementComparisonType; if (value == USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD || value == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD) { - return (USearchAttributeValue)value; + return static_cast(value); } else { return USEARCH_STANDARD_ELEMENT_COMPARISON; } @@ -136,7 +136,7 @@ void SearchIterator::setBreakIterator(BreakIterator *breakiter, // // Besides, a UBreakIterator is a BreakIterator, so // any subclass of BreakIterator should work fine here... - m_search_->breakIter = (UBreakIterator *) breakiter; + m_search_->breakIter = reinterpret_cast(breakiter); #endif m_breakiterator_ = breakiter; @@ -344,7 +344,7 @@ void SearchIterator::reset() SearchIterator::SearchIterator() { - m_search_ = (USearch *)uprv_malloc(sizeof(USearch)); + m_search_ = static_cast(uprv_malloc(sizeof(USearch))); m_search_->breakIter = nullptr; m_search_->isOverlap = false; m_search_->isCanonicalMatch = false; @@ -363,7 +363,7 @@ SearchIterator::SearchIterator(const UnicodeString &text, m_breakiterator_(breakiter), m_text_(text) { - m_search_ = (USearch *)uprv_malloc(sizeof(USearch)); + m_search_ = static_cast(uprv_malloc(sizeof(USearch))); m_search_->breakIter = nullptr; m_search_->isOverlap = false; m_search_->isCanonicalMatch = false; @@ -380,7 +380,7 @@ SearchIterator::SearchIterator(CharacterIterator &text, BreakIterator *breakiter) : m_breakiterator_(breakiter) { - m_search_ = (USearch *)uprv_malloc(sizeof(USearch)); + m_search_ = static_cast(uprv_malloc(sizeof(USearch))); m_search_->breakIter = nullptr; m_search_->isOverlap = false; m_search_->isCanonicalMatch = false; diff --git a/icu4c/source/i18n/simpletz.cpp b/icu4c/source/i18n/simpletz.cpp index 31ee69e7d21c..cbefc29830ff 100644 --- a/icu4c/source/i18n/simpletz.cpp +++ b/icu4c/source/i18n/simpletz.cpp @@ -310,9 +310,9 @@ void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, UErrorCode& status) { - startMonth = (int8_t)month; - startDay = (int8_t)dayOfWeekInMonth; - startDayOfWeek = (int8_t)dayOfWeek; + startMonth = static_cast(month); + startDay = static_cast(dayOfWeekInMonth); + startDayOfWeek = static_cast(dayOfWeek); startTime = time; startTimeMode = mode; decodeStartRule(status); @@ -362,9 +362,9 @@ void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, int32_t time, TimeMode mode, UErrorCode& status) { - endMonth = (int8_t)month; - endDay = (int8_t)dayOfWeekInMonth; - endDayOfWeek = (int8_t)dayOfWeek; + endMonth = static_cast(month); + endDay = static_cast(dayOfWeekInMonth); + endDayOfWeek = static_cast(dayOfWeek); endTime = time; endTimeMode = mode; decodeEndRule(status); @@ -475,11 +475,11 @@ SimpleTimeZone::getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, // Compare the date to the starting and ending rules.+1 = date>rule, -1 // = date(month), static_cast(monthLength), static_cast(prevMonthLength), + static_cast(day), static_cast(dayOfWeek), millis, startTimeMode == UTC_TIME ? -rawOffset : 0, - startMode, (int8_t)startMonth, (int8_t)startDayOfWeek, - (int8_t)startDay, startTime); + startMode, startMonth, startDayOfWeek, + startDay, startTime); int32_t endCompare = 0; /* We don't always have to compute endCompare. For many instances, @@ -489,12 +489,12 @@ SimpleTimeZone::getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, * must have DST. This is reflected in the way the next if statement * (not the one immediately following) short circuits. */ if(southern != (startCompare >= 0)) { - endCompare = compareToRule((int8_t)month, (int8_t)monthLength, (int8_t)prevMonthLength, - (int8_t)day, (int8_t)dayOfWeek, millis, + endCompare = compareToRule(static_cast(month), static_cast(monthLength), static_cast(prevMonthLength), + static_cast(day), static_cast(dayOfWeek), millis, endTimeMode == WALL_TIME ? dstSavings : (endTimeMode == UTC_TIME ? -rawOffset : 0), - endMode, (int8_t)endMonth, (int8_t)endDayOfWeek, - (int8_t)endDay, endTime); + endMode, endMonth, endDayOfWeek, + endDay, endTime); } // Check for both the northern and southern hemisphere cases. We @@ -530,7 +530,7 @@ SimpleTimeZone::getOffsetFromLocal(UDate date, UTimeZoneLocalOption nonExistingT if (U_FAILURE(status)) return; savingsDST = getOffset(GregorianCalendar::AD, year, month, dom, - (uint8_t) dow, millis, + static_cast(dow), millis, Grego::monthLength(year, month), status) - rawOffsetGMT; if (U_FAILURE(status)) { @@ -558,7 +558,7 @@ SimpleTimeZone::getOffsetFromLocal(UDate date, UTimeZoneLocalOption nonExistingT Grego::dayToFields(day, year, month, dom, dow, status); if (U_FAILURE(status)) return; savingsDST = getOffset(GregorianCalendar::AD, year, month, dom, - (uint8_t) dow, millis, + static_cast(dow), millis, Grego::monthLength(year, month), status) - rawOffsetGMT; } @@ -587,7 +587,7 @@ SimpleTimeZone::compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen while (millis >= U_MILLIS_PER_DAY) { millis -= U_MILLIS_PER_DAY; ++dayOfMonth; - dayOfWeek = (int8_t)(1 + (dayOfWeek % 7)); // dayOfWeek is one-based + dayOfWeek = static_cast(1 + (dayOfWeek % 7)); // dayOfWeek is one-based if (dayOfMonth > monthLen) { dayOfMonth = 1; /* When incrementing the month, it is desirable to overflow @@ -600,7 +600,7 @@ SimpleTimeZone::compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen while (millis < 0) { millis += U_MILLIS_PER_DAY; --dayOfMonth; - dayOfWeek = (int8_t)(1 + ((dayOfWeek+5) % 7)); // dayOfWeek is one-based + dayOfWeek = static_cast(1 + ((dayOfWeek + 5) % 7)); // dayOfWeek is one-based if (dayOfMonth < 1) { dayOfMonth = prevMonthLen; --month; @@ -877,7 +877,7 @@ SimpleTimeZone::decodeStartRule(UErrorCode& status) { if(U_FAILURE(status)) return; - useDaylight = (UBool)((startDay != 0) && (endDay != 0) ? true : false); + useDaylight = static_cast(startDay != 0 && endDay != 0); if (useDaylight && dstSavings == 0) { dstSavings = U_MILLIS_PER_HOUR; } @@ -897,11 +897,11 @@ SimpleTimeZone::decodeStartRule(UErrorCode& status) if (startDayOfWeek > 0) { startMode = DOW_IN_MONTH_MODE; } else { - startDayOfWeek = (int8_t)-startDayOfWeek; + startDayOfWeek = static_cast(-startDayOfWeek); if (startDay > 0) { startMode = DOW_GE_DOM_MODE; } else { - startDay = (int8_t)-startDay; + startDay = static_cast(-startDay); startMode = DOW_LE_DOM_MODE; } } @@ -932,7 +932,7 @@ SimpleTimeZone::decodeEndRule(UErrorCode& status) { if(U_FAILURE(status)) return; - useDaylight = (UBool)((startDay != 0) && (endDay != 0) ? true : false); + useDaylight = static_cast(startDay != 0 && endDay != 0); if (useDaylight && dstSavings == 0) { dstSavings = U_MILLIS_PER_HOUR; } @@ -952,11 +952,11 @@ SimpleTimeZone::decodeEndRule(UErrorCode& status) if (endDayOfWeek > 0) { endMode = DOW_IN_MONTH_MODE; } else { - endDayOfWeek = (int8_t)-endDayOfWeek; + endDayOfWeek = static_cast(-endDayOfWeek); if (endDay > 0) { endMode = DOW_GE_DOM_MODE; } else { - endDay = (int8_t)-endDay; + endDay = static_cast(-endDay); endMode = DOW_LE_DOM_MODE; } } diff --git a/icu4c/source/i18n/smpdtfmt.cpp b/icu4c/source/i18n/smpdtfmt.cpp index cd7a08abfc26..f79d4ae49532 100644 --- a/icu4c/source/i18n/smpdtfmt.cpp +++ b/icu4c/source/i18n/smpdtfmt.cpp @@ -297,8 +297,8 @@ static const SharedNumberFormat *createSharedNumberFormat( } static const SharedNumberFormat **allocSharedNumberFormatters() { - const SharedNumberFormat **result = (const SharedNumberFormat**) - uprv_malloc(UDAT_FIELD_COUNT * sizeof(const SharedNumberFormat*)); + const SharedNumberFormat** result = static_cast( + uprv_malloc(UDAT_FIELD_COUNT * sizeof(const SharedNumberFormat*))); if (result == nullptr) { return nullptr; } @@ -346,7 +346,7 @@ SimpleDateFormat::SimpleDateFormat(UErrorCode& status) : fLocale(Locale::getDefault()) { initializeBooleanAttributes(); - construct(kShort, (EStyle) (kShort + kDateOffset), fLocale, status); + construct(kShort, static_cast(kShort + kDateOffset), fLocale, status); initializeDefaultCentury(); } @@ -772,7 +772,7 @@ void SimpleDateFormat::construct(EStyle timeStyle, UnicodeString tempus1(timePattern); if (tempus1.length() == 0) { currentBundle.adoptInstead( - ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)timeStyle, nullptr, &status)); + ures_getByIndex(dateTimePatterns.getAlias(), static_cast(timeStyle), nullptr, &status)); if (U_FAILURE(status)) { status = U_INVALID_FORMAT_ERROR; return; @@ -798,7 +798,7 @@ void SimpleDateFormat::construct(EStyle timeStyle, } currentBundle.adoptInstead( - ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)dateStyle, nullptr, &status)); + ures_getByIndex(dateTimePatterns.getAlias(), static_cast(dateStyle), nullptr, &status)); if (U_FAILURE(status)) { status = U_INVALID_FORMAT_ERROR; return; @@ -848,7 +848,7 @@ void SimpleDateFormat::construct(EStyle timeStyle, int32_t patternsSize = ures_getSize(dateTimePatterns.getAlias()); if (patternsSize >= (kDateTimeOffset + kShort + 1)) { // Get proper date time format - glueIndex = (int32_t)(kDateTimeOffset + (dateStyle - kDateOffset)); + glueIndex = static_cast(kDateTimeOffset + (dateStyle - kDateOffset)); } resStr = ures_getStringByIndex(dateTimePatterns.getAlias(), glueIndex, &resStrLen, &status); @@ -863,7 +863,7 @@ void SimpleDateFormat::construct(EStyle timeStyle, fPattern.setTo(timePattern); if (fPattern.length() == 0) { currentBundle.adoptInstead( - ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)timeStyle, nullptr, &status)); + ures_getByIndex(dateTimePatterns.getAlias(), static_cast(timeStyle), nullptr, &status)); if (U_FAILURE(status)) { status = U_INVALID_FORMAT_ERROR; return; @@ -889,7 +889,7 @@ void SimpleDateFormat::construct(EStyle timeStyle, } else if (dateStyle != kNone) { currentBundle.adoptInstead( - ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)dateStyle, nullptr, &status)); + ures_getByIndex(dateTimePatterns.getAlias(), static_cast(dateStyle), nullptr, &status)); if (U_FAILURE(status)) { status = U_INVALID_FORMAT_ERROR; return; @@ -1088,7 +1088,7 @@ SimpleDateFormat::_format(Calendar& cal, UnicodeString& appendTo, // Consecutive single quotes are a single quote literal, // either outside of quotes or between quotes if ((i+1) < patternLength && fPattern[i+1] == QUOTE) { - appendTo += (char16_t)QUOTE; + appendTo += QUOTE; ++i; } else { inQuote = ! inQuote; @@ -1365,7 +1365,7 @@ SimpleDateFormat::processOverrideString(const Locale &locale, const UnicodeStrin NSOverride *overrideList = nullptr; while (moreToProcess) { - int32_t delimiterPosition = str.indexOf((char16_t)ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE,start); + int32_t delimiterPosition = str.indexOf(static_cast(ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE), start); if (delimiterPosition == -1) { moreToProcess = false; len = str.length() - start; @@ -1373,7 +1373,7 @@ SimpleDateFormat::processOverrideString(const Locale &locale, const UnicodeStrin len = delimiterPosition - start; } UnicodeString currentString(str,start,len); - int32_t equalSignPosition = currentString.indexOf((char16_t)ULOC_KEYWORD_ASSIGN_UNICODE,0); + int32_t equalSignPosition = currentString.indexOf(static_cast(ULOC_KEYWORD_ASSIGN_UNICODE), 0); if (equalSignPosition == -1) { // Simple override string such as "hebrew" nsName.setTo(currentString); ovrField.setToBogus(); @@ -1991,7 +1991,7 @@ SimpleDateFormat::subFormat(UnicodeString &appendTo, if (periodType != DayPeriodRules::DAYPERIOD_AM && periodType != DayPeriodRules::DAYPERIOD_PM && periodType != DayPeriodRules::DAYPERIOD_MIDNIGHT) { - index = (int32_t)periodType; + index = static_cast(periodType); if (count <= 3) { toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short } else if (count == 4 || count > 5) { @@ -2009,7 +2009,7 @@ SimpleDateFormat::subFormat(UnicodeString &appendTo, (periodType == DayPeriodRules::DAYPERIOD_MIDNIGHT || periodType == DayPeriodRules::DAYPERIOD_NOON)) { periodType = ruleSet->getDayPeriodForHour(hour); - index = (int32_t)periodType; + index = static_cast(periodType); if (count <= 3) { toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short @@ -2419,7 +2419,7 @@ SimpleDateFormat::parse(const UnicodeString& text, Calendar& cal, ParsePosition& // If dayPeriod is set, use it in conjunction with hour-of-day to determine am/pm. if (dayPeriodInt >= 0) { - DayPeriodRules::DayPeriod dayPeriod = (DayPeriodRules::DayPeriod)dayPeriodInt; + DayPeriodRules::DayPeriod dayPeriod = static_cast(dayPeriodInt); const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status); if (!cal.isSet(UCAL_HOUR) && !cal.isSet(UCAL_HOUR_OF_DAY)) { @@ -2431,7 +2431,7 @@ SimpleDateFormat::parse(const UnicodeString& text, Calendar& cal, ParsePosition& if (U_SUCCESS(status)) { // Truncate midPoint toward zero to get the hour. // Any leftover means it was a half-hour. - int32_t midPointHour = (int32_t) midPoint; + int32_t midPointHour = static_cast(midPoint); int32_t midPointMinute = (midPoint - midPointHour) > 0 ? 30 : 0; // No need to set am/pm because hour-of-day is set last therefore takes precedence. @@ -3050,7 +3050,7 @@ int32_t SimpleDateFormat::subParse(const UnicodeString& text, int32_t& start, ch UnicodeString hebr("hebr", 4, US_INV); if (numericLeapMonthFormatter != nullptr) { - numericLeapMonthFormatter->setFormats((const Format **)¤tNumberFormat, 1); + numericLeapMonthFormatter->setFormats(reinterpret_cast(¤tNumberFormat), 1); } UBool isChineseCalendar = (uprv_strcmp(cal.getType(),"chinese") == 0 || uprv_strcmp(cal.getType(),"dangi") == 0); @@ -4361,7 +4361,7 @@ SimpleDateFormat::compareSimpleAffix(const UnicodeString& affix, int32_t SimpleDateFormat::skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const { const char16_t* s = text.getBuffer(); - return (int32_t)(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s); + return static_cast(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s); } //---------------------------------------------------------------------- diff --git a/icu4c/source/i18n/strmatch.cpp b/icu4c/source/i18n/strmatch.cpp index b6a5c94e98d4..1c8734c1a96d 100644 --- a/icu4c/source/i18n/strmatch.cpp +++ b/icu4c/source/i18n/strmatch.cpp @@ -165,7 +165,7 @@ UnicodeString& StringMatcher::toPattern(UnicodeString& result, result.truncate(0); UnicodeString str, quoteBuf; if (segmentNumber > 0) { - result.append((char16_t)40); /*(*/ + result.append(static_cast(40)); /*(*/ } for (int32_t i=0; i 0) { - result.append((char16_t)41); /*)*/ + result.append(static_cast(41)); /*)*/ } // Flush quoteBuf out to result ICU_Utility::appendToRule(result, -1, @@ -247,7 +247,7 @@ UnicodeString& StringMatcher::toReplacerPattern(UnicodeString& rule, UBool /*escapeUnprintable*/) const { // assert(segmentNumber > 0); rule.truncate(0); - rule.append((char16_t)0x0024 /*$*/); + rule.append(static_cast(0x0024) /*$*/); ICU_Utility::appendNumber(rule, segmentNumber, 10, 1); return rule; } diff --git a/icu4c/source/i18n/strrepl.cpp b/icu4c/source/i18n/strrepl.cpp index 2981553869a7..a3a0eae1e77f 100644 --- a/icu4c/source/i18n/strrepl.cpp +++ b/icu4c/source/i18n/strrepl.cpp @@ -149,7 +149,7 @@ int32_t StringReplacer::replace(Replaceable& text, text.copy(start-len, start, tempStart); destStart += len; } else { - UnicodeString str((char16_t) 0xFFFF); + UnicodeString str(static_cast(0xFFFF)); text.handleReplaceBetween(tempStart, tempStart, str); destStart++; } @@ -249,14 +249,14 @@ UnicodeString& StringReplacer::toReplacerPattern(UnicodeString& rule, // Handle a cursor preceding the output if (hasCursor && cursor < 0) { while (cursor++ < 0) { - ICU_Utility::appendToRule(rule, (char16_t)0x0040 /*@*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x0040) /*@*/, true, escapeUnprintable, quoteBuf); } // Fall through and append '|' below } for (int32_t i=0; i(0x007C) /*|*/, true, escapeUnprintable, quoteBuf); } char16_t c = output.charAt(i); // Ok to use 16-bits here @@ -266,8 +266,8 @@ UnicodeString& StringReplacer::toReplacerPattern(UnicodeString& rule, } else { UnicodeString buf; r->toReplacerPattern(buf, escapeUnprintable); - buf.insert(0, (char16_t)0x20); - buf.append((char16_t)0x20); + buf.insert(0, static_cast(0x20)); + buf.append(static_cast(0x20)); ICU_Utility::appendToRule(rule, buf, true, escapeUnprintable, quoteBuf); } @@ -279,9 +279,9 @@ UnicodeString& StringReplacer::toReplacerPattern(UnicodeString& rule, if (hasCursor && cursor > output.length()) { cursor -= output.length(); while (cursor-- > 0) { - ICU_Utility::appendToRule(rule, (char16_t)0x0040 /*@*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x0040) /*@*/, true, escapeUnprintable, quoteBuf); } - ICU_Utility::appendToRule(rule, (char16_t)0x007C /*|*/, true, escapeUnprintable, quoteBuf); + ICU_Utility::appendToRule(rule, static_cast(0x007C) /*|*/, true, escapeUnprintable, quoteBuf); } // Flush quoteBuf out to result ICU_Utility::appendToRule(rule, -1, diff --git a/icu4c/source/i18n/stsearch.cpp b/icu4c/source/i18n/stsearch.cpp index 3641d98e7c68..c41e8de21dc1 100644 --- a/icu4c/source/i18n/stsearch.cpp +++ b/icu4c/source/i18n/stsearch.cpp @@ -38,7 +38,7 @@ StringSearch::StringSearch(const UnicodeString &pattern, m_strsrch_ = usearch_open(m_pattern_.getBuffer(), m_pattern_.length(), m_text_.getBuffer(), m_text_.length(), - locale.getName(), (UBreakIterator *)breakiter, + locale.getName(), reinterpret_cast(breakiter), &status); uprv_free(m_search_); m_search_ = nullptr; @@ -70,7 +70,7 @@ StringSearch::StringSearch(const UnicodeString &pattern, m_pattern_.length(), m_text_.getBuffer(), m_text_.length(), coll->toUCollator(), - (UBreakIterator *)breakiter, + reinterpret_cast(breakiter), &status); uprv_free(m_search_); m_search_ = nullptr; @@ -95,7 +95,7 @@ StringSearch::StringSearch(const UnicodeString &pattern, } m_strsrch_ = usearch_open(m_pattern_.getBuffer(), m_pattern_.length(), m_text_.getBuffer(), m_text_.length(), - locale.getName(), (UBreakIterator *)breakiter, + locale.getName(), reinterpret_cast(breakiter), &status); uprv_free(m_search_); m_search_ = nullptr; @@ -127,7 +127,7 @@ StringSearch::StringSearch(const UnicodeString &pattern, m_pattern_.length(), m_text_.getBuffer(), m_text_.length(), coll->toUCollator(), - (UBreakIterator *)breakiter, + reinterpret_cast(breakiter), &status); uprv_free(m_search_); m_search_ = nullptr; @@ -159,7 +159,7 @@ StringSearch::StringSearch(const StringSearch &that) : m_text_.getBuffer(), m_text_.length(), that.m_strsrch_->collator, - (UBreakIterator *)that.m_breakiterator_, + reinterpret_cast(that.m_breakiterator_), &status); if (U_SUCCESS(status)) { // m_search_ has been created by the base SearchIterator class diff --git a/icu4c/source/i18n/timezone.cpp b/icu4c/source/i18n/timezone.cpp index a9fb316a15ab..064bf83cb7b8 100644 --- a/icu4c/source/i18n/timezone.cpp +++ b/icu4c/source/i18n/timezone.cpp @@ -195,7 +195,7 @@ static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id).getTerminatedBuffer()), start, limit)); for (;;) { - mid = (int32_t)((start + limit) / 2); + mid = static_cast((start + limit) / 2); if (lastMid == mid) { /* Have we moved? */ break; /* We haven't moved, and it wasn't found. */ } @@ -258,7 +258,7 @@ static UResourceBundle* getZoneByName(const UResourceBundle* top, const UnicodeS UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) { char key[64]; - ruleid.extract(0, sizeof(key)-1, key, (int32_t)sizeof(key)-1, US_INV); + ruleid.extract(0, sizeof(key) - 1, key, static_cast(sizeof(key)) - 1, US_INV); U_DEBUG_TZ_MSG(("loadRule(%s)\n", key)); UResourceBundle *r = ures_getByKey(top, kRULES, oldbundle, &status); U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key, u_errorName(status))); @@ -630,7 +630,7 @@ static void U_CALLCONV initMap(USystemTimeZoneType type, UErrorCode& ec) { res = ures_getByKey(res, kNAMES, res, &ec); // dereference Zones section if (U_SUCCESS(ec)) { int32_t size = ures_getSize(res); - int32_t *m = (int32_t *)uprv_malloc(size * sizeof(int32_t)); + int32_t* m = static_cast(uprv_malloc(size * sizeof(int32_t))); if (m == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; } else { @@ -669,7 +669,7 @@ static void U_CALLCONV initMap(USystemTimeZoneType type, UErrorCode& ec) { } if (U_SUCCESS(ec)) { int32_t *tmp = m; - m = (int32_t *)uprv_realloc(tmp, numEntries * sizeof(int32_t)); + m = static_cast(uprv_realloc(tmp, numEntries * sizeof(int32_t))); if (m == nullptr) { // realloc failed.. use the original one even it has unused // area at the end @@ -742,7 +742,7 @@ void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset, if (U_FAILURE(ec)) return; dstOffset = getOffset(GregorianCalendar::AD, year, month, dom, - (uint8_t) dow, millis, + static_cast(dow), millis, Grego::monthLength(year, month), ec) - rawOffset; @@ -849,7 +849,7 @@ class TZEnumeration : public StringEnumeration { if (region != nullptr || rawOffset != nullptr) { int32_t filteredMapSize = DEFAULT_FILTERED_MAP_SIZE; - filteredMap = (int32_t *)uprv_malloc(filteredMapSize * sizeof(int32_t)); + filteredMap = static_cast(uprv_malloc(filteredMapSize * sizeof(int32_t))); if (filteredMap == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -893,7 +893,7 @@ class TZEnumeration : public StringEnumeration { if (filteredMapSize <= numEntries) { filteredMapSize += MAP_INCREMENT_SIZE; - int32_t *tmp = (int32_t *)uprv_realloc(filteredMap, filteredMapSize * sizeof(int32_t)); + int32_t* tmp = static_cast(uprv_realloc(filteredMap, filteredMapSize * sizeof(int32_t))); if (tmp == nullptr) { ec = U_MEMORY_ALLOCATION_ERROR; break; @@ -936,7 +936,7 @@ class TZEnumeration : public StringEnumeration { TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(nullptr), localMap(nullptr), len(0), pos(0) { if (other.localMap != nullptr) { - localMap = (int32_t *)uprv_malloc(other.len * sizeof(int32_t)); + localMap = static_cast(uprv_malloc(other.len * sizeof(int32_t))); if (localMap != nullptr) { len = other.len; uprv_memcpy(localMap, other.localMap, len * sizeof(int32_t)); @@ -1473,33 +1473,33 @@ TimeZone::formatCustomID(int32_t hour, int32_t min, int32_t sec, id.setTo(GMT_ID, GMT_ID_LENGTH); if (hour | min | sec) { if (negative) { - id += (char16_t)MINUS; + id += static_cast(MINUS); } else { - id += (char16_t)PLUS; + id += static_cast(PLUS); } if (hour < 10) { - id += (char16_t)ZERO_DIGIT; + id += static_cast(ZERO_DIGIT); } else { - id += (char16_t)(ZERO_DIGIT + hour/10); + id += static_cast(ZERO_DIGIT + hour / 10); } - id += (char16_t)(ZERO_DIGIT + hour%10); - id += (char16_t)COLON; + id += static_cast(ZERO_DIGIT + hour % 10); + id += static_cast(COLON); if (min < 10) { - id += (char16_t)ZERO_DIGIT; + id += static_cast(ZERO_DIGIT); } else { - id += (char16_t)(ZERO_DIGIT + min/10); + id += static_cast(ZERO_DIGIT + min / 10); } - id += (char16_t)(ZERO_DIGIT + min%10); + id += static_cast(ZERO_DIGIT + min % 10); if (sec) { - id += (char16_t)COLON; + id += static_cast(COLON); if (sec < 10) { - id += (char16_t)ZERO_DIGIT; + id += static_cast(ZERO_DIGIT); } else { - id += (char16_t)(ZERO_DIGIT + sec/10); + id += static_cast(ZERO_DIGIT + sec / 10); } - id += (char16_t)(ZERO_DIGIT + sec%10); + id += static_cast(ZERO_DIGIT + sec % 10); } } return id; @@ -1521,7 +1521,7 @@ static void U_CALLCONV initTZDataVersion(UErrorCode &status) { const char16_t *tzver = ures_getStringByKey(bundle.getAlias(), kTZVERSION, &len, &status); if (U_SUCCESS(status)) { - if (len >= (int32_t)sizeof(TZDATA_VERSION)) { + if (len >= static_cast(sizeof(TZDATA_VERSION))) { // Ensure that there is always space for a trailing nul in TZDATA_VERSION len = sizeof(TZDATA_VERSION) - 1; } @@ -1642,7 +1642,7 @@ TimeZone::getWindowsID(const UnicodeString& id, UnicodeString& winid, UErrorCode const char16_t *start = tzids; UBool hasNext = true; while (hasNext) { - const char16_t *end = u_strchr(start, (char16_t)0x20); + const char16_t* end = u_strchr(start, static_cast(0x20)); if (end == nullptr) { end = tzids + len; hasNext = false; @@ -1683,7 +1683,7 @@ TimeZone::getIDForWindowsID(const UnicodeString& winid, const char* region, Unic char winidKey[MAX_WINDOWS_ID_SIZE]; int32_t winKeyLen = winid.extract(0, winid.length(), winidKey, sizeof(winidKey) - 1, US_INV); - if (winKeyLen == 0 || winKeyLen >= (int32_t)sizeof(winidKey)) { + if (winKeyLen == 0 || winKeyLen >= static_cast(sizeof(winidKey))) { ures_close(zones); return id; } @@ -1704,7 +1704,7 @@ TimeZone::getIDForWindowsID(const UnicodeString& winid, const char* region, Unic // regional mapping is optional if (U_SUCCESS(tmperr)) { // first ID delimited by space is the default one - const char16_t *end = u_strchr(tzids, (char16_t)0x20); + const char16_t* end = u_strchr(tzids, static_cast(0x20)); if (end == nullptr) { id.setTo(tzids, -1); } else { diff --git a/icu4c/source/i18n/titletrn.cpp b/icu4c/source/i18n/titletrn.cpp index d3732893a78c..4f2baa00708c 100644 --- a/icu4c/source/i18n/titletrn.cpp +++ b/icu4c/source/i18n/titletrn.cpp @@ -132,7 +132,7 @@ void TitlecaseTransliterator::handleTransliterate( } else { result=ucase_toFullLower(c, utrans_rep_caseContextIterator, &csc, &s, UCASE_LOC_ROOT); } - doTitle = (UBool)(type==0); // doTitle=isUncased + doTitle = static_cast(type == 0); // doTitle=isUncased if(csc.b1 && isIncremental) { // fMap() tried to look beyond the context limit diff --git a/icu4c/source/i18n/tmutfmt.cpp b/icu4c/source/i18n/tmutfmt.cpp index 9f7bc89eeb27..f96ab4322647 100644 --- a/icu4c/source/i18n/tmutfmt.cpp +++ b/icu4c/source/i18n/tmutfmt.cpp @@ -116,7 +116,7 @@ TimeUnitFormat::TimeUnitFormat(const TimeUnitFormat& other) { for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { UErrorCode status = U_ZERO_ERROR; fTimeUnitToCountToPatterns[i] = initHash(status); if (U_SUCCESS(status)) { @@ -132,7 +132,7 @@ TimeUnitFormat::TimeUnitFormat(const TimeUnitFormat& other) TimeUnitFormat::~TimeUnitFormat() { for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { deleteHash(fTimeUnitToCountToPatterns[i]); fTimeUnitToCountToPatterns[i] = nullptr; } @@ -153,13 +153,13 @@ TimeUnitFormat::operator=(const TimeUnitFormat& other) { MeasureFormat::operator=(other); for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { deleteHash(fTimeUnitToCountToPatterns[i]); fTimeUnitToCountToPatterns[i] = nullptr; } for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { UErrorCode status = U_ZERO_ERROR; fTimeUnitToCountToPatterns[i] = initHash(status); if (U_SUCCESS(status)) { @@ -193,22 +193,22 @@ TimeUnitFormat::parseObject(const UnicodeString& source, // and looking for the longest match. for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { Hashtable* countToPatterns = fTimeUnitToCountToPatterns[i]; int32_t elemPos = UHASH_FIRST; const UHashElement* elem = nullptr; while ((elem = countToPatterns->nextElement(elemPos)) != nullptr){ const UHashTok keyTok = elem->key; - UnicodeString* count = (UnicodeString*)keyTok.pointer; + UnicodeString* count = static_cast(keyTok.pointer); #ifdef TMUTFMT_DEBUG count->extract(0, count->length(), res, "UTF-8"); std::cout << "parse plural count: " << res << "\n"; #endif const UHashTok valueTok = elem->value; // the value is a pair of MessageFormat* - MessageFormat** patterns = (MessageFormat**)valueTok.pointer; + MessageFormat** patterns = static_cast(valueTok.pointer); for (UTimeUnitFormatStyle style = UTMUTFMT_FULL_STYLE; style < UTMUTFMT_FORMAT_STYLE_COUNT; - style = (UTimeUnitFormatStyle)(style + 1)) { + style = static_cast(style + 1)) { MessageFormat* pattern = patterns[style]; pos.setErrorIndex(-1); pos.setIndex(oldPos); @@ -295,7 +295,7 @@ TimeUnitFormat::create(UTimeUnitFormatStyle style, UErrorCode& status) { // before checking for failure status. for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { fTimeUnitToCountToPatterns[i] = nullptr; } @@ -346,7 +346,7 @@ TimeUnitFormat::initDataMembers(UErrorCode& err){ } for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; - i = (TimeUnit::UTimeUnitFields)(i+1)) { + i = static_cast(i + 1)) { deleteHash(fTimeUnitToCountToPatterns[i]); fTimeUnitToCountToPatterns[i] = nullptr; } @@ -432,10 +432,10 @@ struct TimeUnitFormatReadSink : public ResourceSink { return; } MessageFormat** formatters = - (MessageFormat**)countToPatterns->get(pluralCountUniStr); + static_cast(countToPatterns->get(pluralCountUniStr)); if (formatters == nullptr) { LocalMemory localFormatters( - (MessageFormat **)uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT*sizeof(MessageFormat*))); + static_cast(uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT * sizeof(MessageFormat*)))); if (localFormatters.isNull()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; @@ -521,14 +521,14 @@ TimeUnitFormat::checkConsistency(UTimeUnitFormatStyle style, const char* key, UE return; } } - MessageFormat** formatters = (MessageFormat**)countToPatterns->get(*pluralCount); + MessageFormat** formatters = static_cast(countToPatterns->get(*pluralCount)); if( formatters == nullptr || formatters[style] == nullptr ) { // look through parents const char* localeName = getLocaleID(err); CharString pluralCountChars; pluralCountChars.appendInvariantChars(*pluralCount, err); searchInLocaleChain(style, key, localeName, - (TimeUnit::UTimeUnitFields)i, + static_cast(i), *pluralCount, pluralCountChars.data(), countToPatterns, err); } @@ -578,10 +578,10 @@ TimeUnitFormat::searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, if (U_FAILURE(err)) { return; } - MessageFormat** formatters = (MessageFormat**)countToPatterns->get(srcPluralCount); + MessageFormat** formatters = static_cast(countToPatterns->get(srcPluralCount)); if (formatters == nullptr) { LocalMemory localFormatters( - (MessageFormat**)uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT*sizeof(MessageFormat*))); + static_cast(uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT * sizeof(MessageFormat*)))); formatters = localFormatters.getAlias(); localFormatters[UTMUTFMT_FULL_STYLE] = nullptr; localFormatters[UTMUTFMT_ABBREVIATED_STYLE] = nullptr; @@ -615,7 +615,7 @@ TimeUnitFormat::searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, if (U_FAILURE(err)) { return; } - MessageFormat** formatters = (MessageFormat**)countToPatterns->get(srcPluralCount); + MessageFormat** formatters = static_cast(countToPatterns->get(srcPluralCount)); if (formatters != nullptr && formatters[style] != nullptr) { return; } @@ -649,10 +649,10 @@ TimeUnitFormat::searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, if (U_FAILURE(err)) { return; } - MessageFormat** formatters = (MessageFormat**)countToPatterns->get(srcPluralCount); + MessageFormat** formatters = static_cast(countToPatterns->get(srcPluralCount)); if (formatters == nullptr) { LocalMemory localFormatters ( - (MessageFormat**)uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT*sizeof(MessageFormat*))); + static_cast(uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT * sizeof(MessageFormat*)))); if (localFormatters.isNull()) { err = U_MEMORY_ALLOCATION_ERROR; return; @@ -697,7 +697,7 @@ TimeUnitFormat::deleteHash(Hashtable* htable) { if ( htable ) { while ( (element = htable->nextElement(pos)) != nullptr ) { const UHashTok valueTok = element->value; - const MessageFormat** value = (const MessageFormat**)valueTok.pointer; + const MessageFormat** value = static_cast(valueTok.pointer); delete value[UTMUTFMT_FULL_STYLE]; delete value[UTMUTFMT_ABBREVIATED_STYLE]; //delete[] value; @@ -718,10 +718,10 @@ TimeUnitFormat::copyHash(const Hashtable* source, Hashtable* target, UErrorCode& if ( source ) { while ( (element = source->nextElement(pos)) != nullptr ) { const UHashTok keyTok = element->key; - const UnicodeString* key = (UnicodeString*)keyTok.pointer; + const UnicodeString* key = static_cast(keyTok.pointer); const UHashTok valueTok = element->value; - const MessageFormat** value = (const MessageFormat**)valueTok.pointer; - MessageFormat** newVal = (MessageFormat**)uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT*sizeof(MessageFormat*)); + const MessageFormat** value = static_cast(valueTok.pointer); + MessageFormat** newVal = static_cast(uprv_malloc(UTMUTFMT_FORMAT_STYLE_COUNT * sizeof(MessageFormat*))); newVal[0] = value[0]->clone(); newVal[1] = value[1]->clone(); target->put(UnicodeString(*key), newVal, status); diff --git a/icu4c/source/i18n/translit.cpp b/icu4c/source/i18n/translit.cpp index 42256140b174..7b1e9f57135a 100644 --- a/icu4c/source/i18n/translit.cpp +++ b/icu4c/source/i18n/translit.cpp @@ -132,7 +132,7 @@ Transliterator::Transliterator(const UnicodeString& theID, maximumContextLength(0) { // NUL-terminate the ID string, which is a non-aliased copy. - ID.append((char16_t)0); + ID.append(static_cast(0)); ID.truncate(ID.length()-1); } @@ -151,7 +151,7 @@ Transliterator::Transliterator(const Transliterator& other) : maximumContextLength(other.maximumContextLength) { // NUL-terminate the ID string, which is a non-aliased copy. - ID.append((char16_t)0); + ID.append(static_cast(0)); ID.truncate(ID.length()-1); if (other.filter != nullptr) { @@ -759,8 +759,8 @@ UnicodeString& U_EXPORT2 Transliterator::getDisplayName(const UnicodeString& id, if (uprv_isInvariantUString(ID.getBuffer(), ID.length())) { char key[200]; uprv_strcpy(key, RB_DISPLAY_NAME_PREFIX); - int32_t length=(int32_t)uprv_strlen(RB_DISPLAY_NAME_PREFIX); - ID.extract(0, (int32_t)(sizeof(key)-length), key+length, (int32_t)(sizeof(key)-length), US_INV); + int32_t length = static_cast(uprv_strlen(RB_DISPLAY_NAME_PREFIX)); + ID.extract(0, static_cast(sizeof(key) - length), key + length, static_cast(sizeof(key) - length), US_INV); // Try to retrieve a UnicodeString from the bundle. UnicodeString resString = bundle.getStringEx(key, status); @@ -793,13 +793,13 @@ UnicodeString& U_EXPORT2 Transliterator::getDisplayName(const UnicodeString& id, // Use display names for the scripts, if they exist UnicodeString s; - length=(int32_t)uprv_strlen(RB_SCRIPT_DISPLAY_NAME_PREFIX); + length = static_cast(uprv_strlen(RB_SCRIPT_DISPLAY_NAME_PREFIX)); for (int j=1; j<=2; ++j) { status = U_ZERO_ERROR; uprv_strcpy(key, RB_SCRIPT_DISPLAY_NAME_PREFIX); args[j].getString(s); if (uprv_isInvariantUString(s.getBuffer(), s.length())) { - s.extract(0, sizeof(key)-length-1, key+length, (int32_t)sizeof(key)-length-1, US_INV); + s.extract(0, sizeof(key) - length - 1, key + length, static_cast(sizeof(key)) - length - 1, US_INV); resString = bundle.getStringEx(key, status); @@ -949,7 +949,7 @@ Transliterator::createInstance(const UnicodeString& ID, t = new CompoundTransliterator(list, parseError, status); } else { - t = (Transliterator*)list.elementAt(0); + t = static_cast(list.elementAt(0)); } // Check null pointer if (t != nullptr) { @@ -1068,7 +1068,7 @@ Transliterator::createFromRules(const UnicodeString& ID, t = new NullTransliterator(); } else if (parser.idBlockVector.size() == 0 && parser.dataVector.size() == 1) { - t = new RuleBasedTransliterator(ID, (TransliterationRuleData*)parser.dataVector.orphanElementAt(0), true); + t = new RuleBasedTransliterator(ID, static_cast(parser.dataVector.orphanElementAt(0)), true); } else if (parser.idBlockVector.size() == 1 && parser.dataVector.size() == 0) { // idBlock, no data -- this is an alias. The ID has @@ -1079,10 +1079,10 @@ Transliterator::createFromRules(const UnicodeString& ID, UnicodeString filterPattern; parser.compoundFilter->toPattern(filterPattern, false); t = createInstance(filterPattern + UnicodeString(ID_DELIM) - + *((UnicodeString*)parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status); + + *static_cast(parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status); } else - t = createInstance(*((UnicodeString*)parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status); + t = createInstance(*static_cast(parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status); if (t != nullptr) { @@ -1101,7 +1101,7 @@ Transliterator::createFromRules(const UnicodeString& ID, for (int32_t i = 0; i < limit; i++) { if (i < parser.idBlockVector.size()) { - UnicodeString* idBlock = (UnicodeString*)parser.idBlockVector.elementAt(i); + UnicodeString* idBlock = static_cast(parser.idBlockVector.elementAt(i)); if (!idBlock->isEmpty()) { Transliterator* temp = createInstance(*idBlock, UTRANS_FORWARD, parseError, status); if (U_FAILURE(status)) { @@ -1120,7 +1120,7 @@ Transliterator::createFromRules(const UnicodeString& ID, } } if (!parser.dataVector.isEmpty()) { - TransliterationRuleData* data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0); + TransliterationRuleData* data = static_cast(parser.dataVector.orphanElementAt(0)); // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")? RuleBasedTransliterator* temprbt = new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING) + UnicodeString(passNumber++), data, true); diff --git a/icu4c/source/i18n/transreg.cpp b/icu4c/source/i18n/transreg.cpp index 226edc6ff9ad..5f050f2e2bd3 100644 --- a/icu4c/source/i18n/transreg.cpp +++ b/icu4c/source/i18n/transreg.cpp @@ -142,8 +142,8 @@ Transliterator* TransliteratorAlias::create(UParseError& pe, // to see whether there really are ID blocks at the beginning and end (by looking for U+FFFF, which // marks the position where an anonymous transliterator goes) and adjust accordingly int32_t anonymousRBTs = transes->size(); - UnicodeString noIDBlock((char16_t)(0xffff)); - noIDBlock += ((char16_t)(0xffff)); + UnicodeString noIDBlock(static_cast(0xffff)); + noIDBlock += static_cast(0xffff); int32_t pos = aliasesOrRules.indexOf(noIDBlock); while (pos >= 0) { pos = aliasesOrRules.indexOf(noIDBlock, pos + 1); @@ -151,7 +151,7 @@ Transliterator* TransliteratorAlias::create(UParseError& pe, UVector transliterators(uprv_deleteUObject, nullptr, ec); UnicodeString idBlock; - int32_t blockSeparatorPos = aliasesOrRules.indexOf((char16_t)(0xffff)); + int32_t blockSeparatorPos = aliasesOrRules.indexOf(static_cast(0xffff)); while (blockSeparatorPos >= 0) { aliasesOrRules.extract(0, blockSeparatorPos, idBlock); aliasesOrRules.remove(0, blockSeparatorPos + 1); @@ -159,7 +159,7 @@ Transliterator* TransliteratorAlias::create(UParseError& pe, transliterators.adoptElement(Transliterator::createInstance(idBlock, UTRANS_FORWARD, pe, ec), ec); if (!transes->isEmpty()) transliterators.adoptElement(transes->orphanElementAt(0), ec); - blockSeparatorPos = aliasesOrRules.indexOf((char16_t)(0xffff)); + blockSeparatorPos = aliasesOrRules.indexOf(static_cast(0xffff)); } if (!aliasesOrRules.isEmpty()) transliterators.adoptElement(Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec), ec); @@ -177,7 +177,7 @@ Transliterator* TransliteratorAlias::create(UParseError& pe, } } else { for (int32_t i = 0; i < transliterators.size(); i++) - delete (Transliterator*)(transliterators.elementAt(i)); + delete static_cast(transliterators.elementAt(i)); } } break; @@ -492,7 +492,7 @@ TransliteratorEntry::~TransliteratorEntry() { delete u.data; } else if (entryType == COMPOUND_RBT) { while (u.dataVector != nullptr && !u.dataVector->isEmpty()) - delete (TransliterationRuleData*)u.dataVector->orphanElementAt(0); + delete static_cast(u.dataVector->orphanElementAt(0)); delete u.dataVector; } delete compoundFilter; @@ -593,11 +593,11 @@ Transliterator* TransliteratorRegistry::reget(const UnicodeString& ID, entry->stringArg = UNICODE_STRING_SIMPLE("Any-nullptr"); } else if (parser.idBlockVector.isEmpty() && parser.dataVector.size() == 1) { - entry->u.data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0); + entry->u.data = static_cast(parser.dataVector.orphanElementAt(0)); entry->entryType = TransliteratorEntry::RBT_DATA; } else if (parser.idBlockVector.size() == 1 && parser.dataVector.isEmpty()) { - entry->stringArg = *(UnicodeString*)(parser.idBlockVector.elementAt(0)); + entry->stringArg = *static_cast(parser.idBlockVector.elementAt(0)); entry->compoundFilter = parser.orphanCompoundFilter(); entry->entryType = TransliteratorEntry::ALIAS; } @@ -615,17 +615,17 @@ Transliterator* TransliteratorRegistry::reget(const UnicodeString& ID, for (int32_t i = 0; i < limit; i++) { if (i < parser.idBlockVector.size()) { - UnicodeString* idBlock = (UnicodeString*)parser.idBlockVector.elementAt(i); + UnicodeString* idBlock = static_cast(parser.idBlockVector.elementAt(i)); if (!idBlock->isEmpty()) entry->stringArg += *idBlock; } if (!parser.dataVector.isEmpty()) { - TransliterationRuleData* data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0); + TransliterationRuleData* data = static_cast(parser.dataVector.orphanElementAt(0)); entry->u.dataVector->addElement(data, status); if (U_FAILURE(status)) { delete data; } - entry->stringArg += (char16_t)0xffff; // use U+FFFF to mark position of RBTs in ID block + entry->stringArg += static_cast(0xffff); // use U+FFFF to mark position of RBTs in ID block } } } @@ -751,7 +751,7 @@ const UnicodeString& TransliteratorRegistry::getAvailableID(int32_t index) const } if (e != nullptr) { - return *(UnicodeString*) e->key.pointer; + return *static_cast(e->key.pointer); } // If the code reaches here, the hash table was likely modified during iteration. @@ -781,20 +781,20 @@ UnicodeString& TransliteratorRegistry::getAvailableSource(int32_t index, if (e == nullptr) { result.truncate(0); } else { - result = *(UnicodeString*) e->key.pointer; + result = *static_cast(e->key.pointer); } return result; } int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString& source) const { - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); return (targets == nullptr) ? 0 : targets->count(); } UnicodeString& TransliteratorRegistry::getAvailableTarget(int32_t index, const UnicodeString& source, UnicodeString& result) const { - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); if (targets == nullptr) { result.truncate(0); // invalid source return result; @@ -810,14 +810,14 @@ UnicodeString& TransliteratorRegistry::getAvailableTarget(int32_t index, if (e == nullptr) { result.truncate(0); // invalid index } else { - result = *(UnicodeString*) e->key.pointer; + result = *static_cast(e->key.pointer); } return result; } int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString& source, const UnicodeString& target) const { - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); if (targets == nullptr) { return 0; } @@ -836,7 +836,7 @@ UnicodeString& TransliteratorRegistry::getAvailableVariant(int32_t index, const UnicodeString& source, const UnicodeString& target, UnicodeString& result) const { - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); if (targets == nullptr) { result.truncate(0); // invalid source return result; @@ -847,7 +847,7 @@ UnicodeString& TransliteratorRegistry::getAvailableVariant(int32_t index, while (varMask > 0) { if (varMask & 1) { if (varCount == index) { - UnicodeString *v = (UnicodeString*) variantList.elementAt(varListIndex); + UnicodeString* v = static_cast(variantList.elementAt(varListIndex)); if (v != nullptr) { result = *v; return result; @@ -905,7 +905,7 @@ const UnicodeString* TransliteratorRegistry::Enumeration::snext(UErrorCode& stat } // Copy the string! This avoids lifetime problems. - unistr = *(const UnicodeString*) element->key.pointer; + unistr = *static_cast(element->key.pointer); return &unistr; } @@ -985,7 +985,7 @@ void TransliteratorRegistry::registerSTV(const UnicodeString& source, // assert(source.length() > 0); // assert(target.length() > 0); UErrorCode status = U_ZERO_ERROR; - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); if (targets == nullptr) { int32_t size = 3; if (source.compare(ANY,3) == 0) { @@ -1030,7 +1030,7 @@ void TransliteratorRegistry::removeSTV(const UnicodeString& source, // assert(source.length() > 0); // assert(target.length() > 0); UErrorCode status = U_ZERO_ERROR; - Hashtable *targets = (Hashtable*) specDAG.get(source); + Hashtable* targets = static_cast(specDAG.get(source)); if (targets == nullptr) { return; // should never happen for valid s-t/v } @@ -1065,7 +1065,7 @@ TransliteratorEntry* TransliteratorRegistry::findInDynamicStore(const Transliter const UnicodeString& variant) const { UnicodeString ID; TransliteratorIDParser::STVtoID(src, trg, variant, ID); - TransliteratorEntry *e = (TransliteratorEntry*) registry.get(ID); + TransliteratorEntry* e = static_cast(registry.get(ID)); DEBUG_useEntry(e); return e; } @@ -1239,7 +1239,7 @@ TransliteratorEntry* TransliteratorRegistry::find(UnicodeString& source, // ICU ticket #8089 UnicodeString ID; TransliteratorIDParser::STVtoID(source, target, variant, ID); - entry = (TransliteratorEntry*) registry.get(ID); + entry = static_cast(registry.get(ID)); if (entry != nullptr) { // std::string ss; // std::cout << ID.toUTF8String(ss) << std::endl; @@ -1345,7 +1345,7 @@ Transliterator* TransliteratorRegistry::instantiateEntry(const UnicodeString& ID for (int32_t i = 0; U_SUCCESS(status) && i < entry->u.dataVector->size(); i++) { // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")? Transliterator* tl = new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING) + UnicodeString(passNumber++), - (TransliterationRuleData*)(entry->u.dataVector->elementAt(i)), false); + static_cast(entry->u.dataVector->elementAt(i)), false); if (tl == nullptr) status = U_MEMORY_ALLOCATION_ERROR; else @@ -1364,7 +1364,7 @@ Transliterator* TransliteratorRegistry::instantiateEntry(const UnicodeString& ID return nullptr; case TransliteratorEntry::LOCALE_RULES: aliasReturn = new TransliteratorAlias(ID, entry->stringArg, - (UTransDirection) entry->intArg); + static_cast(entry->intArg)); if (aliasReturn == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } diff --git a/icu4c/source/i18n/tridpars.cpp b/icu4c/source/i18n/tridpars.cpp index 40f21b452153..5c769dc39fbc 100644 --- a/icu4c/source/i18n/tridpars.cpp +++ b/icu4c/source/i18n/tridpars.cpp @@ -413,7 +413,7 @@ UBool TransliteratorIDParser::parseCompoundID(const UnicodeString& id, int32_t d // Construct canonical ID for (i=0; i(list.elementAt(i)); canonID.append(single->canonID); if (i != (list.size()-1)) { canonID.append(ID_DELIM); @@ -489,7 +489,7 @@ void TransliteratorIDParser::instantiateList(UVector& list, break; } - SingleID* single = (SingleID*) list.elementAt(i); + SingleID* single = static_cast(list.elementAt(i)); if (single->basicID.length() != 0) { t = single->createInstance(); if (t == nullptr) { @@ -522,7 +522,7 @@ void TransliteratorIDParser::instantiateList(UVector& list, list.setDeleter(_deleteTransliteratorTrIDPars); while (tlist.size() > 0) { - t = (Transliterator*) tlist.orphanElementAt(0); + t = static_cast(tlist.orphanElementAt(0)); list.adoptElement(t, ec); if (U_FAILURE(ec)) { list.removeAllElements(); @@ -607,7 +607,7 @@ void TransliteratorIDParser::STVtoID(const UnicodeString& source, } // NUL-terminate the ID string for getTerminatedBuffer. // This prevents valgrind and Purify warnings. - id.append((char16_t)0); + id.append(static_cast(0)); id.truncate(id.length()-1); } @@ -862,7 +862,7 @@ TransliteratorIDParser::specsToSpecialInverse(const Specs& specs, UErrorCode &st UnicodeString* inverseTarget; umtx_lock(&LOCK); - inverseTarget = (UnicodeString*) SPECIAL_INVERSES->get(specs.target); + inverseTarget = static_cast(SPECIAL_INVERSES->get(specs.target)); umtx_unlock(&LOCK); if (inverseTarget != nullptr) { diff --git a/icu4c/source/i18n/tzfmt.cpp b/icu4c/source/i18n/tzfmt.cpp index 00c69ee77346..0fb6336b86de 100644 --- a/icu4c/source/i18n/tzfmt.cpp +++ b/icu4c/source/i18n/tzfmt.cpp @@ -225,7 +225,7 @@ GMTOffsetField::createText(const UnicodeString& text, UErrorCode& status) { } int32_t len = text.length(); - result->fText = (char16_t*)uprv_malloc((len + 1) * sizeof(char16_t)); + result->fText = static_cast(uprv_malloc((len + 1) * sizeof(char16_t))); if (result->fText == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; delete result; @@ -331,7 +331,7 @@ TimeZoneFormat::TimeZoneFormat(const Locale& locale, UErrorCode& status) } else { fTargetRegion[0] = 0; } - } else if (regionLen < (int32_t)sizeof(fTargetRegion)) { + } else if (regionLen < static_cast(sizeof(fTargetRegion))) { uprv_strcpy(fTargetRegion, region); } else { fTargetRegion[0] = 0; @@ -374,10 +374,10 @@ TimeZoneFormat::TimeZoneFormat(const Locale& locale, UErrorCode& status) UBool useDefaultOffsetPatterns = true; if (hourFormats) { - char16_t *sep = u_strchr(hourFormats, (char16_t)0x003B /* ';' */); + char16_t* sep = u_strchr(hourFormats, static_cast(0x003B) /* ';' */); if (sep != nullptr) { UErrorCode tmpStatus = U_ZERO_ERROR; - fGMTOffsetPatterns[UTZFMT_PAT_POSITIVE_HM].setTo(false, hourFormats, (int32_t)(sep - hourFormats)); + fGMTOffsetPatterns[UTZFMT_PAT_POSITIVE_HM].setTo(false, hourFormats, static_cast(sep - hourFormats)); fGMTOffsetPatterns[UTZFMT_PAT_NEGATIVE_HM].setTo(true, sep + 1, -1); expandOffsetPattern(fGMTOffsetPatterns[UTZFMT_PAT_POSITIVE_HM], fGMTOffsetPatterns[UTZFMT_PAT_POSITIVE_HMS], tmpStatus); expandOffsetPattern(fGMTOffsetPatterns[UTZFMT_PAT_NEGATIVE_HM], fGMTOffsetPatterns[UTZFMT_PAT_NEGATIVE_HMS], tmpStatus); @@ -1342,7 +1342,7 @@ TimeZoneFormat::formatGeneric(const TimeZone& tz, int32_t genType, UDate date, U } return gnames->getGenericLocationName(UnicodeString(true, canonicalID, -1), name); } - return gnames->getDisplayName(tz, (UTimeZoneGenericNameType)genType, date, name); + return gnames->getDisplayName(tz, static_cast(genType), date, name); } UnicodeString& @@ -1540,8 +1540,8 @@ TimeZoneFormat::formatOffsetISO8601(int32_t offset, UBool isBasic, UBool useUtcI if (sep && idx != 0) { result.append(sep); } - result.append((char16_t)(0x0030 + fields[idx]/10)); - result.append((char16_t)(0x0030 + fields[idx]%10)); + result.append(static_cast(0x0030 + fields[idx] / 10)); + result.append(static_cast(0x0030 + fields[idx] % 10)); } return result; @@ -1603,7 +1603,7 @@ TimeZoneFormat::formatOffsetLocalizedGMT(int32_t offset, UBool isShort, UnicodeS result.setTo(fGMTPatternPrefix); for (int32_t i = 0; i < offsetPatternItems->size(); i++) { - const GMTOffsetField* item = (GMTOffsetField*)offsetPatternItems->elementAt(i); + const GMTOffsetField* item = static_cast(offsetPatternItems->elementAt(i)); GMTOffsetField::FieldType type = item->getType(); switch (type) { @@ -1641,7 +1641,7 @@ TimeZoneFormat::parseOffsetISO8601(const UnicodeString& text, ParsePosition& pos } char16_t firstChar = text.charAt(start); - if (firstChar == ISO8601_UTC || firstChar == (char16_t)(ISO8601_UTC + 0x20)) { + if (firstChar == ISO8601_UTC || firstChar == static_cast(ISO8601_UTC + 0x20)) { // "Z" (or "z") - indicates UTC pos.setIndex(start + 1); return 0; @@ -1856,7 +1856,7 @@ TimeZoneFormat::parseOffsetFieldsWithPattern(const UnicodeString& text, int32_t for (int32_t i = 0; i < patternItems->size(); i++) { int32_t len = 0; - const GMTOffsetField* field = (const GMTOffsetField*)patternItems->elementAt(i); + const GMTOffsetField* field = static_cast(patternItems->elementAt(i)); GMTOffsetField::FieldType fieldType = field->getType(); if (fieldType == GMTOffsetField::TEXT) { const char16_t* patStr = field->getPatternText(); @@ -2191,8 +2191,8 @@ TimeZoneFormat::formatOffsetWithAsciiDigits(int32_t offset, char16_t sep, Offset if (sep && idx != 0) { result.append(sep); } - result.append((char16_t)(0x0030 + fields[idx]/10)); - result.append((char16_t)(0x0030 + fields[idx]%10)); + result.append(static_cast(0x0030 + fields[idx] / 10)); + result.append(static_cast(0x0030 + fields[idx] % 10)); } return result; @@ -2577,7 +2577,7 @@ TimeZoneFormat::expandOffsetPattern(const UnicodeString& offsetHM, UnicodeString } UnicodeString sep; - int32_t idx_H = offsetHM.tempSubString(0, idx_mm).lastIndexOf((char16_t)0x0048 /* H */); + int32_t idx_H = offsetHM.tempSubString(0, idx_mm).lastIndexOf(static_cast(0x0048) /* H */); if (idx_H >= 0) { sep = offsetHM.tempSubString(idx_H + 1, idx_mm - (idx_H + 1)); } @@ -2607,7 +2607,7 @@ TimeZoneFormat::truncateOffsetPattern(const UnicodeString& offsetHM, UnicodeStri if (idx_HH >= 0) { return result.setTo(offsetHM.tempSubString(0, idx_HH + 2)); } - int32_t idx_H = offsetHM.tempSubString(0, idx_mm).lastIndexOf((char16_t)0x0048, 0); + int32_t idx_H = offsetHM.tempSubString(0, idx_mm).lastIndexOf(static_cast(0x0048), 0); if (idx_H >= 0) { return result.setTo(offsetHM.tempSubString(0, idx_H + 1)); } @@ -2647,7 +2647,7 @@ TimeZoneFormat::checkAbuttingHoursAndMinutes() { UBool afterH = false; UVector *items = fGMTOffsetPatternItems[type]; for (int32_t i = 0; i < items->size(); i++) { - const GMTOffsetField* item = (GMTOffsetField*)items->elementAt(i); + const GMTOffsetField* item = static_cast(items->elementAt(i)); GMTOffsetField::FieldType fieldType = item->getType(); if (fieldType != GMTOffsetField::TEXT) { if (afterH) { @@ -2745,7 +2745,7 @@ ZoneIdMatchHandler::handleMatch(int32_t matchLength, const CharacterNode *node, return false; } if (node->hasValues()) { - const char16_t* id = (const char16_t*)node->getValue(0); + const char16_t* id = static_cast(node->getValue(0)); if (id != nullptr) { if (fLen < matchLength) { fID = id; diff --git a/icu4c/source/i18n/tzgnames.cpp b/icu4c/source/i18n/tzgnames.cpp index 19ad38404bf4..6934e708c501 100644 --- a/icu4c/source/i18n/tzgnames.cpp +++ b/icu4c/source/i18n/tzgnames.cpp @@ -50,7 +50,7 @@ static const char16_t gEmpty[] = {0x00}; static const char16_t gDefRegionPattern[] = {0x7B, 0x30, 0x7D, 0x00}; // "{0}" static const char16_t gDefFallbackPattern[] = {0x7B, 0x31, 0x7D, 0x20, 0x28, 0x7B, 0x30, 0x7D, 0x29, 0x00}; // "{1} ({0})" -static const double kDstCheckRange = (double)184*U_MILLIS_PER_DAY; +static const double kDstCheckRange = static_cast(184) * U_MILLIS_PER_DAY; @@ -157,7 +157,7 @@ TimeZoneGenericNameMatchInfo::size() const { UTimeZoneGenericNameType TimeZoneGenericNameMatchInfo::getGenericNameType(int32_t index) const { - GMatchInfo *minfo = (GMatchInfo *)fMatches->elementAt(index); + GMatchInfo* minfo = static_cast(fMatches->elementAt(index)); if (minfo != nullptr) { return static_cast(minfo->gnameInfo->type); } @@ -166,7 +166,7 @@ TimeZoneGenericNameMatchInfo::getGenericNameType(int32_t index) const { int32_t TimeZoneGenericNameMatchInfo::getMatchLength(int32_t index) const { - ZMatchInfo *minfo = (ZMatchInfo *)fMatches->elementAt(index); + ZMatchInfo* minfo = static_cast(fMatches->elementAt(index)); if (minfo != nullptr) { return minfo->matchLength; } @@ -175,7 +175,7 @@ TimeZoneGenericNameMatchInfo::getMatchLength(int32_t index) const { UnicodeString& TimeZoneGenericNameMatchInfo::getTimeZoneID(int32_t index, UnicodeString& tzID) const { - GMatchInfo *minfo = (GMatchInfo *)fMatches->elementAt(index); + GMatchInfo* minfo = static_cast(fMatches->elementAt(index)); if (minfo != nullptr && minfo->gnameInfo->tzID != nullptr) { tzID.setTo(true, minfo->gnameInfo->tzID, -1); } else { @@ -230,7 +230,7 @@ GNameSearchHandler::handleMatch(int32_t matchLength, const CharacterNode *node, } fResults = lpResults.orphan(); } - GMatchInfo *gmatch = (GMatchInfo *)uprv_malloc(sizeof(GMatchInfo)); + GMatchInfo* gmatch = static_cast(uprv_malloc(sizeof(GMatchInfo))); if (gmatch == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return false; @@ -502,7 +502,7 @@ TZGNCore::getGenericLocationName(const UnicodeString& tzCanonicalID) { U_ASSERT(status == U_ZERO_ERROR); // already checked length above tzIDKey[tzIDKeyLen] = 0; - const char16_t *locname = (const char16_t *)uhash_get(fLocationNamesMap, tzIDKey); + const char16_t* locname = static_cast(uhash_get(fLocationNamesMap, tzIDKey)); if (locname != nullptr) { // gEmpty indicate the name is not available @@ -560,7 +560,7 @@ TZGNCore::getGenericLocationName(const UnicodeString& tzCanonicalID) { locname = nullptr; } else { // put the name info into the trie - GNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(GNameInfo)); + GNameInfo* nameinfo = static_cast(uprv_malloc(sizeof(GNameInfo))); if (nameinfo != nullptr) { nameinfo->type = UTZGNM_LOCATION; nameinfo->tzID = cacheID; @@ -756,7 +756,7 @@ TZGNCore::getPartialLocationName(const UnicodeString& tzCanonicalID, key.isLong = isLong; U_ASSERT(key.tzID != nullptr && key.mzID != nullptr); - const char16_t* uplname = (const char16_t*)uhash_get(fPartialLocationNamesMap, (void *)&key); + const char16_t* uplname = static_cast(uhash_get(fPartialLocationNamesMap, &key)); if (uplname != nullptr) { return uplname; } @@ -799,7 +799,7 @@ TZGNCore::getPartialLocationName(const UnicodeString& tzCanonicalID, uplname = fStringPool.get(name, status); if (U_SUCCESS(status)) { // Add the name to cache - PartialLocationKey* cacheKey = (PartialLocationKey *)uprv_malloc(sizeof(PartialLocationKey)); + PartialLocationKey* cacheKey = static_cast(uprv_malloc(sizeof(PartialLocationKey))); if (cacheKey != nullptr) { cacheKey->tzID = key.tzID; cacheKey->mzID = key.mzID; @@ -809,7 +809,7 @@ TZGNCore::getPartialLocationName(const UnicodeString& tzCanonicalID, uprv_free(cacheKey); } else { // put the name to the local trie as well - GNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(GNameInfo)); + GNameInfo* nameinfo = static_cast(uprv_malloc(sizeof(GNameInfo))); if (nameinfo != nullptr) { nameinfo->type = isLong ? UTZGNM_LONG : UTZGNM_SHORT; nameinfo->tzID = key.tzID; @@ -1142,10 +1142,10 @@ U_CDECL_END static void sweepCache() { int32_t pos = UHASH_FIRST; const UHashElement* elem; - double now = (double)uprv_getUTCtime(); + double now = static_cast(uprv_getUTCtime()); while ((elem = uhash_nextElement(gTZGNCoreCache, &pos)) != nullptr) { - TZGNCoreRef *entry = (TZGNCoreRef *)elem->value.pointer; + TZGNCoreRef* entry = static_cast(elem->value.pointer); if (entry->refCount <= 0 && (now - entry->lastAccess) > CACHE_EXPIRATION) { // delete this entry uhash_removeElement(gTZGNCoreCache, elem); @@ -1198,7 +1198,7 @@ TimeZoneGenericNames::createInstance(const Locale& locale, UErrorCode& status) { // Check the cache, if not available, create new one and cache const char *key = locale.getName(); - cacheEntry = (TZGNCoreRef *)uhash_get(gTZGNCoreCache, key); + cacheEntry = static_cast(uhash_get(gTZGNCoreCache, key)); if (cacheEntry == nullptr) { TZGNCore *tzgnCore = nullptr; char *newKey = nullptr; @@ -1208,7 +1208,7 @@ TimeZoneGenericNames::createInstance(const Locale& locale, UErrorCode& status) { status = U_MEMORY_ALLOCATION_ERROR; } if (U_SUCCESS(status)) { - newKey = (char *)uprv_malloc(uprv_strlen(key) + 1); + newKey = static_cast(uprv_malloc(uprv_strlen(key) + 1)); if (newKey == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { @@ -1216,13 +1216,13 @@ TimeZoneGenericNames::createInstance(const Locale& locale, UErrorCode& status) { } } if (U_SUCCESS(status)) { - cacheEntry = (TZGNCoreRef *)uprv_malloc(sizeof(TZGNCoreRef)); + cacheEntry = static_cast(uprv_malloc(sizeof(TZGNCoreRef))); if (cacheEntry == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { cacheEntry->obj = tzgnCore; cacheEntry->refCount = 1; - cacheEntry->lastAccess = (double)uprv_getUTCtime(); + cacheEntry->lastAccess = static_cast(uprv_getUTCtime()); uhash_put(gTZGNCoreCache, newKey, cacheEntry, &status); } @@ -1240,7 +1240,7 @@ TimeZoneGenericNames::createInstance(const Locale& locale, UErrorCode& status) { } else { // Update the reference count cacheEntry->refCount++; - cacheEntry->lastAccess = (double)uprv_getUTCtime(); + cacheEntry->lastAccess = static_cast(uprv_getUTCtime()); } gAccessCount++; if (gAccessCount >= SWEEP_INTERVAL) { diff --git a/icu4c/source/i18n/tznames.cpp b/icu4c/source/i18n/tznames.cpp index 24ca161e88c8..48e043a3db2b 100644 --- a/icu4c/source/i18n/tznames.cpp +++ b/icu4c/source/i18n/tznames.cpp @@ -85,10 +85,10 @@ U_CDECL_END static void sweepCache() { int32_t pos = UHASH_FIRST; const UHashElement* elem; - double now = (double)uprv_getUTCtime(); + double now = static_cast(uprv_getUTCtime()); while ((elem = uhash_nextElement(gTimeZoneNamesCache, &pos)) != nullptr) { - TimeZoneNamesCacheEntry *entry = (TimeZoneNamesCacheEntry *)elem->value.pointer; + TimeZoneNamesCacheEntry* entry = static_cast(elem->value.pointer); if (entry->refCount <= 0 && (now - entry->lastAccess) > CACHE_EXPIRATION) { // delete this entry uhash_removeElement(gTimeZoneNamesCache, elem); @@ -152,7 +152,7 @@ TimeZoneNamesDelegate::TimeZoneNamesDelegate(const Locale& locale, UErrorCode& s TimeZoneNamesCacheEntry *cacheEntry = nullptr; const char *key = locale.getName(); - cacheEntry = (TimeZoneNamesCacheEntry *)uhash_get(gTimeZoneNamesCache, key); + cacheEntry = static_cast(uhash_get(gTimeZoneNamesCache, key)); if (cacheEntry == nullptr) { TimeZoneNames *tznames = nullptr; char *newKey = nullptr; @@ -162,7 +162,7 @@ TimeZoneNamesDelegate::TimeZoneNamesDelegate(const Locale& locale, UErrorCode& s status = U_MEMORY_ALLOCATION_ERROR; } if (U_SUCCESS(status)) { - newKey = (char *)uprv_malloc(uprv_strlen(key) + 1); + newKey = static_cast(uprv_malloc(uprv_strlen(key) + 1)); if (newKey == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { @@ -170,13 +170,13 @@ TimeZoneNamesDelegate::TimeZoneNamesDelegate(const Locale& locale, UErrorCode& s } } if (U_SUCCESS(status)) { - cacheEntry = (TimeZoneNamesCacheEntry *)uprv_malloc(sizeof(TimeZoneNamesCacheEntry)); + cacheEntry = static_cast(uprv_malloc(sizeof(TimeZoneNamesCacheEntry))); if (cacheEntry == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; } else { cacheEntry->names = tznames; cacheEntry->refCount = 1; - cacheEntry->lastAccess = (double)uprv_getUTCtime(); + cacheEntry->lastAccess = static_cast(uprv_getUTCtime()); uhash_put(gTimeZoneNamesCache, newKey, cacheEntry, &status); } @@ -194,7 +194,7 @@ TimeZoneNamesDelegate::TimeZoneNamesDelegate(const Locale& locale, UErrorCode& s } else { // Update the reference count cacheEntry->refCount++; - cacheEntry->lastAccess = (double)uprv_getUTCtime(); + cacheEntry->lastAccess = static_cast(uprv_getUTCtime()); } gAccessCount++; if (gAccessCount >= SWEEP_INTERVAL) { @@ -442,7 +442,7 @@ TimeZoneNames::MatchInfoCollection::size() const { UTimeZoneNameType TimeZoneNames::MatchInfoCollection::getNameTypeAt(int32_t idx) const { - const MatchInfo* match = (const MatchInfo*)fMatches->elementAt(idx); + const MatchInfo* match = static_cast(fMatches->elementAt(idx)); if (match) { return match->nameType; } @@ -451,7 +451,7 @@ TimeZoneNames::MatchInfoCollection::getNameTypeAt(int32_t idx) const { int32_t TimeZoneNames::MatchInfoCollection::getMatchLengthAt(int32_t idx) const { - const MatchInfo* match = (const MatchInfo*)fMatches->elementAt(idx); + const MatchInfo* match = static_cast(fMatches->elementAt(idx)); if (match) { return match->matchLength; } @@ -461,7 +461,7 @@ TimeZoneNames::MatchInfoCollection::getMatchLengthAt(int32_t idx) const { UBool TimeZoneNames::MatchInfoCollection::getTimeZoneIDAt(int32_t idx, UnicodeString& tzID) const { tzID.remove(); - const MatchInfo* match = (const MatchInfo*)fMatches->elementAt(idx); + const MatchInfo* match = static_cast(fMatches->elementAt(idx)); if (match && match->isTZID) { tzID.setTo(match->id); return true; @@ -472,7 +472,7 @@ TimeZoneNames::MatchInfoCollection::getTimeZoneIDAt(int32_t idx, UnicodeString& UBool TimeZoneNames::MatchInfoCollection::getMetaZoneIDAt(int32_t idx, UnicodeString& mzID) const { mzID.remove(); - const MatchInfo* match = (const MatchInfo*)fMatches->elementAt(idx); + const MatchInfo* match = static_cast(fMatches->elementAt(idx)); if (match && !match->isTZID) { mzID.setTo(match->id); return true; diff --git a/icu4c/source/i18n/tznames_impl.cpp b/icu4c/source/i18n/tznames_impl.cpp index 038b8097f216..8c338b9cc7f1 100644 --- a/icu4c/source/i18n/tznames_impl.cpp +++ b/icu4c/source/i18n/tznames_impl.cpp @@ -132,7 +132,7 @@ void CharacterNode::deleteValues(UObjectDeleter *valueDeleter) { valueDeleter(fValues); } } else { - delete (UVector *)fValues; + delete static_cast(fValues); } } @@ -168,7 +168,7 @@ CharacterNode::addValue(void *value, UObjectDeleter *valueDeleter, UErrorCode &s fHasValuesVector = true; } // Add the new value. - UVector *values = (UVector *)fValues; + UVector* values = static_cast(fValues); if (values->hasDeleter()) { values->adoptElement(value, status); } else { @@ -259,7 +259,7 @@ void TextTrieMap::putImpl(const UnicodeString &key, void *value, UErrorCode &status) { if (fNodes == nullptr) { fNodesCapacity = 512; - fNodes = (CharacterNode *)uprv_malloc(fNodesCapacity * sizeof(CharacterNode)); + fNodes = static_cast(uprv_malloc(fNodesCapacity * sizeof(CharacterNode))); if (fNodes == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; @@ -298,7 +298,7 @@ TextTrieMap::growNodes() { if (newCapacity > 0xffff) { newCapacity = 0xffff; } - CharacterNode *newNodes = (CharacterNode *)uprv_malloc(newCapacity * sizeof(CharacterNode)); + CharacterNode* newNodes = static_cast(uprv_malloc(newCapacity * sizeof(CharacterNode))); if (newNodes == nullptr) { return false; } @@ -331,7 +331,7 @@ TextTrieMap::addChildNode(CharacterNode *parent, char16_t c, UErrorCode &status) // Ensure capacity. Grow fNodes[] if needed. if (fNodesCount == fNodesCapacity) { - int32_t parentIndex = (int32_t)(parent - fNodes); + int32_t parentIndex = static_cast(parent - fNodes); if (!growNodes()) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -345,9 +345,9 @@ TextTrieMap::addChildNode(CharacterNode *parent, char16_t c, UErrorCode &status) node->fCharacter = c; node->fNextSibling = nodeIndex; if (prevIndex == 0) { - parent->fFirstChild = (uint16_t)fNodesCount; + parent->fFirstChild = static_cast(fNodesCount); } else { - fNodes[prevIndex].fNextSibling = (uint16_t)fNodesCount; + fNodes[prevIndex].fNextSibling = static_cast(fNodesCount); } ++fNodesCount; return node; @@ -378,7 +378,7 @@ TextTrieMap::getChildNode(CharacterNode *parent, char16_t c) const { void TextTrieMap::buildTrie(UErrorCode &status) { if (fLazyContents != nullptr) { for (int32_t i=0; isize(); i+=2) { - const char16_t *key = (char16_t *)fLazyContents->elementAt(i); + const char16_t* key = static_cast(fLazyContents->elementAt(i)); void *val = fLazyContents->elementAt(i+1); UnicodeString keyString(true, key, -1); // Aliasing UnicodeString constructor. putImpl(keyString, val, status); @@ -678,7 +678,7 @@ class ZNames : public UMemory { if (locationNameUniStr.length() > 0) { const char16_t* buff = locationNameUniStr.getTerminatedBuffer(); int32_t len = sizeof(char16_t) * (locationNameUniStr.length() + 1); - locationName = (char16_t*) uprv_malloc(len); + locationName = static_cast(uprv_malloc(len)); if (locationName == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -721,14 +721,14 @@ class ZNames : public UMemory { for (int32_t i = 0; i < UTZNM_INDEX_COUNT; i++) { const char16_t* name = fNames[i]; if (name != nullptr) { - ZNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(ZNameInfo)); + ZNameInfo* nameinfo = static_cast(uprv_malloc(sizeof(ZNameInfo))); if (nameinfo == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return; } nameinfo->mzID = mzID; nameinfo->tzID = tzID; - nameinfo->type = getTZNameType((UTimeZoneNameTypeIndex)i); + nameinfo->type = getTZNameType(static_cast(i)); trie.put(name, nameinfo, status); // trie.put() takes ownership of the key if (U_FAILURE(status)) { return; @@ -767,8 +767,8 @@ struct ZNames::ZNamesLoader : public ResourceSink { // Replace "/" with ":". UnicodeString uKey(tzID); for (int32_t i = 0; i < uKey.length(); i++) { - if (uKey.charAt(i) == (char16_t)0x2F) { - uKey.setCharAt(i, (char16_t)0x3A); + if (uKey.charAt(i) == static_cast(0x2F)) { + uKey.setCharAt(i, static_cast(0x3A)); } } @@ -905,7 +905,7 @@ MetaZoneIDsEnumeration::MetaZoneIDsEnumeration(LocalPointer mzIDs) const UnicodeString* MetaZoneIDsEnumeration::snext(UErrorCode& status) { if (U_SUCCESS(status) && fMetaZoneIDs != nullptr && fPos < fLen) { - unistr.setTo((const char16_t*)fMetaZoneIDs->elementAt(fPos++), -1); + unistr.setTo(static_cast(fMetaZoneIDs->elementAt(fPos++)), -1); return &unistr; } return nullptr; @@ -1168,7 +1168,7 @@ TimeZoneNamesImpl::_getAvailableMetaZoneIDs(const UnicodeString& tzID, UErrorCod U_ASSERT(mzIDs.isValid()); for (int32_t i = 0; U_SUCCESS(status) && i < mappings->size(); i++) { - OlsonToMetaMappingEntry *map = (OlsonToMetaMappingEntry *)mappings->elementAt(i); + OlsonToMetaMappingEntry* map = static_cast(mappings->elementAt(i)); const char16_t *mzID = map->mzid; if (!mzIDs->contains((void *)mzID)) { mzIDs->addElement((void *)mzID, status); @@ -1338,7 +1338,7 @@ TimeZoneNamesImpl::loadMetaZoneNames(const UnicodeString& mzID, UErrorCode& stat } if (mznames != EMPTY) { - return (ZNames*)mznames; + return static_cast(mznames); } else { return nullptr; } @@ -1369,7 +1369,7 @@ TimeZoneNamesImpl::loadTimeZoneNames(const UnicodeString& tzID, UErrorCode& stat } // tznames is never EMPTY - return (ZNames*)tznames; + return static_cast(tznames); } TimeZoneNames::MatchInfoCollection* @@ -1441,8 +1441,8 @@ void TimeZoneNamesImpl::addAllNamesIntoTrie(UErrorCode& status) { pos = UHASH_FIRST; while ((element = uhash_nextElement(fMZNamesMap, &pos)) != nullptr) { if (element->value.pointer == EMPTY) { continue; } - char16_t* mzID = (char16_t*) element->key.pointer; - ZNames* znames = (ZNames*) element->value.pointer; + char16_t* mzID = static_cast(element->key.pointer); + ZNames* znames = static_cast(element->value.pointer); znames->addAsMetaZoneIntoTrie(mzID, fNamesTrie, status); if (U_FAILURE(status)) { return; } } @@ -1450,8 +1450,8 @@ void TimeZoneNamesImpl::addAllNamesIntoTrie(UErrorCode& status) { pos = UHASH_FIRST; while ((element = uhash_nextElement(fTZNamesMap, &pos)) != nullptr) { if (element->value.pointer == EMPTY) { continue; } - char16_t* tzID = (char16_t*) element->key.pointer; - ZNames* znames = (ZNames*) element->value.pointer; + char16_t* tzID = static_cast(element->key.pointer); + ZNames* znames = static_cast(element->value.pointer); znames->addAsTimeZoneIntoTrie(tzID, fNamesTrie, status); if (U_FAILURE(status)) { return; } } @@ -1481,7 +1481,7 @@ struct TimeZoneNamesImpl::ZoneStringsLoader : public ResourceSink { void* createKey(const char* key, UErrorCode& status) { int32_t len = sizeof(char) * (static_cast(uprv_strlen(key)) + 1); - char* newKey = (char*) uprv_malloc(len); + char* newKey = static_cast(uprv_malloc(len)); if (newKey == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; @@ -1518,8 +1518,8 @@ struct TimeZoneNamesImpl::ZoneStringsLoader : public ResourceSink { const UHashElement* element; while ((element = uhash_nextElement(keyToLoader, &pos)) != nullptr) { if (element->value.pointer == DUMMY_LOADER) { continue; } - ZNames::ZNamesLoader* loader = (ZNames::ZNamesLoader*) element->value.pointer; - char* key = (char*) element->key.pointer; + ZNames::ZNamesLoader* loader = static_cast(element->value.pointer); + char* key = static_cast(element->key.pointer); if (isMetaZone(key)) { UnicodeString mzID = mzIDFromKey(key); @@ -1578,7 +1578,7 @@ struct TimeZoneNamesImpl::ZoneStringsLoader : public ResourceSink { if (loader != DUMMY_LOADER) { // Let the ZNamesLoader consume the names table. - ((ZNames::ZNamesLoader*)loader)->put(key, value, noFallback, status); + static_cast(loader)->put(key, value, noFallback, status); } } @@ -1634,7 +1634,7 @@ void TimeZoneNamesImpl::getDisplayNames(const UnicodeString& tzID, // Load the values into the dest array for (int i = 0; i < numTypes; i++) { UTimeZoneNameType type = types[i]; - const char16_t* name = ((ZNames*)tznames)->getName(type); + const char16_t* name = static_cast(tznames)->getName(type); if (name == nullptr) { if (mznames == nullptr) { // Load the meta zone name @@ -1657,7 +1657,7 @@ void TimeZoneNamesImpl::getDisplayNames(const UnicodeString& tzID, } U_ASSERT(mznames != nullptr); if (mznames != EMPTY) { - name = ((ZNames*)mznames)->getName(type); + name = static_cast(mznames)->getName(type); } } if (name != nullptr) { @@ -1716,11 +1716,11 @@ TimeZoneNamesImpl::getDefaultExemplarLocationName(const UnicodeString& tzID, Uni return name; } - int32_t sep = tzID.lastIndexOf((char16_t)0x2F /* '/' */); + int32_t sep = tzID.lastIndexOf(static_cast(0x2F) /* '/' */); if (sep > 0 && sep + 1 < tzID.length()) { name.setTo(tzID, sep + 1); - name.findAndReplace(UnicodeString((char16_t)0x5f /* _ */), - UnicodeString((char16_t)0x20 /* space */)); + name.findAndReplace(UnicodeString(static_cast(0x5f) /* _ */), + UnicodeString(static_cast(0x20) /* space */)); } else { name.setToBogus(); } @@ -1790,7 +1790,7 @@ TZDBNames::createInstance(UResourceBundle* rb, const char* key) { return nullptr; } - names = (const char16_t **)uprv_malloc(sizeof(const char16_t*) * TZDBNAMES_KEYS_SIZE); + names = static_cast(uprv_malloc(sizeof(const char16_t*) * TZDBNAMES_KEYS_SIZE)); UBool isEmpty = true; if (names != nullptr) { for (int32_t i = 0; i < TZDBNAMES_KEYS_SIZE; i++) { @@ -1817,7 +1817,7 @@ TZDBNames::createInstance(UResourceBundle* rb, const char* key) { if (U_SUCCESS(status)) { numRegions = ures_getSize(regionsRes); if (numRegions > 0) { - regions = (char**)uprv_malloc(sizeof(char*) * numRegions); + regions = static_cast(uprv_malloc(sizeof(char*) * numRegions)); if (regions != nullptr) { char **pRegion = regions; for (int32_t i = 0; i < numRegions; i++, pRegion++) { @@ -1832,7 +1832,7 @@ TZDBNames::createInstance(UResourceBundle* rb, const char* key) { regionError = true; break; } - *pRegion = (char*)uprv_malloc(sizeof(char) * (len + 1)); + *pRegion = static_cast(uprv_malloc(sizeof(char) * (len + 1))); if (*pRegion == nullptr) { regionError = true; break; @@ -2316,7 +2316,7 @@ TZDBTimeZoneNames::getMetaZoneNames(const UnicodeString& mzID, UErrorCode& statu } ures_close(zoneStringsRes); } else if (cacheVal != EMPTY) { - tzdbNames = (TZDBNames *)cacheVal; + tzdbNames = static_cast(cacheVal); } } umtx_unlock(&gTZDBNamesMapLock); diff --git a/icu4c/source/i18n/tznames_impl.h b/icu4c/source/i18n/tznames_impl.h index 3ab1e5cc94d1..eb4748799e2e 100644 --- a/icu4c/source/i18n/tznames_impl.h +++ b/icu4c/source/i18n/tznames_impl.h @@ -99,21 +99,21 @@ struct CharacterNode { }; inline UBool CharacterNode::hasValues() const { - return (UBool)(fValues != nullptr); + return static_cast(fValues != nullptr); } inline int32_t CharacterNode::countValues() const { return fValues == nullptr ? 0 : !fHasValuesVector ? 1 : - ((const UVector *)fValues)->size(); + static_cast(fValues)->size(); } inline const void *CharacterNode::getValue(int32_t index) const { if (!fHasValuesVector) { return fValues; // Assume index == 0. } else { - return ((const UVector *)fValues)->elementAt(index); + return static_cast(fValues)->elementAt(index); } } diff --git a/icu4c/source/i18n/tzrule.cpp b/icu4c/source/i18n/tzrule.cpp index 2ec57c9c1ba8..7507068c8807 100644 --- a/icu4c/source/i18n/tzrule.cpp +++ b/icu4c/source/i18n/tzrule.cpp @@ -591,7 +591,7 @@ TimeArrayTimeZoneRule::initStartTimes(const UDate source[], int32_t size, UError } // Allocate new one if needed if (size > TIMEARRAY_STACK_BUFFER_SIZE) { - fStartTimes = (UDate*)uprv_malloc(sizeof(UDate)*size); + fStartTimes = static_cast(uprv_malloc(sizeof(UDate) * size)); if (fStartTimes == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; fNumStartTimes = 0; @@ -603,7 +603,7 @@ TimeArrayTimeZoneRule::initStartTimes(const UDate source[], int32_t size, UError uprv_memcpy(fStartTimes, source, sizeof(UDate)*size); fNumStartTimes = size; // Sort dates - uprv_sortArray(fStartTimes, fNumStartTimes, (int32_t)sizeof(UDate), compareDates, nullptr, true, &status); + uprv_sortArray(fStartTimes, fNumStartTimes, static_cast(sizeof(UDate)), compareDates, nullptr, true, &status); if (U_FAILURE(status)) { if (fStartTimes != nullptr && fStartTimes != fLocalStartTimes) { uprv_free(fStartTimes); diff --git a/icu4c/source/i18n/ucal.cpp b/icu4c/source/i18n/ucal.cpp index 78d01763c74d..b8905fe9a3d1 100644 --- a/icu4c/source/i18n/ucal.cpp +++ b/icu4c/source/i18n/ucal.cpp @@ -42,7 +42,7 @@ _createTimeZone(const char16_t* zoneID, int32_t len, UErrorCode* ec) { // failure we will see is a memory allocation failure. int32_t l = (len<0 ? u_strlen(zoneID) : len); UnicodeString zoneStrID; - zoneStrID.setTo((UBool)(len < 0), zoneID, l); /* temporary read-only alias */ + zoneStrID.setTo(static_cast(len < 0), zoneID, l); /* temporary read-only alias */ zone = TimeZone::createTimeZone(zoneStrID); if (zone == nullptr) { *ec = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/ucol_res.cpp b/icu4c/source/i18n/ucol_res.cpp index aa0086802733..480575c6e50b 100644 --- a/icu4c/source/i18n/ucol_res.cpp +++ b/icu4c/source/i18n/ucol_res.cpp @@ -654,7 +654,7 @@ struct KeywordsSink : public ResourceSink { } } } else if (type == URES_TABLE && uprv_strncmp(key, "private-", 8) != 0) { - if (!ulist_containsString(values, key, (int32_t)uprv_strlen(key))) { + if (!ulist_containsString(values, key, static_cast(uprv_strlen(key)))) { ulist_addItemEndList(values, key, false, &errorCode); } } diff --git a/icu4c/source/i18n/ucol_sit.cpp b/icu4c/source/i18n/ucol_sit.cpp index 490dbd57884b..87387f879d83 100644 --- a/icu4c/source/i18n/ucol_sit.cpp +++ b/icu4c/source/i18n/ucol_sit.cpp @@ -238,7 +238,7 @@ readHexCodeUnit(const char **string, UErrorCode *status) #endif return 0; } - result = (result << 4) | (char16_t)value; + result = (result << 4) | static_cast(value); noDigits++; (*string)++; } @@ -319,7 +319,7 @@ const char* ucol_sit_readOption(const char *start, CollatorSpec *spec, fprintf(stderr, "***Set %d to %s...\n", i, start); #endif // assume 'start' does not go away through all this - spec->entries[i].copyFrom(CharString(start, (int32_t)(end - start), *status), *status); + spec->entries[i].copyFrom(CharString(start, static_cast(end - start), *status), *status); return end; } } @@ -343,7 +343,7 @@ ucol_sit_readSpecs(CollatorSpec *s, const char *string, } } if(U_FAILURE(*status)) { - parseError->offset = (int32_t)(string - definition); + parseError->offset = static_cast(string - definition); } return string; } diff --git a/icu4c/source/i18n/ucoleitr.cpp b/icu4c/source/i18n/ucoleitr.cpp index 36b83c4c1043..8930c103cf4d 100644 --- a/icu4c/source/i18n/ucoleitr.cpp +++ b/icu4c/source/i18n/ucoleitr.cpp @@ -350,7 +350,7 @@ UCollationPCE::nextProcessed( break; } - result = processCE((uint32_t)ce); + result = processCE(static_cast(ce)); } while (result == UCOL_IGNORABLE); if (ixLow != nullptr) { @@ -412,7 +412,7 @@ UCollationPCE::previousProcessed( goto finish; } - rceb.put((uint32_t)ce, low, high, *status); + rceb.put(static_cast(ce), low, high, *status); } while (U_SUCCESS(*status) && ((ce & UCOL_PRIMARYORDERMASK) == 0 || isContinuation(ce))); // process the raw CEs diff --git a/icu4c/source/i18n/uitercollationiterator.cpp b/icu4c/source/i18n/uitercollationiterator.cpp index 6f840f3fe5e0..e0d91514852c 100644 --- a/icu4c/source/i18n/uitercollationiterator.cpp +++ b/icu4c/source/i18n/uitercollationiterator.cpp @@ -54,7 +54,7 @@ char16_t UIterCollationIterator::handleGetTrailSurrogate() { UChar32 trail = iter.next(&iter); if(!U16_IS_TRAIL(trail) && trail >= 0) { iter.previous(&iter); } - return (char16_t)trail; + return static_cast(trail); } UChar32 @@ -149,7 +149,7 @@ FCDUIterCollationIterator::handleGetTrailSurrogate() { } else if(trail >= 0) { iter.previous(&iter); } - return (char16_t)trail; + return static_cast(trail); } else { U_ASSERT(pos < normalized.length()); char16_t trail; @@ -315,7 +315,7 @@ FCDUIterCollationIterator::nextSegment(UErrorCode &errorCode) { UChar32 c = uiter_next32(&iter); if(c < 0) { break; } uint16_t fcd16 = nfcImpl.getFCD16(c); - uint8_t leadCC = (uint8_t)(fcd16 >> 8); + uint8_t leadCC = static_cast(fcd16 >> 8); if(leadCC == 0 && !s.isEmpty()) { // FCD boundary before this character. uiter_previous32(&iter); @@ -340,7 +340,7 @@ FCDUIterCollationIterator::nextSegment(UErrorCode &errorCode) { pos = 0; return true; } - prevCC = (uint8_t)fcd16; + prevCC = static_cast(fcd16); if(prevCC == 0) { // FCD boundary after the last character. break; @@ -396,7 +396,7 @@ FCDUIterCollationIterator::previousSegment(UErrorCode &errorCode) { UChar32 c = uiter_previous32(&iter); if(c < 0) { break; } uint16_t fcd16 = nfcImpl.getFCD16(c); - uint8_t trailCC = (uint8_t)fcd16; + uint8_t trailCC = static_cast(fcd16); if(trailCC == 0 && !s.isEmpty()) { // FCD boundary after this character. uiter_next32(&iter); @@ -424,7 +424,7 @@ FCDUIterCollationIterator::previousSegment(UErrorCode &errorCode) { pos = normalized.length(); return true; } - nextCC = (uint8_t)(fcd16 >> 8); + nextCC = static_cast(fcd16 >> 8); if(nextCC == 0) { // FCD boundary before the following character. break; diff --git a/icu4c/source/i18n/umsg.cpp b/icu4c/source/i18n/umsg.cpp index b1f279580721..292fa7b87687 100644 --- a/icu4c/source/i18n/umsg.cpp +++ b/icu4c/source/i18n/umsg.cpp @@ -558,7 +558,7 @@ umsg_vparse(const UMessageFormat *fmt, case Formattable::kLong: aInt = va_arg(ap, int32_t*); if(aInt){ - *aInt = (int32_t) args[i].getLong(); + *aInt = args[i].getLong(); }else{ *status=U_ILLEGAL_ARGUMENT_ERROR; } diff --git a/icu4c/source/i18n/unesctrn.cpp b/icu4c/source/i18n/unesctrn.cpp index cce191ca62e7..774d82a32e56 100644 --- a/icu4c/source/i18n/unesctrn.cpp +++ b/icu4c/source/i18n/unesctrn.cpp @@ -84,7 +84,7 @@ static char16_t* copySpec(const char16_t* spec) { ++len; } ++len; - char16_t *result = (char16_t *)uprv_malloc(len*sizeof(char16_t)); + char16_t* result = static_cast(uprv_malloc(len * sizeof(char16_t))); // Check for memory allocation error. if (result != nullptr) { uprv_memcpy(result, spec, (size_t)len*sizeof(result[0])); @@ -186,7 +186,7 @@ void UnescapeTransliterator::handleTransliterate(Replaceable& text, UTransPositi // Read the header int32_t prefixLen = spec[ipat++]; int32_t suffixLen = spec[ipat++]; - int8_t radix = (int8_t) spec[ipat++]; + int8_t radix = static_cast(spec[ipat++]); int32_t minDigits = spec[ipat++]; int32_t maxDigits = spec[ipat++]; diff --git a/icu4c/source/i18n/uni2name.cpp b/icu4c/source/i18n/uni2name.cpp index 727f8953dbbf..5173ee1d0c76 100644 --- a/icu4c/source/i18n/uni2name.cpp +++ b/icu4c/source/i18n/uni2name.cpp @@ -82,7 +82,7 @@ void UnicodeNameTransliterator::handleTransliterate(Replaceable& text, UTransPos } // Accommodate the longest possible name plus padding - char* buf = (char*) uprv_malloc(maxLen); + char* buf = static_cast(uprv_malloc(maxLen)); if (buf == nullptr) { offsets.start = offsets.limit; return; diff --git a/icu4c/source/i18n/unicode/calendar.h b/icu4c/source/i18n/unicode/calendar.h index a21df22ff050..a04f5b65bd5b 100644 --- a/icu4c/source/i18n/unicode/calendar.h +++ b/icu4c/source/i18n/unicode/calendar.h @@ -2539,14 +2539,14 @@ Calendar::createInstance(TimeZone* zone, UErrorCode& errorCode) inline void Calendar::roll(UCalendarDateFields field, UBool up, UErrorCode& status) { - roll(field, (int32_t)(up ? +1 : -1), status); + roll(field, static_cast(up ? +1 : -1), status); } #ifndef U_HIDE_DEPRECATED_API inline void Calendar::roll(EDateFields field, UBool up, UErrorCode& status) { - roll((UCalendarDateFields) field, up, status); + roll(static_cast(field), up, status); } #endif /* U_HIDE_DEPRECATED_API */ diff --git a/icu4c/source/i18n/unicode/coleitr.h b/icu4c/source/i18n/unicode/coleitr.h index 1b7fec0d1dc8..a147d6cfba14 100644 --- a/icu4c/source/i18n/unicode/coleitr.h +++ b/icu4c/source/i18n/unicode/coleitr.h @@ -128,7 +128,7 @@ class U_I18N_API CollationElementIterator final : public UObject { * NULLORDER indicates that an error has occurred while processing * @stable ICU 2.0 */ - NULLORDER = (int32_t)0xffffffff + NULLORDER = static_cast(0xffffffff) }; // CollationElementIterator public constructor/destructor ------------------- diff --git a/icu4c/source/i18n/unicode/dcfmtsym.h b/icu4c/source/i18n/unicode/dcfmtsym.h index 52f2268434da..02e12f9c39b2 100644 --- a/icu4c/source/i18n/unicode/dcfmtsym.h +++ b/icu4c/source/i18n/unicode/dcfmtsym.h @@ -576,7 +576,7 @@ DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString fCodePointZero = sym; for ( int8_t i = 1 ; i<= 9 ; i++ ) { sym++; - fSymbols[(int)kOneDigitSymbol+i-1] = UnicodeString(sym); + fSymbols[static_cast(kOneDigitSymbol) + i - 1] = UnicodeString(sym); } } else { fCodePointZero = -1; diff --git a/icu4c/source/i18n/unicode/fmtable.h b/icu4c/source/i18n/unicode/fmtable.h index d251d35ba88c..1f6b43844a27 100644 --- a/icu4c/source/i18n/unicode/fmtable.h +++ b/icu4c/source/i18n/unicode/fmtable.h @@ -311,7 +311,7 @@ class U_I18N_API Formattable : public UObject { * @return the long value of this object. * @stable ICU 2.0 */ - int32_t getLong() const { return (int32_t)fValue.fInt64; } + int32_t getLong() const { return static_cast(fValue.fInt64); } /** * Gets the long value of this object. If the magnitude is too diff --git a/icu4c/source/i18n/unicode/messageformat2_arguments.h b/icu4c/source/i18n/unicode/messageformat2_arguments.h index f79865a43ff6..c43d96191f16 100644 --- a/icu4c/source/i18n/unicode/messageformat2_arguments.h +++ b/icu4c/source/i18n/unicode/messageformat2_arguments.h @@ -73,7 +73,7 @@ namespace message2 { if (U_FAILURE(status)) { return; } - argumentNames = LocalArray(new UnicodeString[argsLen = (int32_t) args.size()]); + argumentNames = LocalArray(new UnicodeString[argsLen = static_cast(args.size())]); arguments = LocalArray(new Formattable[argsLen]); if (!argumentNames.isValid() || !arguments.isValid()) { status = U_MEMORY_ALLOCATION_ERROR; diff --git a/icu4c/source/i18n/unicode/sortkey.h b/icu4c/source/i18n/unicode/sortkey.h index a9b6fee83b2f..6679beb9357a 100644 --- a/icu4c/source/i18n/unicode/sortkey.h +++ b/icu4c/source/i18n/unicode/sortkey.h @@ -264,7 +264,7 @@ class U_I18N_API CollationKey : public UObject { return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes; } int32_t getCapacity() const { - return (fFlagAndLength >= 0) ? (int32_t)sizeof(fUnion) : fUnion.fFields.fCapacity; + return fFlagAndLength >= 0 ? static_cast(sizeof(fUnion)) : fUnion.fFields.fCapacity; } int32_t getLength() const { return fFlagAndLength & 0x7fffffff; } diff --git a/icu4c/source/i18n/unicode/tblcoll.h b/icu4c/source/i18n/unicode/tblcoll.h index 0c018beb8138..3843691ddf5f 100644 --- a/icu4c/source/i18n/unicode/tblcoll.h +++ b/icu4c/source/i18n/unicode/tblcoll.h @@ -843,14 +843,14 @@ class U_I18N_API RuleBasedCollator final : public Collator { const CollationSettings &getDefaultSettings() const; void setAttributeDefault(int32_t attribute) { - explicitlySetAttributes &= ~((uint32_t)1 << attribute); + explicitlySetAttributes &= ~(static_cast(1) << attribute); } void setAttributeExplicitly(int32_t attribute) { - explicitlySetAttributes |= (uint32_t)1 << attribute; + explicitlySetAttributes |= static_cast(1) << attribute; } UBool attributeHasBeenSetExplicitly(int32_t attribute) const { // assert(0 <= attribute < ATTR_LIMIT); - return (UBool)((explicitlySetAttributes & ((uint32_t)1 << attribute)) != 0); + return static_cast((explicitlySetAttributes & (static_cast(1) << attribute)) != 0); } /** diff --git a/icu4c/source/i18n/unicode/translit.h b/icu4c/source/i18n/unicode/translit.h index cde8450c8891..70ba1c87fa38 100644 --- a/icu4c/source/i18n/unicode/translit.h +++ b/icu4c/source/i18n/unicode/translit.h @@ -1566,7 +1566,7 @@ inline int32_t Transliterator::getMaximumContextLength() const { 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.append(static_cast(0)); ID.truncate(ID.length()-1); } diff --git a/icu4c/source/i18n/units_converter.cpp b/icu4c/source/i18n/units_converter.cpp index 84ea1c176132..3ccb0065bfca 100644 --- a/icu4c/source/i18n/units_converter.cpp +++ b/icu4c/source/i18n/units_converter.cpp @@ -74,7 +74,8 @@ void U_I18N_API Factor::applyPrefix(UMeasurePrefix unitPrefix) { } int32_t prefixPower = umeas_getPrefixPower(unitPrefix); - double prefixFactor = std::pow((double)umeas_getPrefixBase(unitPrefix), (double)std::abs(prefixPower)); + double prefixFactor = std::pow(static_cast(umeas_getPrefixBase(unitPrefix)), + static_cast(std::abs(prefixPower))); if (prefixPower >= 0) { factorNum *= prefixFactor; } else { @@ -697,10 +698,10 @@ double UnitsConverter::scaleToBase(double scaleValue, double minBaseForScaleValu scaleValue = -scaleValue; } scaleValue += 0.5; // adjust up for later truncation - if (scaleValue > (double)scaleMax) { - scaleValue = (double)scaleMax; + if (scaleValue > static_cast(scaleMax)) { + scaleValue = static_cast(scaleMax); } - int scaleInt = (int)scaleValue; + int scaleInt = static_cast(scaleValue); return (minBaseForScaleValues[scaleInt] + minBaseForScaleValues[scaleInt+1])/2.0; } @@ -737,7 +738,7 @@ double UnitsConverter::baseToScale(double baseValue, double minBaseForScaleValue baseValue = -baseValue; } int scaleIndex = bsearchRanges(minBaseForScaleValues, scaleMax, baseValue); - return (double)scaleIndex; + return static_cast(scaleIndex); } double UnitsConverter::convert(double inputValue) const { diff --git a/icu4c/source/i18n/unum.cpp b/icu4c/source/i18n/unum.cpp index 7c35473f2d13..7e112d4ad732 100644 --- a/icu4c/source/i18n/unum.cpp +++ b/icu4c/source/i18n/unum.cpp @@ -386,13 +386,13 @@ parseRes(Formattable& res, if(U_FAILURE(*status)) return; - const UnicodeString src((UBool)(textLength == -1), text, textLength); + const UnicodeString src(static_cast(textLength == -1), text, textLength); ParsePosition pp; if (parsePos != nullptr) pp.setIndex(*parsePos); - ((const NumberFormat*)fmt)->parse(src, res, pp); + reinterpret_cast(fmt)->parse(src, res, pp); if(pp.getErrorIndex() != -1) { *status = U_PARSE_ERROR; diff --git a/icu4c/source/i18n/uregex.cpp b/icu4c/source/i18n/uregex.cpp index 534310d609d0..5a5ff1d0387d 100644 --- a/icu4c/source/i18n/uregex.cpp +++ b/icu4c/source/i18n/uregex.cpp @@ -637,7 +637,7 @@ uregex_groupNumberFromName(URegularExpression *regexp2, const char16_t *groupName, int32_t nameLength, UErrorCode *status) { - RegularExpression *regexp = (RegularExpression*)regexp2; + RegularExpression* regexp = reinterpret_cast(regexp2); if (validateRE(regexp, false, status) == false) { return 0; } @@ -650,7 +650,7 @@ uregex_groupNumberFromCName(URegularExpression *regexp2, const char *groupName, int32_t nameLength, UErrorCode *status) { - RegularExpression *regexp = (RegularExpression*)regexp2; + RegularExpression* regexp = reinterpret_cast(regexp2); if (validateRE(regexp, false, status) == false) { return 0; } @@ -1389,8 +1389,8 @@ int32_t RegexCImpl::appendReplacement(RegularExpression *regexp, int32_t matchStart; int32_t lastMatchEnd; if (UTEXT_USES_U16(m->fInputText)) { - lastMatchEnd = (int32_t)m->fLastMatchEnd; - matchStart = (int32_t)m->fMatchStart; + lastMatchEnd = static_cast(m->fLastMatchEnd); + matchStart = static_cast(m->fMatchStart); } else { // !!!: Would like a better way to do this! UErrorCode tempStatus = U_ZERO_ERROR; @@ -1440,9 +1440,9 @@ int32_t RegexCImpl::appendReplacement(RegularExpression *regexp, replacementLength, // Length of replacement text (void *)replacementText); - if (escapedChar != (UChar32)0xFFFFFFFF) { + if (escapedChar != static_cast(0xFFFFFFFF)) { if (escapedChar <= 0xffff) { - appendToBuf((char16_t)escapedChar, &destIdx, dest, capacity); + appendToBuf(static_cast(escapedChar), &destIdx, dest, capacity); } else { appendToBuf(U16_LEAD(escapedChar), &destIdx, dest, capacity); appendToBuf(U16_TRAIL(escapedChar), &destIdx, dest, capacity); @@ -1527,7 +1527,7 @@ int32_t RegexCImpl::appendReplacement(RegularExpression *regexp, // Finally, append the capture group data to the destination. if (U_SUCCESS(*status)) { - destIdx += uregex_group((URegularExpression*)regexp, groupNum, + destIdx += uregex_group(reinterpret_cast(regexp), groupNum, dest==nullptr?nullptr:&dest[destIdx], REMAINING_CAPACITY(destIdx, capacity), status); if (*status == U_BUFFER_OVERFLOW_ERROR) { // Ignore buffer overflow when extracting the group. We need to @@ -1653,7 +1653,7 @@ int32_t RegexCImpl::appendTail(RegularExpression *regexp, if (nativeIdx == -1) { srcIdx = 0; } else if (UTEXT_USES_U16(m->fInputText)) { - srcIdx = (int32_t)nativeIdx; + srcIdx = static_cast(nativeIdx); } else { UErrorCode newStatus = U_ZERO_ERROR; srcIdx = utext_extract(m->fInputText, 0, nativeIdx, nullptr, 0, &newStatus); @@ -1842,7 +1842,7 @@ int32_t RegexCImpl::split(RegularExpression *regexp, // No fields are left. Recycle the last one for holding the trailing part of // the input string. i = destFieldsCapacity-1; - destIdx = (int32_t)(destFields[i] - destFields[0]); + destIdx = static_cast(destFields[i] - destFields[0]); } destFields[i] = (destBuf == nullptr) ? nullptr : &destBuf[destIdx]; @@ -1879,7 +1879,7 @@ int32_t RegexCImpl::split(RegularExpression *regexp, // Set up to extract the capture group contents into the dest buffer. destFields[i] = &destBuf[destIdx]; tStatus = U_ZERO_ERROR; - int32_t t = uregex_group((URegularExpression*)regexp, + int32_t t = uregex_group(reinterpret_cast(regexp), groupNum, destFields[i], REMAINING_CAPACITY(destIdx, destCapacity), diff --git a/icu4c/source/i18n/usearch.cpp b/icu4c/source/i18n/usearch.cpp index cc92b1ccaa53..d296c2874026 100644 --- a/icu4c/source/i18n/usearch.cpp +++ b/icu4c/source/i18n/usearch.cpp @@ -111,7 +111,7 @@ uint16_t getFCD(const char16_t *str, int32_t *offset, { const char16_t *temp = str + *offset; uint16_t result = g_nfcImpl->nextFCD16(temp, str + strlength); - *offset = (int32_t)(temp - str); + *offset = static_cast(temp - str); return result; } @@ -162,7 +162,7 @@ inline int32_t getCE(const UStringSearch *strsrch, uint32_t sourcece) static inline void * allocateMemory(uint32_t size, UErrorCode *status) { - uint32_t *result = (uint32_t *)uprv_malloc(size); + uint32_t* result = static_cast(uprv_malloc(size)); if (result == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; } @@ -196,8 +196,8 @@ inline int32_t * addTouint32_tArray(int32_t *destination, uint32_t newlength = *destinationlength; if (offset + 1 == newlength) { newlength += increments; - int32_t *temp = (int32_t *)allocateMemory( - sizeof(int32_t) * newlength, status); + int32_t* temp = static_cast(allocateMemory( + sizeof(int32_t) * newlength, status)); if (U_FAILURE(*status)) { return nullptr; } @@ -236,8 +236,8 @@ inline int64_t * addTouint64_tArray(int64_t *destination, uint32_t newlength = *destinationlength; if (offset + 1 == newlength) { newlength += increments; - int64_t *temp = (int64_t *)allocateMemory( - sizeof(int64_t) * newlength, status); + int64_t* temp = static_cast(allocateMemory( + sizeof(int64_t) * newlength, status)); if (U_FAILURE(*status)) { return nullptr; @@ -1432,7 +1432,7 @@ CEIBuffer::CEIBuffer(UStringSearch *ss, UErrorCode *status) { if (!initTextProcessedIter(ss, status)) { return; } if (bufSize>DEFAULT_CEBUFFER_SIZE) { - buf = (CEI *)uprv_malloc(bufSize * sizeof(CEI)); + buf = static_cast(uprv_malloc(bufSize * sizeof(CEI))); if (buf == nullptr) { *status = U_MEMORY_ALLOCATION_ERROR; } @@ -1705,8 +1705,8 @@ static UCompareCEsResult compareCE64s(int64_t targCE, int64_t patCE, int16_t com int64_t mask; mask = 0xFFFF0000; - int32_t targLev1 = (int32_t)(targCEshifted & mask); - int32_t patLev1 = (int32_t)(patCEshifted & mask); + int32_t targLev1 = static_cast(targCEshifted & mask); + int32_t patLev1 = static_cast(patCEshifted & mask); if ( targLev1 != patLev1 ) { if ( targLev1 == 0 ) { return U_CE_SKIP_TARG; @@ -1718,8 +1718,8 @@ static UCompareCEsResult compareCE64s(int64_t targCE, int64_t patCE, int16_t com } mask = 0x0000FFFF; - int32_t targLev2 = (int32_t)(targCEshifted & mask); - int32_t patLev2 = (int32_t)(patCEshifted & mask); + int32_t targLev2 = static_cast(targCEshifted & mask); + int32_t patLev2 = static_cast(patCEshifted & mask); if ( targLev2 != patLev2 ) { if ( targLev2 == 0 ) { return U_CE_SKIP_TARG; @@ -1732,8 +1732,8 @@ static UCompareCEsResult compareCE64s(int64_t targCE, int64_t patCE, int16_t com } mask = 0xFFFF0000; - int32_t targLev3 = (int32_t)(targCE & mask); - int32_t patLev3 = (int32_t)(patCE & mask); + int32_t targLev3 = static_cast(targCE & mask); + int32_t patLev3 = static_cast(patCE & mask); if ( targLev3 != patLev3 ) { return (patLev3 == U_CE_LEVEL3_BASE || (compareType == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD && targLev3 == U_CE_LEVEL3_BASE) )? U_CE_MATCH: U_CE_NO_MATCH; diff --git a/icu4c/source/i18n/uspoof_conf.cpp b/icu4c/source/i18n/uspoof_conf.cpp index dbbf627286a9..09e104ba5d8f 100644 --- a/icu4c/source/i18n/uspoof_conf.cpp +++ b/icu4c/source/i18n/uspoof_conf.cpp @@ -79,7 +79,7 @@ SPUStringPool::SPUStringPool(UErrorCode &status) : fVec(nullptr), fHash(nullptr) return; } vec->setDeleter( - [](void *obj) {delete (SPUString *)obj;}); + [](void *obj) {delete static_cast(obj);}); fVec = vec.orphan(); fHash = uhash_open(uhash_hashUnicodeString, // key hash function uhash_compareUnicodeString, // Key Comparator @@ -99,7 +99,7 @@ int32_t SPUStringPool::size() { } SPUString *SPUStringPool::getByIndex(int32_t index) { - SPUString *retString = (SPUString *)fVec->elementAt(index); + SPUString* retString = static_cast(fVec->elementAt(index)); return retString; } @@ -430,7 +430,7 @@ void ConfusabledataBuilder::outputData(UErrorCode &status) { previousCodePoint = codePoint; } SpoofDataHeader *rawData = fSpoofImpl->fSpoofData->fRawData; - rawData->fCFUKeys = (int32_t)((char *)keys - (char *)rawData); + rawData->fCFUKeys = static_cast(reinterpret_cast(keys) - reinterpret_cast(rawData)); rawData->fCFUKeysSize = numKeys; fSpoofImpl->fSpoofData->fCFUKeys = keys; @@ -449,7 +449,7 @@ void ConfusabledataBuilder::outputData(UErrorCode &status) { values[i] = static_cast(value); } rawData = fSpoofImpl->fSpoofData->fRawData; - rawData->fCFUStringIndex = (int32_t)((char *)values - (char *)rawData); + rawData->fCFUStringIndex = static_cast(reinterpret_cast(values) - reinterpret_cast(rawData)); rawData->fCFUStringIndexSize = numValues; fSpoofImpl->fSpoofData->fCFUValues = values; @@ -466,7 +466,7 @@ void ConfusabledataBuilder::outputData(UErrorCode &status) { fStringTable->extract(strings, stringsLength+1, status); rawData = fSpoofImpl->fSpoofData->fRawData; U_ASSERT(rawData->fCFUStringTable == 0); - rawData->fCFUStringTable = (int32_t)((char *)strings - (char *)rawData); + rawData->fCFUStringTable = static_cast(reinterpret_cast(strings) - reinterpret_cast(rawData)); rawData->fCFUStringTableLen = stringsLength; fSpoofImpl->fSpoofData->fCFUStrings = strings; } diff --git a/icu4c/source/i18n/uspoof_impl.cpp b/icu4c/source/i18n/uspoof_impl.cpp index 93402e670be2..c727fafb37b1 100644 --- a/icu4c/source/i18n/uspoof_impl.cpp +++ b/icu4c/source/i18n/uspoof_impl.cpp @@ -148,7 +148,7 @@ void SpoofImpl::setAllowedLocales(const char *localesList, UErrorCode &status) { if (trimmedEnd <= locStart) { break; } - const char *locale = uprv_strndup(locStart, (int32_t)(trimmedEnd + 1 - locStart)); + const char* locale = uprv_strndup(locStart, static_cast(trimmedEnd + 1 - locStart)); localeListCount++; // We have one locale from the locales list. @@ -305,7 +305,7 @@ void SpoofImpl::getNumerics(const UnicodeString& input, UnicodeSet& result, UErr if (u_charType(codePoint) == U_DECIMAL_DIGIT_NUMBER) { // Store the zero character as a representative for comparison. // Unicode guarantees it is codePoint - value - result.add(codePoint - (UChar32)u_getNumericValue(codePoint)); + result.add(codePoint - static_cast(u_getNumericValue(codePoint))); } } } @@ -432,7 +432,7 @@ UChar32 SpoofImpl::ScanHex(const char16_t *s, int32_t start, int32_t limit, UErr status = U_PARSE_ERROR; val = 0; } - return (UChar32)val; + return static_cast(val); } @@ -601,7 +601,7 @@ SpoofData::SpoofData(const void *data, int32_t length, UErrorCode &status) if (U_FAILURE(status)) { return; } - if ((size_t)length < sizeof(SpoofDataHeader)) { + if (static_cast(length) < sizeof(SpoofDataHeader)) { status = U_INVALID_FORMAT_ERROR; return; } @@ -688,13 +688,13 @@ void SpoofData::initPtrs(UErrorCode &status) { return; } if (fRawData->fCFUKeys != 0) { - fCFUKeys = (int32_t *)((char *)fRawData + fRawData->fCFUKeys); + fCFUKeys = reinterpret_cast(reinterpret_cast(fRawData) + fRawData->fCFUKeys); } if (fRawData->fCFUStringIndex != 0) { - fCFUValues = (uint16_t *)((char *)fRawData + fRawData->fCFUStringIndex); + fCFUValues = reinterpret_cast(reinterpret_cast(fRawData) + fRawData->fCFUStringIndex); } if (fRawData->fCFUStringTable != 0) { - fCFUStrings = (char16_t *)((char *)fRawData + fRawData->fCFUStringTable); + fCFUStrings = reinterpret_cast(reinterpret_cast(fRawData) + fRawData->fCFUStringTable); } } @@ -739,7 +739,7 @@ void *SpoofData::reserveSpace(int32_t numBytes, UErrorCode &status) { fRawData->fLength = fMemLimit; uprv_memset((char *)fRawData + returnOffset, 0, numBytes); initPtrs(status); - return (char *)fRawData + returnOffset; + return reinterpret_cast(fRawData) + returnOffset; } int32_t SpoofData::serialize(void *buf, int32_t capacity, UErrorCode &status) const { @@ -806,7 +806,7 @@ int32_t SpoofData::appendValueTo(int32_t index, UnicodeString& dest) const { // an index into the string table (for longer strings) uint16_t value = fCFUValues[index]; if (stringLength == 1) { - dest.append((char16_t)value); + dest.append(static_cast(value)); } else { dest.append(fCFUStrings + value, stringLength); } diff --git a/icu4c/source/i18n/utf16collationiterator.cpp b/icu4c/source/i18n/utf16collationiterator.cpp index e04721f7d7d4..64c454b5d368 100644 --- a/icu4c/source/i18n/utf16collationiterator.cpp +++ b/icu4c/source/i18n/utf16collationiterator.cpp @@ -53,7 +53,7 @@ UTF16CollationIterator::resetToOffset(int32_t newOffset) { int32_t UTF16CollationIterator::getOffset() const { - return (int32_t)(pos - start); + return static_cast(pos - start); } uint32_t @@ -198,11 +198,11 @@ FCDUTF16CollationIterator::resetToOffset(int32_t newOffset) { int32_t FCDUTF16CollationIterator::getOffset() const { if(checkDir != 0 || start == segmentStart) { - return (int32_t)(pos - rawStart); + return static_cast(pos - rawStart); } else if(pos == start) { - return (int32_t)(segmentStart - rawStart); + return static_cast(segmentStart - rawStart); } else { - return (int32_t)(segmentLimit - rawStart); + return static_cast(segmentLimit - rawStart); } } @@ -381,7 +381,7 @@ FCDUTF16CollationIterator::nextSegment(UErrorCode &errorCode) { // Fetch the next character's fcd16 value. const char16_t *q = p; uint16_t fcd16 = nfcImpl.nextFCD16(p, rawLimit); - uint8_t leadCC = (uint8_t)(fcd16 >> 8); + uint8_t leadCC = static_cast(fcd16 >> 8); if(leadCC == 0 && q != pos) { // FCD boundary before the [q, p[ character. limit = segmentLimit = q; @@ -396,7 +396,7 @@ FCDUTF16CollationIterator::nextSegment(UErrorCode &errorCode) { pos = start; break; } - prevCC = (uint8_t)fcd16; + prevCC = static_cast(fcd16); if(p == rawLimit || prevCC == 0) { // FCD boundary after the last character. limit = segmentLimit = p; @@ -445,7 +445,7 @@ FCDUTF16CollationIterator::previousSegment(UErrorCode &errorCode) { // Fetch the previous character's fcd16 value. const char16_t *q = p; uint16_t fcd16 = nfcImpl.previousFCD16(rawStart, p); - uint8_t trailCC = (uint8_t)fcd16; + uint8_t trailCC = static_cast(fcd16); if(trailCC == 0 && q != pos) { // FCD boundary after the [p, q[ character. start = segmentStart = q; @@ -462,7 +462,7 @@ FCDUTF16CollationIterator::previousSegment(UErrorCode &errorCode) { pos = limit; break; } - nextCC = (uint8_t)(fcd16 >> 8); + nextCC = static_cast(fcd16 >> 8); if(p == rawStart || nextCC == 0) { // FCD boundary before the following character. start = segmentStart = p; @@ -478,7 +478,7 @@ UBool FCDUTF16CollationIterator::normalize(const char16_t *from, const char16_t *to, UErrorCode &errorCode) { // NFD without argument checking. U_ASSERT(U_SUCCESS(errorCode)); - nfcImpl.decompose(from, to, normalized, (int32_t)(to - from), errorCode); + nfcImpl.decompose(from, to, normalized, static_cast(to - from), errorCode); if(U_FAILURE(errorCode)) { return false; } // Switch collation processing into the FCD buffer // with the result of normalizing [segmentStart, segmentLimit[. diff --git a/icu4c/source/i18n/utf8collationiterator.cpp b/icu4c/source/i18n/utf8collationiterator.cpp index ea7278afc6ca..470a757accd8 100644 --- a/icu4c/source/i18n/utf8collationiterator.cpp +++ b/icu4c/source/i18n/utf8collationiterator.cpp @@ -396,7 +396,7 @@ FCDUTF8CollationIterator::nextSegment(UErrorCode &errorCode) { UChar32 c; U8_NEXT_OR_FFFD(u8, pos, length, c); uint16_t fcd16 = nfcImpl.getFCD16(c); - uint8_t leadCC = (uint8_t)(fcd16 >> 8); + uint8_t leadCC = static_cast(fcd16 >> 8); if(leadCC == 0 && cpStart != segmentStart) { // FCD boundary before this character. pos = cpStart; @@ -421,7 +421,7 @@ FCDUTF8CollationIterator::nextSegment(UErrorCode &errorCode) { pos = 0; return true; } - prevCC = (uint8_t)fcd16; + prevCC = static_cast(fcd16); if(pos == length || prevCC == 0) { // FCD boundary after the last character. break; @@ -475,7 +475,7 @@ FCDUTF8CollationIterator::previousSegment(UErrorCode &errorCode) { UChar32 c; U8_PREV_OR_FFFD(u8, 0, pos, c); uint16_t fcd16 = nfcImpl.getFCD16(c); - uint8_t trailCC = (uint8_t)fcd16; + uint8_t trailCC = static_cast(fcd16); if(trailCC == 0 && cpLimit != segmentLimit) { // FCD boundary after this character. pos = cpLimit; @@ -503,7 +503,7 @@ FCDUTF8CollationIterator::previousSegment(UErrorCode &errorCode) { pos = normalized.length(); return true; } - nextCC = (uint8_t)(fcd16 >> 8); + nextCC = static_cast(fcd16 >> 8); if(pos == 0 || nextCC == 0) { // FCD boundary before the following character. break; diff --git a/icu4c/source/i18n/vtzone.cpp b/icu4c/source/i18n/vtzone.cpp index 250cc70193e1..6067c5490e8d 100644 --- a/icu4c/source/i18n/vtzone.cpp +++ b/icu4c/source/i18n/vtzone.cpp @@ -139,7 +139,7 @@ static UnicodeString& appendAsciiDigits(int32_t number, uint8_t length, UnicodeS str.append(MINUS); } for (i = length - 1; i >= 0; i--) { - str.append((char16_t)(digits[i] + 0x0030)); + str.append(static_cast(digits[i] + 0x0030)); } return str; } @@ -151,11 +151,11 @@ static UnicodeString& appendMillis(UDate date, UnicodeString& str) { int64_t number; if (date < MIN_MILLIS) { - number = (int64_t)MIN_MILLIS; + number = static_cast(MIN_MILLIS); } else if (date > MAX_MILLIS) { - number = (int64_t)MAX_MILLIS; + number = static_cast(MAX_MILLIS); } else { - number = (int64_t)date; + number = static_cast(date); } if (number < 0) { negative = true; @@ -163,7 +163,7 @@ static UnicodeString& appendMillis(UDate date, UnicodeString& str) { } i = 0; do { - digits[i++] = (int32_t)(number % 10); + digits[i++] = static_cast(number % 10); number /= 10; } while (number != 0); @@ -172,7 +172,7 @@ static UnicodeString& appendMillis(UDate date, UnicodeString& str) { } i--; while (i >= 0) { - str.append((char16_t)(digits[i--] + 0x0030)); + str.append(static_cast(digits[i--] + 0x0030)); } return str; } @@ -190,7 +190,7 @@ static UnicodeString& getDateTimeString(UDate time, UnicodeString& str, UErrorCo appendAsciiDigits(year, 4, str); appendAsciiDigits(month + 1, 2, str); appendAsciiDigits(dom, 2, str); - str.append((char16_t)0x0054 /*'T'*/); + str.append(static_cast(0x0054) /*'T'*/); int32_t t = mid; int32_t hour = t / U_MILLIS_PER_HOUR; @@ -210,7 +210,7 @@ static UnicodeString& getDateTimeString(UDate time, UnicodeString& str, UErrorCo */ static UnicodeString& getUTCDateTimeString(UDate time, UnicodeString& str, UErrorCode& status) { getDateTimeString(time, str, status); - str.append((char16_t)0x005A /*'Z'*/); + str.append(static_cast(0x005A) /*'Z'*/); return str; } @@ -531,7 +531,7 @@ static TimeZoneRule* createRuleByRRULE(const UnicodeString& zonename, int rawOff DateTimeRule *adtr = nullptr; // Parse the first rule - UnicodeString rrule = *((UnicodeString*)dates->elementAt(0)); + UnicodeString rrule = *static_cast(dates->elementAt(0)); int32_t month, dayOfWeek, nthDayOfWeek, dayOfMonth = 0; int32_t days[7]; int32_t daysCount = UPRV_LENGTHOF(days); @@ -607,7 +607,7 @@ static TimeZoneRule* createRuleByRRULE(const UnicodeString& zonename, int rawOff int32_t anotherMonth = -1; for (i = 1; i < dates->size(); i++) { - rrule = *((UnicodeString*)dates->elementAt(i)); + rrule = *static_cast(dates->elementAt(i)); UDate tmp_until; int32_t tmp_month, tmp_dayOfWeek, tmp_nthDayOfWeek; int32_t tmp_days[7]; @@ -737,13 +737,13 @@ static TimeZoneRule* createRuleByRDATE(const UnicodeString& zonename, int32_t ra } else { // Create an array of transition times int32_t size = dates->size(); - UDate* times = (UDate*)uprv_malloc(sizeof(UDate) * size); + UDate* times = static_cast(uprv_malloc(sizeof(UDate) * size)); if (times == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; } for (int32_t i = 0; i < size; i++) { - UnicodeString *datestr = (UnicodeString*)dates->elementAt(i); + UnicodeString* datestr = static_cast(dates->elementAt(i)); times[i] = parseDateTimeString(*datestr, fromOffset, status); if (U_FAILURE(status)) { uprv_free(times); @@ -980,7 +980,7 @@ VTimeZone::VTimeZone(const VTimeZone& source) return; } for (int32_t i = 0; i < size; i++) { - UnicodeString *line = ((UnicodeString*)source.vtzlines->elementAt(i))->clone(); + UnicodeString* line = static_cast(source.vtzlines->elementAt(i))->clone(); lpVtzLines->adoptElement(line, status); if (U_FAILURE(status) || line == nullptr) { return; @@ -1021,7 +1021,7 @@ VTimeZone::operator=(const VTimeZone& right) { if (U_SUCCESS(status)) { for (int32_t i = 0; i < size; i++) { LocalPointer line( - ((UnicodeString*)right.vtzlines->elementAt(i))->clone(), status); + static_cast(right.vtzlines->elementAt(i))->clone(), status); lpVtzLines->adoptElement(line.orphan(), status); if (U_FAILURE(status)) { break; @@ -1401,7 +1401,7 @@ VTimeZone::parse(UErrorCode& status) { } for (n = 0; n < vtzlines->size(); n++) { - UnicodeString *line = (UnicodeString*)vtzlines->elementAt(n); + UnicodeString* line = static_cast(vtzlines->elementAt(n)); int32_t valueSep = line->indexOf(COLON); if (valueSep < 0) { continue; @@ -1612,7 +1612,7 @@ VTimeZone::parse(UErrorCode& status) { } for (n = 0; n < rules.size(); n++) { - TimeZoneRule *r = (TimeZoneRule*)rules.elementAt(n); + TimeZoneRule* r = static_cast(rules.elementAt(n)); AnnualTimeZoneRule *atzrule = dynamic_cast(r); if (atzrule != nullptr) { if (atzrule->getEndYear() == AnnualTimeZoneRule::MAX_YEAR) { @@ -1635,7 +1635,7 @@ VTimeZone::parse(UErrorCode& status) { rules.removeAllElements(); } else { // Normalize the final rule - AnnualTimeZoneRule *finalRule = (AnnualTimeZoneRule*)rules.elementAt(finalRuleIdx); + AnnualTimeZoneRule* finalRule = static_cast(rules.elementAt(finalRuleIdx)); int32_t tmpRaw = finalRule->getRawOffset(); int32_t tmpDST = finalRule->getDSTSavings(); @@ -1647,7 +1647,7 @@ VTimeZone::parse(UErrorCode& status) { if (finalRuleIdx == n) { continue; } - TimeZoneRule *r = (TimeZoneRule*)rules.elementAt(n); + TimeZoneRule* r = static_cast(rules.elementAt(n)); UDate lastStart; r->getFinalStart(tmpRaw, tmpDST, lastStart); if (lastStart > start) { @@ -1699,7 +1699,7 @@ VTimeZone::parse(UErrorCode& status) { } while (!rules.isEmpty()) { - TimeZoneRule *tzr = (TimeZoneRule*)rules.orphanElementAt(0); + TimeZoneRule* tzr = static_cast(rules.orphanElementAt(0)); rbtz->addTransitionRule(tzr, status); if (U_FAILURE(status)) { return; @@ -1719,7 +1719,7 @@ VTimeZone::write(VTZWriter& writer, UErrorCode& status) const { if (U_FAILURE(status)) return; if (vtzlines != nullptr) { for (int32_t i = 0; i < vtzlines->size(); i++) { - UnicodeString *line = (UnicodeString*)vtzlines->elementAt(i); + UnicodeString* line = static_cast(vtzlines->elementAt(i)); if (line->startsWith(ICAL_TZURL, -1) && line->charAt(u_strlen(ICAL_TZURL)) == COLON) { writer.write(ICAL_TZURL); @@ -1777,7 +1777,7 @@ VTimeZone::write(UDate start, VTZWriter& writer, UErrorCode& status) const { if (lpTransitionRules.isValid()) { U_ASSERT(transitionRules->hasDeleter()); // Assumed for U_FAILURE early return, below. while (!lpTransitionRules->isEmpty()) { - TimeZoneRule *tr = (TimeZoneRule*)lpTransitionRules->orphanElementAt(0); + TimeZoneRule* tr = static_cast(lpTransitionRules->orphanElementAt(0)); rbtz.addTransitionRule(tr, status); if (U_FAILURE(status)) { return; @@ -1796,11 +1796,11 @@ VTimeZone::write(UDate start, VTZWriter& writer, UErrorCode& status) const { return; } icutzprop->append(olsonzid); - icutzprop->append((char16_t)0x005B/*'['*/); + icutzprop->append(static_cast(0x005B)/*'['*/); icutzprop->append(icutzver); icutzprop->append(ICU_TZINFO_PARTIAL, -1); appendMillis(start, *icutzprop); - icutzprop->append((char16_t)0x005D/*']'*/); + icutzprop->append(static_cast(0x005D)/*']'*/); customProps.adoptElement(icutzprop, status); if (U_FAILURE(status)) { return; @@ -1843,11 +1843,11 @@ VTimeZone::writeSimple(UDate time, VTZWriter& writer, UErrorCode& status) const return; } icutzprop->append(olsonzid); - icutzprop->append((char16_t)0x005B/*'['*/); + icutzprop->append(static_cast(0x005B)/*'['*/); icutzprop->append(icutzver); icutzprop->append(ICU_TZINFO_SIMPLE, -1); appendMillis(time, *icutzprop); - icutzprop->append((char16_t)0x005D/*']'*/); + icutzprop->append(static_cast(0x005D)/*']'*/); customProps.adoptElement(icutzprop.orphan(), status); } writeZone(writer, rbtz, &customProps, status); @@ -1867,7 +1867,7 @@ VTimeZone::writeZone(VTZWriter& w, BasicTimeZone& basictz, if (customProps != nullptr) { for (int32_t i = 0; i < customProps->size(); i++) { - UnicodeString *custprop = (UnicodeString*)customProps->elementAt(i); + UnicodeString* custprop = static_cast(customProps->elementAt(i)); w.write(*custprop); w.write(ICAL_NEWLINE); } diff --git a/icu4c/source/i18n/zonemeta.cpp b/icu4c/source/i18n/zonemeta.cpp index 78d2391479f2..6257d4a2b9ca 100644 --- a/icu4c/source/i18n/zonemeta.cpp +++ b/icu4c/source/i18n/zonemeta.cpp @@ -258,7 +258,7 @@ ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UErrorCode& status) { // Check if it was already cached umtx_lock(&gZoneMetaLock); { - canonicalID = (const char16_t *)uhash_get(gCanonicalIDCache, utzid); + canonicalID = static_cast(uhash_get(gCanonicalIDCache, utzid)); } umtx_unlock(&gZoneMetaLock); @@ -309,7 +309,7 @@ ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UErrorCode& status) { } else { int32_t len = u_strlen(derefer); u_UCharsToChars(derefer,id,len); - id[len] = (char) 0; // Make sure it is null terminated. + id[len] = static_cast(0); // Make sure it is null terminated. // replace '/' with ':' char *q = id; @@ -343,20 +343,20 @@ ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UErrorCode& status) { // Put the resolved canonical ID to the cache umtx_lock(&gZoneMetaLock); { - const char16_t* idInCache = (const char16_t *)uhash_get(gCanonicalIDCache, utzid); + const char16_t* idInCache = static_cast(uhash_get(gCanonicalIDCache, utzid)); if (idInCache == nullptr) { const char16_t* key = ZoneMeta::findTimeZoneID(tzid); U_ASSERT(key != nullptr); if (key != nullptr) { - idInCache = (const char16_t *)uhash_put(gCanonicalIDCache, (void *)key, (void *)canonicalID, &status); + idInCache = static_cast(uhash_put(gCanonicalIDCache, const_cast(key), const_cast(canonicalID), &status)); U_ASSERT(idInCache == nullptr); } } if (U_SUCCESS(status) && isInputCanonical) { // Also put canonical ID itself into the cache if not exist - const char16_t *canonicalInCache = (const char16_t*)uhash_get(gCanonicalIDCache, canonicalID); + const char16_t* canonicalInCache = static_cast(uhash_get(gCanonicalIDCache, canonicalID)); if (canonicalInCache == nullptr) { - canonicalInCache = (const char16_t *)uhash_put(gCanonicalIDCache, (void *)canonicalID, (void *)canonicalID, &status); + canonicalInCache = static_cast(uhash_put(gCanonicalIDCache, const_cast(canonicalID), const_cast(canonicalID), &status)); U_ASSERT(canonicalInCache == nullptr); } } @@ -550,7 +550,7 @@ ZoneMeta::getMetazoneID(const UnicodeString &tzid, UDate date, UnicodeString &re const UVector *mappings = getMetazoneMappings(tzid); if (mappings != nullptr) { for (int32_t i = 0; i < mappings->size(); i++) { - OlsonToMetaMappingEntry *mzm = (OlsonToMetaMappingEntry*)mappings->elementAt(i); + OlsonToMetaMappingEntry* mzm = static_cast(mappings->elementAt(i)); if (mzm->from <= date && mzm->to > date) { result.setTo(mzm->mzid, -1); isSet = true; @@ -596,7 +596,7 @@ ZoneMeta::getMetazoneMappings(const UnicodeString &tzid) { umtx_lock(&gZoneMetaLock); { - result = (UVector*) uhash_get(gOlsonToMeta, tzidUChars); + result = static_cast(uhash_get(gOlsonToMeta, tzidUChars)); } umtx_unlock(&gZoneMetaLock); @@ -615,11 +615,11 @@ ZoneMeta::getMetazoneMappings(const UnicodeString &tzid) { umtx_lock(&gZoneMetaLock); { // make sure it's already created - result = (UVector*) uhash_get(gOlsonToMeta, tzidUChars); + result = static_cast(uhash_get(gOlsonToMeta, tzidUChars)); if (result == nullptr) { // add the one just created int32_t tzidLen = tzid.length() + 1; - char16_t *key = (char16_t*)uprv_malloc(tzidLen * sizeof(char16_t)); + char16_t* key = static_cast(uprv_malloc(tzidLen * sizeof(char16_t))); if (key == nullptr) { // memory allocation error.. just return nullptr result = nullptr; @@ -806,7 +806,7 @@ static void U_CALLCONV initAvailableMetaZoneIDs () { } const char *mzID = ures_getKey(res.getAlias()); int32_t len = static_cast(uprv_strlen(mzID)); - LocalMemory uMzID((char16_t*)uprv_malloc(sizeof(char16_t) * (len + 1))); + LocalMemory uMzID(static_cast(uprv_malloc(sizeof(char16_t) * (len + 1)))); if (uMzID.isNull()) { status = U_MEMORY_ALLOCATION_ERROR; break; @@ -847,7 +847,7 @@ ZoneMeta::findMetaZoneID(const UnicodeString& mzid) { if (gMetaZoneIDTable == nullptr) { return nullptr; } - return (const char16_t*)uhash_get(gMetaZoneIDTable, &mzid); + return static_cast(uhash_get(gMetaZoneIDTable, &mzid)); } const char16_t* @@ -883,20 +883,20 @@ ZoneMeta::formatCustomID(uint8_t hour, uint8_t min, uint8_t sec, UBool negative, id.setTo(gCustomTzPrefix, -1); if (hour != 0 || min != 0) { if (negative) { - id.append((char16_t)0x2D); // '-' + id.append(static_cast(0x2D)); // '-' } else { - id.append((char16_t)0x2B); // '+' + id.append(static_cast(0x2B)); // '+' } // Always use US-ASCII digits - id.append((char16_t)(0x30 + (hour%100)/10)); - id.append((char16_t)(0x30 + (hour%10))); - id.append((char16_t)0x3A); // ':' - id.append((char16_t)(0x30 + (min%100)/10)); - id.append((char16_t)(0x30 + (min%10))); + id.append(static_cast(0x30 + (hour % 100) / 10)); + id.append(static_cast(0x30 + (hour % 10))); + id.append(static_cast(0x3A)); // ':' + id.append(static_cast(0x30 + (min % 100) / 10)); + id.append(static_cast(0x30 + (min % 10))); if (sec != 0) { - id.append((char16_t)0x3A); // ':' - id.append((char16_t)(0x30 + (sec%100)/10)); - id.append((char16_t)(0x30 + (sec%10))); + id.append(static_cast(0x3A)); // ':' + id.append(static_cast(0x30 + (sec % 100) / 10)); + id.append(static_cast(0x30 + (sec % 10))); } } return id; @@ -933,7 +933,7 @@ ZoneMeta::getShortIDFromCanonical(const char16_t* canonicalID) { char tzidKey[ZID_KEY_MAX + 1]; u_UCharsToChars(canonicalID, tzidKey, len); - tzidKey[len] = (char) 0; // Make sure it is null terminated. + tzidKey[len] = static_cast(0); // Make sure it is null terminated. // replace '/' with ':' char *p = tzidKey; diff --git a/icu4c/source/io/sprintf.cpp b/icu4c/source/io/sprintf.cpp index 792ad00fd996..47b2296ffc9b 100644 --- a/icu4c/source/io/sprintf.cpp +++ b/icu4c/source/io/sprintf.cpp @@ -40,7 +40,7 @@ u_sprintf_write(void *context, const char16_t *str, int32_t count) { - u_localized_print_string *output = (u_localized_print_string *)context; + u_localized_print_string* output = static_cast(context); /* just calculating buffer size */ if (output->str == nullptr) { @@ -60,7 +60,7 @@ u_sprintf_pad_and_justify(void *context, const char16_t *result, int32_t resultLen) { - u_localized_print_string *output = (u_localized_print_string *)context; + u_localized_print_string* output = static_cast(context); int32_t written = 0; int32_t lengthOfResult = resultLen; @@ -193,7 +193,7 @@ u_vsnprintf(char16_t *buffer, int32_t size = (int32_t)strlen(patternSpecification) + 1; /* convert from the default codepage to Unicode */ - if (size >= (int32_t)MAX_UCHAR_BUFFER_SIZE(patBuffer)) { + if (size >= MAX_UCHAR_BUFFER_SIZE(patBuffer)) { pattern = (char16_t *)uprv_malloc(size * sizeof(char16_t)); if (pattern == nullptr) { return 0; diff --git a/icu4c/source/io/sscanf.cpp b/icu4c/source/io/sscanf.cpp index deef15d40c6b..ab5c6cd9c40c 100644 --- a/icu4c/source/io/sscanf.cpp +++ b/icu4c/source/io/sscanf.cpp @@ -73,7 +73,7 @@ u_vsscanf(const char16_t *buffer, int32_t size = (int32_t)uprv_strlen(patternSpecification) + 1; /* convert from the default codepage to Unicode */ - if (size >= (int32_t)MAX_UCHAR_BUFFER_SIZE(patBuffer)) { + if (size >= MAX_UCHAR_BUFFER_SIZE(patBuffer)) { pattern = (char16_t *)uprv_malloc(size * sizeof(char16_t)); if (pattern == nullptr) { return 0; diff --git a/icu4c/source/io/ufile.cpp b/icu4c/source/io/ufile.cpp index 9d8330743f44..67930fda544a 100644 --- a/icu4c/source/io/ufile.cpp +++ b/icu4c/source/io/ufile.cpp @@ -71,7 +71,7 @@ finit_owner(FILE *f, if(f == nullptr) { return nullptr; } - result = (UFILE*) uprv_malloc(sizeof(UFILE)); + result = static_cast(uprv_malloc(sizeof(UFILE))); if(result == nullptr) { return nullptr; } diff --git a/icu4c/source/io/ufmt_cmn.cpp b/icu4c/source/io/ufmt_cmn.cpp index 85262729391a..0202783f8b5e 100644 --- a/icu4c/source/io/ufmt_cmn.cpp +++ b/icu4c/source/io/ufmt_cmn.cpp @@ -58,7 +58,7 @@ ufmt_isdigit(char16_t c, { int digitVal = ufmt_digitvalue(c); - return (UBool)(digitVal < radix && digitVal >= 0); + return static_cast(digitVal < radix && digitVal >= 0); } #define TO_UC_DIGIT(a) a <= 9 ? (DIGIT_0 + a) : (0x0037 + a) @@ -77,9 +77,9 @@ ufmt_64tou(char16_t *buffer, char16_t *left, *right, temp; do { - digit = (uint32_t)(value % radix); + digit = static_cast(value % radix); value = value / radix; - buffer[length++] = (char16_t)(uselower ? TO_LC_DIGIT(digit) + buffer[length++] = static_cast(uselower ? TO_LC_DIGIT(digit) : TO_UC_DIGIT(digit)); } while(value); @@ -109,17 +109,17 @@ ufmt_ptou(char16_t *buffer, { int32_t i; int32_t length = 0; - uint8_t *ptrIdx = (uint8_t *)&value; + uint8_t* ptrIdx = reinterpret_cast(&value); #if U_IS_BIG_ENDIAN for (i = 0; i < (int32_t)sizeof(void *); i++) #else - for (i = (int32_t)sizeof(void *)-1; i >= 0 ; i--) + for (i = static_cast(sizeof(void*)) - 1; i >= 0; i--) #endif { uint8_t byteVal = ptrIdx[i]; - uint16_t firstNibble = (uint16_t)(byteVal>>4); - uint16_t secondNibble = (uint16_t)(byteVal&0xF); + uint16_t firstNibble = static_cast(byteVal >> 4); + uint16_t secondNibble = static_cast(byteVal & 0xF); if (uselower) { buffer[length++]=TO_LC_DIGIT(firstNibble); buffer[length++]=TO_LC_DIGIT(secondNibble); @@ -193,8 +193,8 @@ ufmt_utop(const char16_t *buffer, } /* detect overflow */ - if (count - offset > (int32_t)(sizeof(void*)*NIBBLE_PER_BYTE)) { - offset = count - (int32_t)(sizeof(void*)*NIBBLE_PER_BYTE); + if (count - offset > static_cast(sizeof(void*) * NIBBLE_PER_BYTE)) { + offset = count - static_cast(sizeof(void*) * NIBBLE_PER_BYTE); } /* Initialize the direction of the input */ @@ -209,11 +209,11 @@ ufmt_utop(const char16_t *buffer, *len = count; while(--count >= offset) { /* Get the first nibble of the byte */ - uint8_t byte = (uint8_t)ufmt_digitvalue(buffer[count]); + uint8_t byte = static_cast(ufmt_digitvalue(buffer[count])); if (count > offset) { /* Get the second nibble of the byte when available */ - byte = (uint8_t)(byte + (ufmt_digitvalue(buffer[--count]) << 4)); + byte = static_cast(byte + (ufmt_digitvalue(buffer[--count]) << 4)); } /* Write the byte into the array */ result.bytes[resultIdx] = byte; diff --git a/icu4c/source/io/uprintf.cpp b/icu4c/source/io/uprintf.cpp index c2e1f308afd1..f246b83ef6bd 100644 --- a/icu4c/source/io/uprintf.cpp +++ b/icu4c/source/io/uprintf.cpp @@ -71,7 +71,7 @@ u_printf_write(void *context, const char16_t *str, int32_t count) { - return u_file_write(str, count, (UFILE *)context); + return u_file_write(str, count, static_cast(context)); } static int32_t @@ -80,7 +80,7 @@ u_printf_pad_and_justify(void *context, const char16_t *result, int32_t resultLen) { - UFILE *output = (UFILE *)context; + UFILE* output = static_cast(context); int32_t written, i; /* pad and justify, if needed */ diff --git a/icu4c/source/io/uprntf_p.cpp b/icu4c/source/io/uprntf_p.cpp index 06d0f789d693..6146995dee49 100644 --- a/icu4c/source/io/uprntf_p.cpp +++ b/icu4c/source/io/uprntf_p.cpp @@ -206,14 +206,14 @@ u_printf_string_handler(const u_printf_stream_handler *handler, char16_t buffer[UFMT_DEFAULT_BUFFER_SIZE]; int32_t len, written; int32_t argSize; - const char *arg = (const char*)(args[0].ptrValue); + const char* arg = static_cast(args[0].ptrValue); /* convert from the default codepage to Unicode */ if (arg) { - argSize = (int32_t)strlen(arg) + 1; + argSize = static_cast(strlen(arg)) + 1; if (argSize >= MAX_UCHAR_BUFFER_SIZE(buffer)) { s = ufmt_defaultCPToUnicode(arg, argSize, - (char16_t *)uprv_malloc(MAX_UCHAR_BUFFER_NEEDED(argSize)), + static_cast(uprv_malloc(MAX_UCHAR_BUFFER_NEEDED(argSize))), MAX_UCHAR_BUFFER_NEEDED(argSize)); if(s == nullptr) { return 0; @@ -255,10 +255,10 @@ u_printf_char_handler(const u_printf_stream_handler *handler, (void)formatBundle; char16_t s[U16_MAX_LENGTH+1]; int32_t len = 1, written; - unsigned char arg = (unsigned char)(args[0].int64Value); + unsigned char arg = static_cast(args[0].int64Value); /* convert from default codepage to Unicode */ - ufmt_defaultCPToUnicode((const char *)&arg, 2, s, UPRV_LENGTHOF(s)); + ufmt_defaultCPToUnicode(reinterpret_cast(&arg), 2, s, UPRV_LENGTHOF(s)); /* Remember that this may be an MBCS character */ if (arg != 0) { @@ -281,7 +281,7 @@ u_printf_double_handler(const u_printf_stream_handler *handler, const u_printf_spec_info *info, const ufmt_args *args) { - double num = (double) (args[0].doubleValue); + double num = args[0].doubleValue; UNumberFormat *format; char16_t result[UPRINTF_BUFFER_SIZE]; char16_t prefixBuffer[UPRINTF_BUFFER_SIZE]; @@ -370,9 +370,9 @@ u_printf_integer_handler(const u_printf_stream_handler *handler, /* mask off any necessary bits */ if (info->fIsShort) - num = (int16_t)num; + num = static_cast(num); else if (!info->fIsLongLong) - num = (int32_t)num; + num = static_cast(num); /* get the formatter */ format = u_locbund_getNumberFormat(formatBundle, UNUM_DECIMAL); @@ -437,7 +437,7 @@ u_printf_hex_handler(const u_printf_stream_handler *handler, /* format the number, preserving the minimum # of digits */ ufmt_64tou(result, &len, num, 16, - (UBool)(info->fSpec == 0x0078), + static_cast(info->fSpec == 0x0078), (info->fPrecision == -1 && info->fZero) ? info->fWidth : info->fPrecision); /* convert to alt form, if desired */ @@ -564,7 +564,7 @@ u_printf_scientific_handler(const u_printf_stream_handler *handler, const u_printf_spec_info *info, const ufmt_args *args) { - double num = (double) (args[0].doubleValue); + double num = args[0].doubleValue; UNumberFormat *format; char16_t result[UPRINTF_BUFFER_SIZE]; char16_t prefixBuffer[UPRINTF_BUFFER_SIZE]; @@ -599,14 +599,14 @@ u_printf_scientific_handler(const u_printf_stream_handler *handler, &status); /* Upper/lower case the e */ - if (info->fSpec == (char16_t)0x65 /* e */) { - expLen = u_strToLower(expBuf, (int32_t)sizeof(expBuf), + if (info->fSpec == static_cast(0x65) /* e */) { + expLen = u_strToLower(expBuf, static_cast(sizeof(expBuf)), srcExpBuf, srcLen, formatBundle->fLocale, &status); } else { - expLen = u_strToUpper(expBuf, (int32_t)sizeof(expBuf), + expLen = u_strToUpper(expBuf, static_cast(sizeof(expBuf)), srcExpBuf, srcLen, formatBundle->fLocale, &status); @@ -625,7 +625,8 @@ u_printf_scientific_handler(const u_printf_stream_handler *handler, /* set the appropriate flags and number of decimal digits on the formatter */ if(info->fPrecision != -1) { /* set the # of decimal digits */ - if (info->fOrigSpec == (char16_t)0x65 /* e */ || info->fOrigSpec == (char16_t)0x45 /* E */) { + if (info->fOrigSpec == static_cast(0x65) /* e */ || + info->fOrigSpec == static_cast(0x45) /* E */) { unum_setAttribute(format, UNUM_FRACTION_DIGITS, info->fPrecision); } else { @@ -684,7 +685,7 @@ u_printf_percent_handler(const u_printf_stream_handler *handler, const u_printf_spec_info *info, const ufmt_args *args) { - double num = (double) (args[0].doubleValue); + double num = args[0].doubleValue; UNumberFormat *format; char16_t result[UPRINTF_BUFFER_SIZE]; char16_t prefixBuffer[UPRINTF_BUFFER_SIZE]; @@ -761,7 +762,7 @@ u_printf_ustring_handler(const u_printf_stream_handler *handler, { (void)formatBundle; int32_t len, written; - const char16_t *arg = (const char16_t*)(args[0].ptrValue); + const char16_t* arg = static_cast(args[0].ptrValue); /* allocate enough space for the buffer */ if (arg == nullptr) { @@ -790,7 +791,7 @@ u_printf_uchar_handler(const u_printf_stream_handler *handler, { (void)formatBundle; int32_t written = 0; - char16_t arg = (char16_t)(args[0].int64Value); + char16_t arg = static_cast(args[0].int64Value); /* width = minimum # of characters to write */ /* precision = maximum # of characters to write */ @@ -871,7 +872,7 @@ u_printf_count_handler(const u_printf_stream_handler *handler, (void)handler; (void)context; (void)formatBundle; - int32_t *count = (int32_t*)(args[0].ptrValue); + int32_t* count = static_cast(args[0].ptrValue); /* in the special case of count, the u_printf_spec_info's width */ /* will contain the # of chars written thus far */ @@ -887,7 +888,7 @@ u_printf_spellout_handler(const u_printf_stream_handler *handler, const u_printf_spec_info *info, const ufmt_args *args) { - double num = (double) (args[0].doubleValue); + double num = args[0].doubleValue; UNumberFormat *format; char16_t result[UPRINTF_BUFFER_SIZE]; char16_t prefixBuffer[UPRINTF_BUFFER_SIZE]; @@ -1086,11 +1087,11 @@ static ufmt_args* parseArguments(const char16_t *alias, va_list ap, UErrorCode * /* handle positional parameters */ if(ISDIGIT(*alias)) { - pos = (int) (*alias++ - DIGIT_ZERO); + pos = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { pos *= 10; - pos += (int) (*alias++ - DIGIT_ZERO); + pos += *alias++ - DIGIT_ZERO; } } @@ -1108,9 +1109,9 @@ static ufmt_args* parseArguments(const char16_t *alias, va_list ap, UErrorCode * } /* create the parsed argument list */ - typelist = (ufmt_type_info*)uprv_malloc(sizeof(ufmt_type_info) * size); - islonglong = (UBool*)uprv_malloc(sizeof(UBool) * size); - arglist = (ufmt_args*)uprv_malloc(sizeof(ufmt_args) * size); + typelist = static_cast(uprv_malloc(sizeof(ufmt_type_info) * size)); + islonglong = static_cast(uprv_malloc(sizeof(UBool) * size)); + arglist = static_cast(uprv_malloc(sizeof(ufmt_args) * size)); /* If malloc failed, return nullptr */ if (!typelist || !islonglong || !arglist) { @@ -1147,11 +1148,11 @@ static ufmt_args* parseArguments(const char16_t *alias, va_list ap, UErrorCode * /* handle positional parameters */ if(ISDIGIT(*alias)) { - pos = (int) (*alias++ - DIGIT_ZERO); + pos = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { pos *= 10; - pos += (int) (*alias++ - DIGIT_ZERO); + pos += *alias++ - DIGIT_ZERO; } } /* offset position by 1 */ @@ -1172,7 +1173,7 @@ static ufmt_args* parseArguments(const char16_t *alias, va_list ap, UErrorCode * type = *alias; /* store the argument type in the correct position of the parsed argument list */ - handlerNum = (uint16_t)(type - UPRINTF_BASE_FMT_HANDLERS); + handlerNum = static_cast(type - UPRINTF_BASE_FMT_HANDLERS); if (handlerNum < UPRINTF_NUM_FMT_HANDLERS) { typelist[pos] = g_u_printf_infos[ handlerNum ].info; } else { @@ -1199,7 +1200,7 @@ static ufmt_args* parseArguments(const char16_t *alias, va_list ap, UErrorCode * } break; case ufmt_float: - arglist[pos].floatValue = (float) va_arg(ap, double); + arglist[pos].floatValue = static_cast(va_arg(ap, double)); break; case ufmt_double: arglist[pos].doubleValue = va_arg(ap, double); @@ -1291,11 +1292,11 @@ u_printf_parse(const u_printf_stream_handler *streamHandler, /* handle positional parameters */ if(ISDIGIT(*alias)) { - spec.fArgPos = (int) (*alias++ - DIGIT_ZERO); + spec.fArgPos = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { spec.fArgPos *= 10; - spec.fArgPos += (int) (*alias++ - DIGIT_ZERO); + spec.fArgPos += *alias++ - DIGIT_ZERO; } } @@ -1372,11 +1373,11 @@ u_printf_parse(const u_printf_stream_handler *streamHandler, /* handle positional parameters */ if(ISDIGIT(*alias)) { - spec.fWidthPos = (int) (*alias++ - DIGIT_ZERO); + spec.fWidthPos = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { spec.fWidthPos *= 10; - spec.fWidthPos += (int) (*alias++ - DIGIT_ZERO); + spec.fWidthPos += *alias++ - DIGIT_ZERO; } } @@ -1391,11 +1392,11 @@ u_printf_parse(const u_printf_stream_handler *streamHandler, } /* read the width, if present */ else if(ISDIGIT(*alias)){ - info->fWidth = (int) (*alias++ - DIGIT_ZERO); + info->fWidth = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { info->fWidth *= 10; - info->fWidth += (int) (*alias++ - DIGIT_ZERO); + info->fWidth += *alias++ - DIGIT_ZERO; } } @@ -1419,11 +1420,11 @@ u_printf_parse(const u_printf_stream_handler *streamHandler, /* handle positional parameters */ if(ISDIGIT(*alias)) { - spec.fPrecisionPos = (int) (*alias++ - DIGIT_ZERO); + spec.fPrecisionPos = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { spec.fPrecisionPos *= 10; - spec.fPrecisionPos += (int) (*alias++ - DIGIT_ZERO); + spec.fPrecisionPos += *alias++ - DIGIT_ZERO; } /* if there is no '$', don't read anything */ @@ -1439,11 +1440,11 @@ u_printf_parse(const u_printf_stream_handler *streamHandler, } /* read the precision */ else if(ISDIGIT(*alias)){ - info->fPrecision = (int) (*alias++ - DIGIT_ZERO); + info->fPrecision = *alias++ - DIGIT_ZERO; while(ISDIGIT(*alias)) { info->fPrecision *= 10; - info->fPrecision += (int) (*alias++ - DIGIT_ZERO); + info->fPrecision += *alias++ - DIGIT_ZERO; } } } diff --git a/icu4c/source/io/uscanf_p.cpp b/icu4c/source/io/uscanf_p.cpp index 3def83e1ff58..85222ed2d593 100644 --- a/icu4c/source/io/uscanf_p.cpp +++ b/icu4c/source/io/uscanf_p.cpp @@ -144,11 +144,11 @@ u_scanf_parse_spec (const char16_t *fmt, /* handle positional parameters */ if(ISDIGIT(*s)) { - spec->fArgPos = (int) (*s++ - DIGIT_ZERO); + spec->fArgPos = *s++ - DIGIT_ZERO; while(ISDIGIT(*s)) { spec->fArgPos *= 10; - spec->fArgPos += (int) (*s++ - DIGIT_ZERO); + spec->fArgPos += *s++ - DIGIT_ZERO; } } @@ -175,10 +175,10 @@ u_scanf_parse_spec (const char16_t *fmt, case FLAG_PAREN: /* first four characters are hex values for pad char */ - info->fPadChar = (char16_t)ufmt_digitvalue(*s++); - info->fPadChar = (char16_t)((info->fPadChar * 16) + ufmt_digitvalue(*s++)); - info->fPadChar = (char16_t)((info->fPadChar * 16) + ufmt_digitvalue(*s++)); - info->fPadChar = (char16_t)((info->fPadChar * 16) + ufmt_digitvalue(*s++)); + info->fPadChar = static_cast(ufmt_digitvalue(*s++)); + info->fPadChar = static_cast((info->fPadChar * 16) + ufmt_digitvalue(*s++)); + info->fPadChar = static_cast((info->fPadChar * 16) + ufmt_digitvalue(*s++)); + info->fPadChar = static_cast((info->fPadChar * 16) + ufmt_digitvalue(*s++)); /* final character is ignored */ s++; @@ -189,11 +189,11 @@ u_scanf_parse_spec (const char16_t *fmt, /* Get the width */ if(ISDIGIT(*s)){ - info->fWidth = (int) (*s++ - DIGIT_ZERO); + info->fWidth = *s++ - DIGIT_ZERO; while(ISDIGIT(*s)) { info->fWidth *= 10; - info->fWidth += (int) (*s++ - DIGIT_ZERO); + info->fWidth += *s++ - DIGIT_ZERO; } } @@ -228,7 +228,7 @@ u_scanf_parse_spec (const char16_t *fmt, info->fSpec = *s++; /* return # of characters in this specifier */ - return (int32_t)(s - fmt); + return static_cast(s - fmt); } #define UP_PERCENT 0x0025 @@ -323,7 +323,7 @@ u_scanf_skip_leading_ws(UFILE *input, UBool isNotEOF; /* skip all leading ws in the input */ - while( ((isNotEOF = ufile_getch(input, &c))==(UBool)true) && (c == pad || u_isWhitespace(c)) ) + while (((isNotEOF = ufile_getch(input, &c)) == static_cast(true)) && (c == pad || u_isWhitespace(c))) { count++; } @@ -357,7 +357,7 @@ u_scanf_skip_leading_positive_sign(UFILE *input, if (U_SUCCESS(localStatus)) { /* skip all leading ws in the input */ - while( ((isNotEOF = ufile_getch(input, &c))==(UBool)true) && (count < symbolLen && c == plusSymbol[count]) ) + while (((isNotEOF = ufile_getch(input, &c)) == static_cast(true)) && (count < symbolLen && c == plusSymbol[count])) { count++; } @@ -409,11 +409,11 @@ u_scanf_count_handler(UFILE *input, /* will contain the # of items converted thus far */ if (!info->fSkipArg) { if (info->fIsShort) - *(int16_t*)(args[0].ptrValue) = (int16_t)(UINT16_MAX & info->fWidth); + *static_cast(args[0].ptrValue) = static_cast(UINT16_MAX & info->fWidth); else if (info->fIsLongLong) - *(int64_t*)(args[0].ptrValue) = info->fWidth; + *static_cast(args[0].ptrValue) = info->fWidth; else - *(int32_t*)(args[0].ptrValue) = (int32_t)(UINT32_MAX & info->fWidth); + *static_cast(args[0].ptrValue) = static_cast(UINT32_MAX & info->fWidth); } *argConverted = 0; @@ -447,7 +447,7 @@ u_scanf_double_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -468,11 +468,11 @@ u_scanf_double_handler(UFILE *input, if (!info->fSkipArg) { if (info->fIsLong) - *(double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else if (info->fIsLongDouble) - *(long double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else - *(float*)(args[0].ptrValue) = (float)num; + *static_cast(args[0].ptrValue) = static_cast(num); } /* mask off any necessary bits */ @@ -518,7 +518,7 @@ u_scanf_scientific_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -540,14 +540,14 @@ u_scanf_scientific_handler(UFILE *input, &status); /* Upper/lower case the e */ - if (info->fSpec == (char16_t)0x65 /* e */) { - expLen = u_strToLower(expBuf, (int32_t)sizeof(expBuf), + if (info->fSpec == static_cast(0x65) /* e */) { + expLen = u_strToLower(expBuf, static_cast(sizeof(expBuf)), srcExpBuf, srcLen, input->str.fBundle.fLocale, &status); } else { - expLen = u_strToUpper(expBuf, (int32_t)sizeof(expBuf), + expLen = u_strToUpper(expBuf, static_cast(sizeof(expBuf)), srcExpBuf, srcLen, input->str.fBundle.fLocale, &status); @@ -570,11 +570,11 @@ u_scanf_scientific_handler(UFILE *input, if (!info->fSkipArg) { if (info->fIsLong) - *(double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else if (info->fIsLongDouble) - *(long double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else - *(float*)(args[0].ptrValue) = (float)num; + *static_cast(args[0].ptrValue) = static_cast(num); } /* mask off any necessary bits */ @@ -624,7 +624,7 @@ u_scanf_scidbl_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -666,11 +666,11 @@ u_scanf_scidbl_handler(UFILE *input, if (!info->fSkipArg) { if (info->fIsLong) - *(double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else if (info->fIsLongDouble) - *(long double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; else - *(float*)(args[0].ptrValue) = (float)num; + *static_cast(args[0].ptrValue) = static_cast(num); } /* mask off any necessary bits */ @@ -694,7 +694,7 @@ u_scanf_integer_handler(UFILE *input, (void)fmtConsumed; int32_t len; - void *num = (void*) (args[0].ptrValue); + void* num = args[0].ptrValue; UNumberFormat *format, *localFormat; int32_t parsePos = 0; int32_t skipped; @@ -710,7 +710,7 @@ u_scanf_integer_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -741,11 +741,11 @@ u_scanf_integer_handler(UFILE *input, /* mask off any necessary bits */ if (!info->fSkipArg) { if (info->fIsShort) - *(int16_t*)num = (int16_t)(UINT16_MAX & result); + *static_cast(num) = static_cast(UINT16_MAX & result); else if (info->fIsLongLong) - *(int64_t*)num = result; + *static_cast(num) = result; else - *(int32_t*)num = (int32_t)(UINT32_MAX & result); + *static_cast(num) = static_cast(UINT32_MAX & result); } /* update the input's position to reflect consumed data */ @@ -796,7 +796,7 @@ u_scanf_percent_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -816,7 +816,7 @@ u_scanf_percent_handler(UFILE *input, num = unum_parseDouble(format, input->str.fPos, len, &parsePos, &status); if (!info->fSkipArg) { - *(double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; } /* mask off any necessary bits */ @@ -844,7 +844,7 @@ u_scanf_string_handler(UFILE *input, const char16_t *source; UConverter *conv; - char *arg = (char*)(args[0].ptrValue); + char* arg = static_cast(args[0].ptrValue); char *alias = arg; char *limit; UErrorCode status = U_ZERO_ERROR; @@ -868,7 +868,7 @@ u_scanf_string_handler(UFILE *input, return -1; while( (info->fWidth == -1 || count < info->fWidth) - && ((isNotEOF = ufile_getch(input, &c))==(UBool)true) + && ((isNotEOF = ufile_getch(input, &c)) == static_cast(true)) && (!info->fIsString || (c != info->fPadChar && !u_isWhitespace(c)))) { @@ -943,7 +943,7 @@ u_scanf_ustring_handler(UFILE *input, (void)fmt; (void)fmtConsumed; - char16_t *arg = (char16_t*)(args[0].ptrValue); + char16_t* arg = static_cast(args[0].ptrValue); char16_t *alias = arg; int32_t count; int32_t skipped = 0; @@ -959,7 +959,7 @@ u_scanf_ustring_handler(UFILE *input, count = 0; while( (info->fWidth == -1 || count < info->fWidth) - && ((isNotEOF = ufile_getch(input, &c))==(UBool)true) + && ((isNotEOF = ufile_getch(input, &c)) == static_cast(true)) && (!info->fIsString || (c != info->fPadChar && !u_isWhitespace(c)))) { @@ -1030,7 +1030,7 @@ u_scanf_spellout_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -1051,7 +1051,7 @@ u_scanf_spellout_handler(UFILE *input, num = unum_parseDouble(format, input->str.fPos, len, &parsePos, &status); if (!info->fSkipArg) { - *(double*)(args[0].ptrValue) = num; + *static_cast(args[0].ptrValue) = num; } /* mask off any necessary bits */ @@ -1079,7 +1079,7 @@ u_scanf_hex_handler(UFILE *input, int32_t len; int32_t skipped; - void *num = (void*) (args[0].ptrValue); + void* num = args[0].ptrValue; int64_t result; /* skip all ws in the input */ @@ -1089,7 +1089,7 @@ u_scanf_hex_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -1113,11 +1113,11 @@ u_scanf_hex_handler(UFILE *input, /* mask off any necessary bits */ if (!info->fSkipArg) { if (info->fIsShort) - *(int16_t*)num = (int16_t)(UINT16_MAX & result); + *static_cast(num) = static_cast(UINT16_MAX & result); else if (info->fIsLongLong) - *(int64_t*)num = result; + *static_cast(num) = result; else - *(int32_t*)num = (int32_t)(UINT32_MAX & result); + *static_cast(num) = static_cast(UINT32_MAX & result); } /* we converted 1 arg */ @@ -1138,7 +1138,7 @@ u_scanf_octal_handler(UFILE *input, int32_t len; int32_t skipped; - void *num = (void*) (args[0].ptrValue); + void* num = args[0].ptrValue; int64_t result; /* skip all ws in the input */ @@ -1148,7 +1148,7 @@ u_scanf_octal_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) @@ -1163,11 +1163,11 @@ u_scanf_octal_handler(UFILE *input, /* mask off any necessary bits */ if (!info->fSkipArg) { if (info->fIsShort) - *(int16_t*)num = (int16_t)(UINT16_MAX & result); + *static_cast(num) = static_cast(UINT16_MAX & result); else if (info->fIsLongLong) - *(int64_t*)num = result; + *static_cast(num) = result; else - *(int32_t*)num = (int32_t)(UINT32_MAX & result); + *static_cast(num) = static_cast(UINT32_MAX & result); } /* we converted 1 arg */ @@ -1189,7 +1189,7 @@ u_scanf_pointer_handler(UFILE *input, int32_t len; int32_t skipped; void *result; - void **p = (void**)(args[0].ptrValue); + void** p = static_cast(args[0].ptrValue); /* skip all ws in the input */ @@ -1199,7 +1199,7 @@ u_scanf_pointer_handler(UFILE *input, ufile_fill_uchar_buffer(input); /* determine the size of the input's buffer */ - len = (int32_t)(input->str.fLimit - input->str.fPos); + len = static_cast(input->str.fLimit - input->str.fPos); /* truncate to the width, if specified */ if(info->fWidth != -1) { @@ -1207,8 +1207,8 @@ u_scanf_pointer_handler(UFILE *input, } /* Make sure that we don't consume too much */ - if (len > (int32_t)(sizeof(void*)*2)) { - len = (int32_t)(sizeof(void*)*2); + if (len > static_cast(sizeof(void*) * 2)) { + len = static_cast(sizeof(void*) * 2); } /* parse the pointer - assign to temporary value */ @@ -1238,7 +1238,7 @@ u_scanf_scanset_handler(UFILE *input, UErrorCode status = U_ZERO_ERROR; int32_t chLeft = INT32_MAX; UChar32 c; - char16_t *alias = (char16_t*) (args[0].ptrValue); + char16_t* alias = static_cast(args[0].ptrValue); UBool isNotEOF = false; UBool readCharacter = false; @@ -1262,7 +1262,7 @@ u_scanf_scanset_handler(UFILE *input, /* grab characters one at a time and make sure they are in the scanset */ while(chLeft > 0) { - if ( ((isNotEOF = ufile_getch32(input, &c))==(UBool)true) && uset_contains(scanset, c) ) { + if (((isNotEOF = ufile_getch32(input, &c)) == static_cast(true)) && uset_contains(scanset, c)) { readCharacter = true; if (!info->fSkipArg) { int32_t idx = 0; diff --git a/icu4c/source/io/ustdio.cpp b/icu4c/source/io/ustdio.cpp index 4130f340442c..0cee48f17083 100644 --- a/icu4c/source/io/ustdio.cpp +++ b/icu4c/source/io/ustdio.cpp @@ -162,11 +162,11 @@ static const char16_t * u_file_translit(UFILE *f, const char16_t *src, int32_t * { if(f->fTranslit->buffer == nullptr) { - f->fTranslit->buffer = (char16_t*)uprv_malloc(newlen * sizeof(char16_t)); + f->fTranslit->buffer = static_cast(uprv_malloc(newlen * sizeof(char16_t))); } else { - f->fTranslit->buffer = (char16_t*)uprv_realloc(f->fTranslit->buffer, newlen * sizeof(char16_t)); + f->fTranslit->buffer = static_cast(uprv_realloc(f->fTranslit->buffer, newlen * sizeof(char16_t))); } /* Check for malloc/realloc failure. */ if (f->fTranslit->buffer == nullptr) { @@ -422,7 +422,7 @@ ufile_fill_uchar_buffer(UFILE *f) } str = &f->str; - dataSize = (int32_t)(str->fLimit - str->fPos); + dataSize = static_cast(str->fLimit - str->fPos); if (f->fFileno == 0 && dataSize > 0) { /* Don't read from stdin too many times. There is still some data. */ return; @@ -445,14 +445,14 @@ ufile_fill_uchar_buffer(UFILE *f) if (f->fFileno == 0) { /* Special case. Read from stdin one line at a time. */ char *retStr = fgets(charBuffer, ufmt_min(maxCPBytes, UFILE_CHARBUFFER_SIZE), f->fFile); - bytesRead = (int32_t)(retStr ? uprv_strlen(charBuffer) : 0); + bytesRead = static_cast(retStr ? uprv_strlen(charBuffer) : 0); } else { /* A normal file */ - bytesRead = (int32_t)fread(charBuffer, + bytesRead = static_cast(fread(charBuffer, sizeof(char), ufmt_min(maxCPBytes, UFILE_CHARBUFFER_SIZE), - f->fFile); + f->fFile)); } /* Set up conversion parameters */ @@ -470,7 +470,7 @@ ufile_fill_uchar_buffer(UFILE *f) &mySource, mySourceEnd, nullptr, - (UBool)(feof(f->fFile) != 0), + static_cast(feof(f->fFile) != 0), &status); } else { /*weiv: do the invariant conversion */ diff --git a/icu4c/source/io/ustream.cpp b/icu4c/source/io/ustream.cpp index 2bc212da0948..355909ed5b9f 100644 --- a/icu4c/source/io/ustream.cpp +++ b/icu4c/source/io/ustream.cpp @@ -105,7 +105,7 @@ operator>>(STD_ISTREAM& stream, UnicodeString& str) } continueReading = false; } - sLimit = &ch + (int)continueReading; + sLimit = &ch + static_cast(continueReading); us = uBuffer; s = &ch; errorCode = U_ZERO_ERROR; diff --git a/icu4c/source/layoutex/ParagraphLayout.cpp b/icu4c/source/layoutex/ParagraphLayout.cpp index 1788b68e1d0a..6ac0c7d49eba 100644 --- a/icu4c/source/layoutex/ParagraphLayout.cpp +++ b/icu4c/source/layoutex/ParagraphLayout.cpp @@ -389,7 +389,7 @@ ParagraphLayout::ParagraphLayout(const LEUnicode chars[], le_int32 count, fStyleRunInfo[run].font = nullptr; fStyleRunInfo[run].runBase = 0; fStyleRunInfo[run].runLimit = 0; - fStyleRunInfo[run].script = (UScriptCode)0; + fStyleRunInfo[run].script = static_cast(0); fStyleRunInfo[run].locale = nullptr; fStyleRunInfo[run].level = 0; fStyleRunInfo[run].glyphBase = 0; @@ -405,9 +405,9 @@ ParagraphLayout::ParagraphLayout(const LEUnicode chars[], le_int32 count, fStyleRunInfo[run].font = fFontRuns->getFont(styleIndices[0]); fStyleRunInfo[run].runBase = runStart; fStyleRunInfo[run].runLimit = fStyleRunLimits[run]; - fStyleRunInfo[run].script = (UScriptCode) fScriptRuns->getValue(styleIndices[2]); + fStyleRunInfo[run].script = static_cast(fScriptRuns->getValue(styleIndices[2])); fStyleRunInfo[run].locale = fLocaleRuns->getLocale(styleIndices[3]); - fStyleRunInfo[run].level = (UBiDiLevel) fLevelRuns->getValue(styleIndices[1]); + fStyleRunInfo[run].level = static_cast(fLevelRuns->getValue(styleIndices[1])); fStyleRunInfo[run].glyphBase = fGlyphCount; fStyleRunInfo[run].engine = LayoutEngine::layoutEngineFactory(fStyleRunInfo[run].font, @@ -527,24 +527,24 @@ ParagraphLayout::ParagraphLayout(const LEUnicode chars[], le_int32 count, ParagraphLayout::~ParagraphLayout() { - delete (FontRuns *) fFontRuns; + delete const_cast(fFontRuns); if (! fClientLevels) { - delete (ValueRuns *) fLevelRuns; + delete const_cast(fLevelRuns); fLevelRuns = nullptr; fClientLevels = true; } if (! fClientScripts) { - delete (ValueRuns *) fScriptRuns; + delete const_cast(fScriptRuns); fScriptRuns = nullptr; fClientScripts = true; } if (! fClientLocales) { - delete (LocaleRuns *) fLocaleRuns; + delete const_cast(fLocaleRuns); fLocaleRuns = nullptr; fClientLocales = true; @@ -635,7 +635,7 @@ le_bool ParagraphLayout::isComplex(const LEUnicode chars[], le_int32 count) le_int32 ParagraphLayout::getAscent() const { if (fAscent <= 0 && fCharCount > 0) { - ((ParagraphLayout *) this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fAscent; @@ -644,7 +644,7 @@ le_int32 ParagraphLayout::getAscent() const le_int32 ParagraphLayout::getDescent() const { if (fAscent <= 0 && fCharCount > 0) { - ((ParagraphLayout *) this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fDescent; @@ -653,7 +653,7 @@ le_int32 ParagraphLayout::getDescent() const le_int32 ParagraphLayout::getLeading() const { if (fAscent <= 0 && fCharCount > 0) { - ((ParagraphLayout *) this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fLeading; @@ -717,7 +717,7 @@ void ParagraphLayout::computeLevels(UBiDiLevel paragraphLevel) fEmbeddingLevels = LE_NEW_ARRAY(UBiDiLevel, fCharCount); for (ch = 0, run = 0; run < fLevelRuns->getCount(); run += 1) { - UBiDiLevel runLevel = (UBiDiLevel) fLevelRuns->getValue(run) | UBIDI_LEVEL_OVERRIDE; + UBiDiLevel runLevel = static_cast(fLevelRuns->getValue(run)) | UBIDI_LEVEL_OVERRIDE; le_int32 runLimit = fLevelRuns->getLimit(run); while (ch < runLimit) { @@ -1173,7 +1173,7 @@ ParagraphLayout::Line::~Line() le_int32 ParagraphLayout::Line::getAscent() const { if (fAscent <= 0) { - ((ParagraphLayout::Line *)this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fAscent; @@ -1182,7 +1182,7 @@ le_int32 ParagraphLayout::Line::getAscent() const le_int32 ParagraphLayout::Line::getDescent() const { if (fAscent <= 0) { - ((ParagraphLayout::Line *)this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fDescent; @@ -1191,7 +1191,7 @@ le_int32 ParagraphLayout::Line::getDescent() const le_int32 ParagraphLayout::Line::getLeading() const { if (fAscent <= 0) { - ((ParagraphLayout::Line *)this)->computeMetrics(); + const_cast(this)->computeMetrics(); } return fLeading; @@ -1208,7 +1208,7 @@ le_int32 ParagraphLayout::Line::getWidth() const le_int32 glyphCount = lastRun->getGlyphCount(); const float *positions = lastRun->getPositions(); - return (le_int32) positions[glyphCount * 2]; + return static_cast(positions[glyphCount * 2]); } const ParagraphLayout::VisualRun *ParagraphLayout::Line::getVisualRun(le_int32 runIndex) const @@ -1229,7 +1229,7 @@ void ParagraphLayout::Line::append(const LEFontInstance *font, UBiDiDirection di fRuns = LE_NEW_ARRAY(ParagraphLayout::VisualRun *, fRunCapacity); } else { fRunCapacity += (fRunCapacity < RUN_CAPACITY_GROW_LIMIT? fRunCapacity : RUN_CAPACITY_GROW_LIMIT); - fRuns = (ParagraphLayout::VisualRun **) LE_GROW_ARRAY(fRuns, fRunCapacity); + fRuns = static_cast(LE_GROW_ARRAY(fRuns, fRunCapacity)); } } diff --git a/icu4c/source/layoutex/RunArrays.cpp b/icu4c/source/layoutex/RunArrays.cpp index 30b40e530087..09692dc57ac3 100644 --- a/icu4c/source/layoutex/RunArrays.cpp +++ b/icu4c/source/layoutex/RunArrays.cpp @@ -56,7 +56,7 @@ void RunArray::init(le_int32 capacity) void RunArray::grow(le_int32 newCapacity) { - fLimits = (le_int32 *) LE_GROW_ARRAY(fLimits, newCapacity); + fLimits = static_cast(LE_GROW_ARRAY(fLimits, newCapacity)); } le_int32 RunArray::add(le_int32 limit) @@ -66,7 +66,7 @@ le_int32 RunArray::add(le_int32 limit) } le_int32 index = ensureCapacity(); - le_int32 *limits = (le_int32 *) fLimits; + le_int32* limits = const_cast(fLimits); limits[index] = limit; @@ -100,7 +100,7 @@ void FontRuns::init(le_int32 capacity) void FontRuns::grow(le_int32 capacity) { RunArray::grow(capacity); - fFonts = (const LEFontInstance **) LE_GROW_ARRAY(fFonts, capacity); + fFonts = static_cast(LE_GROW_ARRAY(fFonts, capacity)); } le_int32 FontRuns::add(const LEFontInstance *font, le_int32 limit) @@ -108,9 +108,9 @@ le_int32 FontRuns::add(const LEFontInstance *font, le_int32 limit) le_int32 index = RunArray::add(limit); if (index >= 0) { - LEFontInstance **fonts = (LEFontInstance **) fFonts; + LEFontInstance** fonts = const_cast(fFonts); - fonts[index] = (LEFontInstance *) font; + fonts[index] = const_cast(font); } return index; @@ -152,7 +152,7 @@ void LocaleRuns::init(le_int32 capacity) void LocaleRuns::grow(le_int32 capacity) { RunArray::grow(capacity); - fLocales = (const Locale **) LE_GROW_ARRAY(fLocales, capacity); + fLocales = static_cast(LE_GROW_ARRAY(fLocales, capacity)); } le_int32 LocaleRuns::add(const Locale *locale, le_int32 limit) @@ -160,9 +160,9 @@ le_int32 LocaleRuns::add(const Locale *locale, le_int32 limit) le_int32 index = RunArray::add(limit); if (index >= 0) { - Locale **locales = (Locale **) fLocales; + Locale** locales = const_cast(fLocales); - locales[index] = (Locale *) locale; + locales[index] = const_cast(locale); } return index; @@ -204,7 +204,7 @@ void ValueRuns::init(le_int32 capacity) void ValueRuns::grow(le_int32 capacity) { RunArray::grow(capacity); - fValues = (const le_int32 *) LE_GROW_ARRAY(fValues, capacity); + fValues = static_cast(LE_GROW_ARRAY(fValues, capacity)); } le_int32 ValueRuns::add(le_int32 value, le_int32 limit) @@ -212,7 +212,7 @@ le_int32 ValueRuns::add(le_int32 value, le_int32 limit) le_int32 index = RunArray::add(limit); if (index >= 0) { - le_int32 *values = (le_int32 *) fValues; + le_int32* values = const_cast(fValues); values[index] = value; } diff --git a/icu4c/source/layoutex/plruns.cpp b/icu4c/source/layoutex/plruns.cpp index 20346517dad1..248f7bf2cedc 100644 --- a/icu4c/source/layoutex/plruns.cpp +++ b/icu4c/source/layoutex/plruns.cpp @@ -378,7 +378,7 @@ void ULocRuns::init(le_int32 capacity) void ULocRuns::grow(le_int32 capacity) { LocaleRuns::grow(capacity); - fLocaleNames = (const char **) LE_GROW_ARRAY(fLocaleNames, capacity); + fLocaleNames = static_cast(LE_GROW_ARRAY(fLocaleNames, capacity)); } le_int32 ULocRuns::add(const char *locale, le_int32 limit) @@ -387,9 +387,9 @@ le_int32 ULocRuns::add(const char *locale, le_int32 limit) le_int32 index = LocaleRuns::add(loc, limit); if (index >= 0) { - char **localeNames = (char **) fLocaleNames; + char** localeNames = const_cast(fLocaleNames); - localeNames[index] = (char *) locale; + localeNames[index] = const_cast(locale); } return index; diff --git a/icu4c/source/samples/coll/coll.cpp b/icu4c/source/samples/coll/coll.cpp index ed3ec0adc319..f7bace96251e 100644 --- a/icu4c/source/samples/coll/coll.cpp +++ b/icu4c/source/samples/coll/coll.cpp @@ -97,7 +97,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) if (strcmp(pOpt->name, pArgName) == 0) { switch (pOpt->type) { case OptSpec::FLAG: - *(UBool *)(pOpt->pVar) = true; + *static_cast(pOpt->pVar) = true; break; case OptSpec::STRING: argNum ++; @@ -106,7 +106,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) pOpt->name); return false; } - *(const char **)(pOpt->pVar) = argv[argNum]; + *static_cast(pOpt->pVar) = argv[argNum]; break; case OptSpec::NUM: argNum ++; @@ -123,7 +123,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) pOpt->name); return false; } - *(int *)(pOpt->pVar) = i; + *static_cast(pOpt->pVar) = i; } break; } diff --git a/icu4c/source/samples/strsrch/strsrch.cpp b/icu4c/source/samples/strsrch/strsrch.cpp index f1a52578695d..5994a18a025b 100644 --- a/icu4c/source/samples/strsrch/strsrch.cpp +++ b/icu4c/source/samples/strsrch/strsrch.cpp @@ -107,7 +107,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) if (strcmp(pOpt->name, pArgName) == 0) { switch (pOpt->type) { case OptSpec::FLAG: - *(UBool *)(pOpt->pVar) = true; + *static_cast(pOpt->pVar) = true; break; case OptSpec::STRING: argNum ++; @@ -116,7 +116,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) pOpt->name); return false; } - *(const char **)(pOpt->pVar) = argv[argNum]; + *static_cast(pOpt->pVar) = argv[argNum]; break; case OptSpec::NUM: argNum ++; @@ -133,7 +133,7 @@ UBool processOptions(int argc, const char **argv, OptSpec opts[]) pOpt->name); return false; } - *(int *)(pOpt->pVar) = i; + *static_cast(pOpt->pVar) = i; } break; } diff --git a/icu4c/source/samples/translit/answers/unaccent.cpp b/icu4c/source/samples/translit/answers/unaccent.cpp index 3592f0db0819..a8045b5f3f19 100644 --- a/icu4c/source/samples/translit/answers/unaccent.cpp +++ b/icu4c/source/samples/translit/answers/unaccent.cpp @@ -35,13 +35,13 @@ UnaccentTransliterator::~UnaccentTransliterator() { char16_t UnaccentTransliterator::unaccent(char16_t c) const { UnicodeString str(c); UErrorCode status = U_ZERO_ERROR; - UnaccentTransliterator* t = (UnaccentTransliterator*)this; + UnaccentTransliterator* t = const_cast(this); t->normalizer.setText(str, status); if (U_FAILURE(status)) { return c; } - return (char16_t) t->normalizer.next(); + return static_cast(t->normalizer.next()); } /** diff --git a/icu4c/source/samples/translit/unaccent.cpp b/icu4c/source/samples/translit/unaccent.cpp index 57eca261891a..6b1624abbe57 100644 --- a/icu4c/source/samples/translit/unaccent.cpp +++ b/icu4c/source/samples/translit/unaccent.cpp @@ -32,13 +32,13 @@ UnaccentTransliterator::~UnaccentTransliterator() { char16_t UnaccentTransliterator::unaccent(char16_t c) const { UnicodeString str(c); UErrorCode status = U_ZERO_ERROR; - UnaccentTransliterator* t = (UnaccentTransliterator*)this; + UnaccentTransliterator* t = const_cast(this); t->normalizer.setText(str, status); if (U_FAILURE(status)) { return c; } - return (char16_t) t->normalizer.next(); + return static_cast(t->normalizer.next()); } /** diff --git a/icu4c/source/samples/ugrep/ugrep.cpp b/icu4c/source/samples/ugrep/ugrep.cpp index 3b1bca4baf73..479db54e2932 100644 --- a/icu4c/source/samples/ugrep/ugrep.cpp +++ b/icu4c/source/samples/ugrep/ugrep.cpp @@ -289,7 +289,7 @@ void readFile(const char *name) { // // Read in the file // - charBuf = (char *)realloc(charBuf, rawFileLen+1); // Need error checking... + charBuf = static_cast(realloc(charBuf, rawFileLen + 1)); // Need error checking... int t = static_cast(fread(charBuf, 1, rawFileLen, file)); if (t != rawFileLen) { fprintf(stderr, "Error reading file \"%s\"\n", fileName); @@ -343,7 +343,7 @@ void readFile(const char *name) { }; status = U_ZERO_ERROR; - ucharBuf = (char16_t *)realloc(ucharBuf, (destCap+1) * sizeof(char16_t)); + ucharBuf = static_cast(realloc(ucharBuf, (destCap + 1) * sizeof(char16_t))); ucnv_toUChars(conv, ucharBuf, // dest, destCap+1, diff --git a/icu4c/source/test/fuzzer/fuzzer_driver.cpp b/icu4c/source/test/fuzzer/fuzzer_driver.cpp index 9361d606a00f..893bcdbdd45e 100644 --- a/icu4c/source/test/fuzzer/fuzzer_driver.cpp +++ b/icu4c/source/test/fuzzer/fuzzer_driver.cpp @@ -52,7 +52,7 @@ int main(int argc, char* argv[]) } std::ostringstream ostrm; ostrm << file.rdbuf(); - LLVMFuzzerTestOneInput((const uint8_t *) ostrm.str().c_str(), ostrm.str().size()); + LLVMFuzzerTestOneInput(reinterpret_cast(ostrm.str().c_str()), ostrm.str().size()); return 0; } diff --git a/icu4c/source/test/intltest/alphaindextst.cpp b/icu4c/source/test/intltest/alphaindextst.cpp index 2906d7e63d5e..182ffef7cdbc 100644 --- a/icu4c/source/test/intltest/alphaindextst.cpp +++ b/icu4c/source/test/intltest/alphaindextst.cpp @@ -36,7 +36,7 @@ UnicodeString joinLabelsAndAppend(AlphabeticIndex::ImmutableIndex &index, Unicod const AlphabeticIndex::Bucket *bucket; for (int32_t i = 0; (bucket = index.getBucket(i)) != nullptr; ++i) { if (dest.length() > oldLength) { - dest.append((char16_t)0x3A); // ':' + dest.append(static_cast(0x3A)); // ':' } dest.append(bucket->getLabel()); } @@ -127,7 +127,7 @@ void AlphabeticIndexTest::APITest() { index.adoptInstead(new AlphabeticIndex(Locale::getEnglish(), status)); TEST_CHECK_STATUS; UnicodeSet additions; - additions.add((UChar32)0x410).add((UChar32)0x415); // A couple of Cyrillic letters + additions.add(static_cast(0x410)).add(static_cast(0x415)); // A couple of Cyrillic letters index->addLabels(additions, status); TEST_CHECK_STATUS; lc = index->getBucketCount(status); @@ -161,7 +161,7 @@ void AlphabeticIndexTest::APITest() { const RuleBasedCollator &indexCol = index->getCollator(); TEST_ASSERT(*germanCol == indexCol); - UnicodeString ELLIPSIS; ELLIPSIS.append((UChar32)0x2026); + UnicodeString ELLIPSIS; ELLIPSIS.append(static_cast(0x2026)); UnicodeString s = index->getUnderflowLabel(); TEST_ASSERT(ELLIPSIS == s); s = index->getOverflowLabel(); @@ -284,7 +284,7 @@ void AlphabeticIndexTest::APITest() { } else if (i <= 26) { // Labels A - Z for English locale TEST_ASSERT(type == U_ALPHAINDEX_NORMAL); - UnicodeString expectedLabel((char16_t)(0x40 + i)); + UnicodeString expectedLabel(static_cast(0x40 + i)); TEST_ASSERT(expectedLabel == label); } else if (i == 27) { TEST_ASSERT(type == U_ALPHAINDEX_OVERFLOW); @@ -571,16 +571,16 @@ void AlphabeticIndexTest::TestHaniFirst() { assertEquals("getBucketCount()", 1, index.getBucketCount(status)); // ... (underflow only) index.addLabels(Locale::getEnglish(), status); assertEquals("getBucketCount()", 28, index.getBucketCount(status)); // ... A-Z ... - int32_t bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x897f), status); + int32_t bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x897f)), status); assertEquals("getBucketIndex(U+897F)", 0, bucketIndex); // underflow bucket bucketIndex = index.getBucketIndex("i", status); assertEquals("getBucketIndex(i)", 9, bucketIndex); - bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x03B1), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x03B1)), status); assertEquals("getBucketIndex(Greek alpha)", 27, bucketIndex); // U+50005 is an unassigned code point which sorts at the end, independent of the Hani group. - bucketIndex = index.getBucketIndex(UnicodeString((UChar32)0x50005), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x50005)), status); assertEquals("getBucketIndex(U+50005)", 27, bucketIndex); - bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0xFFFF), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0xFFFF)), status); assertEquals("getBucketIndex(U+FFFF)", 27, bucketIndex); } @@ -600,16 +600,16 @@ void AlphabeticIndexTest::TestPinyinFirst() { assertEquals("getBucketCount()", 28, index.getBucketCount(status)); // ... A-Z ... index.addLabels(Locale::getChinese(), status); assertEquals("getBucketCount()", 28, index.getBucketCount(status)); // ... A-Z ... - int32_t bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x897f), status); - assertEquals("getBucketIndex(U+897F)", (int32_t)((char16_t)0x0058/*X*/ - (char16_t)0x0041/*A*/ + 1), bucketIndex); + int32_t bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x897f)), status); + assertEquals("getBucketIndex(U+897F)", static_cast(static_cast(0x0058) /*X*/ - static_cast(0x0041) /*A*/ + 1), bucketIndex); bucketIndex = index.getBucketIndex("i", status); assertEquals("getBucketIndex(i)", 9, bucketIndex); - bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x03B1), status); - assertEquals("getBucketIndex(Greek alpha)", (int32_t)27, bucketIndex); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x03B1)), status); + assertEquals("getBucketIndex(Greek alpha)", static_cast(27), bucketIndex); // U+50005 is an unassigned code point which sorts at the end, independent of the Hani group. - bucketIndex = index.getBucketIndex(UnicodeString((UChar32)0x50005), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x50005)), status); assertEquals("getBucketIndex(U+50005)", 27, bucketIndex); - bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0xFFFF), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0xFFFF)), status); assertEquals("getBucketIndex(U+FFFF)", 27, bucketIndex); } @@ -663,13 +663,13 @@ void AlphabeticIndexTest::TestNoLabels() { TEST_CHECK_STATUS; AlphabeticIndex index(coll.orphan(), status); TEST_CHECK_STATUS; - index.addRecord(UnicodeString((char16_t)0x897f), nullptr, status); + index.addRecord(UnicodeString(static_cast(0x897f)), nullptr, status); index.addRecord("i", nullptr, status); - index.addRecord(UnicodeString((char16_t)0x03B1), nullptr, status); + index.addRecord(UnicodeString(static_cast(0x03B1)), nullptr, status); assertEquals("getBucketCount()", 1, index.getBucketCount(status)); // ... TEST_ASSERT(index.nextBucket(status)); - assertEquals("underflow label type", (int32_t)U_ALPHAINDEX_UNDERFLOW, index.getBucketLabelType()); - assertEquals("all records in the underflow bucket", (int32_t)3, index.getBucketRecordCount()); + assertEquals("underflow label type", static_cast(U_ALPHAINDEX_UNDERFLOW), index.getBucketLabelType()); + assertEquals("all records in the underflow bucket", static_cast(3), index.getBucketRecordCount()); } void AlphabeticIndexTest::TestChineseZhuyin() { @@ -680,11 +680,11 @@ void AlphabeticIndexTest::TestChineseZhuyin() { LocalPointer immIndex(index.buildImmutableIndex(status)); TEST_CHECK_STATUS; assertEquals("getBucketCount()", 38, immIndex->getBucketCount()); - assertEquals("label 1", UnicodeString((char16_t)0x3105), immIndex->getBucket(1)->getLabel()); - assertEquals("label 2", UnicodeString((char16_t)0x3106), immIndex->getBucket(2)->getLabel()); - assertEquals("label 3", UnicodeString((char16_t)0x3107), immIndex->getBucket(3)->getLabel()); - assertEquals("label 4", UnicodeString((char16_t)0x3108), immIndex->getBucket(4)->getLabel()); - assertEquals("label 5", UnicodeString((char16_t)0x3109), immIndex->getBucket(5)->getLabel()); + assertEquals("label 1", UnicodeString(static_cast(0x3105)), immIndex->getBucket(1)->getLabel()); + assertEquals("label 2", UnicodeString(static_cast(0x3106)), immIndex->getBucket(2)->getLabel()); + assertEquals("label 3", UnicodeString(static_cast(0x3107)), immIndex->getBucket(3)->getLabel()); + assertEquals("label 4", UnicodeString(static_cast(0x3108)), immIndex->getBucket(4)->getLabel()); + assertEquals("label 5", UnicodeString(static_cast(0x3109)), immIndex->getBucket(5)->getLabel()); } void AlphabeticIndexTest::TestJapaneseKanji() { @@ -698,7 +698,7 @@ void AlphabeticIndexTest::TestJapaneseKanji() { int32_t overflowIndex = immIndex->getBucketCount() - 1; for(int32_t i = 0; i < UPRV_LENGTHOF(kanji); ++i) { char msg[40]; - snprintf(msg, sizeof(msg), "kanji[%d]=U+%04lX in overflow bucket", (int)i, (long)kanji[i]); + snprintf(msg, sizeof(msg), "kanji[%d]=U+%04lX in overflow bucket", static_cast(i), static_cast(kanji[i])); assertEquals(msg, overflowIndex, immIndex->getBucketIndex(UnicodeString(kanji[i]), status)); TEST_CHECK_STATUS; } @@ -726,10 +726,10 @@ void AlphabeticIndexTest::TestChineseUnihan() { logln("Chinese/unihan has %d buckets/labels", bucketCount); } // bucketIndex = radical number, adjusted for simplified radicals in lower buckets. - int32_t bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x4e5d), status); + int32_t bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x4e5d)), status); assertEquals("getBucketIndex(U+4E5D)", 5, bucketIndex); // radical 100, and there is a 90' since Unicode 8 - bucketIndex = index.getBucketIndex(UnicodeString((char16_t)0x7527), status); + bucketIndex = index.getBucketIndex(UnicodeString(static_cast(0x7527)), status); assertEquals("getBucketIndex(U+7527)", 101, bucketIndex); } diff --git a/icu4c/source/test/intltest/apicoll.cpp b/icu4c/source/test/intltest/apicoll.cpp index ac5ed932c603..4464266b1ad5 100644 --- a/icu4c/source/test/intltest/apicoll.cpp +++ b/icu4c/source/test/intltest/apicoll.cpp @@ -536,7 +536,7 @@ CollationAPITest::TestCollationKey(/* char* par */) CollationKey sortkIgnorable; // Most control codes and CGJ are completely ignorable. // A string with only completely ignorables must compare equal to an empty string. - col->getCollationKey(UnicodeString((char16_t)1).append((char16_t)0x34f), sortkIgnorable, key1Status); + col->getCollationKey(UnicodeString(static_cast(1)).append(static_cast(0x34f)), sortkIgnorable, key1Status); sortkIgnorable.getByteArray(length); doAssert(!sortkIgnorable.isBogus() && length == 3, "Completely ignorable string should return a collation key with empty levels"); @@ -799,14 +799,14 @@ CollationAPITest::TestElemIter(/* char* par */) } int32_t position=coliter->previous(success); if(position != CollationElementIterator::NULLORDER){ - errln((UnicodeString)"Expected NULLORDER got" + position); + errln(UnicodeString("Expected NULLORDER got") + position); } coliter->reset(); coliter->setText(*chariter, success); if(!U_FAILURE(success)){ errln("Expected error"); } - iterator1->setText((UnicodeString)"hello there", success); + iterator1->setText(UnicodeString("hello there"), success); if(!U_FAILURE(success)){ errln("Expected error"); } @@ -926,8 +926,8 @@ CollationAPITest::TestDuplicate(/* char* par */) doAssert((*col1 == *col3), "Copied object is not equal to the original"); UCollationResult res; - UnicodeString first((char16_t)0x0061); - UnicodeString second((char16_t)0x0062); + UnicodeString first(static_cast(0x0061)); + UnicodeString second(static_cast(0x0062)); UnicodeString copiedEnglishRules((dynamic_cast(col1))->getRules()); delete col1; @@ -1280,7 +1280,7 @@ void CollationAPITest::TestSortKeyOverflow() { } // Insert an 'a' to match ++prefixLength. - s.insert(prefixLength, (char16_t)0x61); + s.insert(prefixLength, static_cast(0x61)); } } @@ -1564,18 +1564,18 @@ void CollationAPITest::TestVariableTopSetting() { errln("setVariableTop(dollar sign) != following getVariableTop()"); } - UnicodeString dollar((char16_t)0x24); - UnicodeString euro((char16_t)0x20AC); + UnicodeString dollar(static_cast(0x24)); + UnicodeString euro(static_cast(0x20AC)); uint32_t newVarTop2 = coll->setVariableTop(euro, status); assertEquals("setVariableTop(Euro sign) == following getVariableTop()", - (int64_t)newVarTop2, (int64_t)coll->getVariableTop(status)); + static_cast(newVarTop2), static_cast(coll->getVariableTop(status))); assertEquals("setVariableTop(Euro sign) == setVariableTop(dollar sign) (should pin to top of currency group)", - (int64_t)newVarTop2, (int64_t)newVarTop); + static_cast(newVarTop2), static_cast(newVarTop)); coll->setAttribute(UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, status); - assertEquals("empty==dollar", (int32_t)UCOL_EQUAL, (int32_t)coll->compare(UnicodeString(), dollar)); - assertEquals("empty==euro", (int32_t)UCOL_EQUAL, (int32_t)coll->compare(UnicodeString(), euro)); - assertEquals("dollarcompare(dollar, UnicodeString((char16_t)0x30))); + assertEquals("empty==dollar", static_cast(UCOL_EQUAL), static_cast(coll->compare(UnicodeString(), dollar))); + assertEquals("empty==euro", static_cast(UCOL_EQUAL), static_cast(coll->compare(UnicodeString(), euro))); + assertEquals("dollar(UCOL_LESS), static_cast(coll->compare(dollar, UnicodeString(static_cast(0x30))))); coll->setVariableTop(oldVarTop, status); @@ -1610,9 +1610,9 @@ void CollationAPITest::TestMaxVariable() { } coll->setAttribute(UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, errorCode); - assertEquals("empty==dollar", (int32_t)UCOL_EQUAL, (int32_t)coll->compare(UnicodeString(), UnicodeString((char16_t)0x24))); - assertEquals("empty==euro", (int32_t)UCOL_EQUAL, (int32_t)coll->compare(UnicodeString(), UnicodeString((char16_t)0x20AC))); - assertEquals("dollarcompare(UnicodeString((char16_t)0x24), UnicodeString((char16_t)0x30))); + assertEquals("empty==dollar", static_cast(UCOL_EQUAL), static_cast(coll->compare(UnicodeString(), UnicodeString(static_cast(0x24))))); + assertEquals("empty==euro", static_cast(UCOL_EQUAL), static_cast( coll->compare(UnicodeString(), UnicodeString(static_cast(0x20AC))))); + assertEquals("dollar(UCOL_LESS), static_cast(coll->compare(UnicodeString(static_cast(0x24)), UnicodeString(static_cast(0x30))))); } void CollationAPITest::TestGetLocale() { @@ -1886,10 +1886,10 @@ void CollationAPITest::TestBounds() { lowerSize = coll->getBound(tests[i].key, -1, UCOL_BOUND_LOWER, 1, lower, 512, status); upperSize = coll->getBound(tests[j].key, -1, UCOL_BOUND_UPPER, 1, upper, 512, status); for(k = i; k <= j; k++) { - if(strcmp((const char *)lower, (const char *)tests[k].key) > 0) { + if (strcmp(reinterpret_cast(lower), reinterpret_cast(tests[k].key)) > 0) { errln("Problem with lower! j = %i (%s vs %s)", k, tests[k].original, tests[i].original); } - if(strcmp((const char *)upper, (const char *)tests[k].key) <= 0) { + if (strcmp(reinterpret_cast(upper), reinterpret_cast(tests[k].key)) <= 0) { errln("Problem with upper! j = %i (%s vs %s)", k, tests[k].original, tests[j].original); } } @@ -1905,10 +1905,10 @@ void CollationAPITest::TestBounds() { for(j = i+1; jgetSortKey(buffer, buffSize, sortkey, 512); - if(strcmp((const char *)lower, (const char *)sortkey) > 0) { + if (strcmp(reinterpret_cast(lower), reinterpret_cast(sortkey)) > 0) { errln("Problem with lower! i = %i, j = %i (%s vs %s)", i, j, test[i], test[j]); } - if(strcmp((const char *)upper, (const char *)sortkey) <= 0) { + if (strcmp(reinterpret_cast(upper), reinterpret_cast(sortkey)) <= 0) { errln("Problem with upper! i = %i, j = %i (%s vs %s)", i, j, test[i], test[j]); } } @@ -1957,7 +1957,7 @@ void CollationAPITest::TestGetTailoredSet() void CollationAPITest::TestUClassID() { - char id = *((char *)RuleBasedCollator::getStaticClassID()); + char id = *static_cast(RuleBasedCollator::getStaticClassID()); if (id != 0) { errln("Static class id for RuleBasedCollator should be 0"); } @@ -1969,26 +1969,26 @@ void CollationAPITest::TestUClassID() errcheckln(status, "Collator creation failed with %s", u_errorName(status)); return; } - id = *((char *)coll->getDynamicClassID()); + id = *static_cast(coll->getDynamicClassID()); if (id != 0) { errln("Dynamic class id for RuleBasedCollator should be 0"); } - id = *((char *)CollationKey::getStaticClassID()); + id = *static_cast(CollationKey::getStaticClassID()); if (id != 0) { errln("Static class id for CollationKey should be 0"); } CollationKey *key = new CollationKey(); - id = *((char *)key->getDynamicClassID()); + id = *static_cast(key->getDynamicClassID()); if (id != 0) { errln("Dynamic class id for CollationKey should be 0"); } - id = *((char *)CollationElementIterator::getStaticClassID()); + id = *static_cast(CollationElementIterator::getStaticClassID()); if (id != 0) { errln("Static class id for CollationElementIterator should be 0"); } UnicodeString str("testing"); CollationElementIterator *iter = coll->createCollationElementIterator(str); - id = *((char *)iter->getDynamicClassID()); + id = *static_cast(iter->getDynamicClassID()); if (id != 0) { errln("Dynamic class id for CollationElementIterator should be 0"); } @@ -2075,7 +2075,7 @@ UCollationResult TestCollator::compare(const UnicodeString& source, UErrorCode& status) const { if(U_SUCCESS(status)) { - return UCollationResult(source.compare(target)); + return static_cast(source.compare(target)); } else { return UCOL_EQUAL; } @@ -2087,7 +2087,7 @@ UCollationResult TestCollator::compare(const UnicodeString& source, UErrorCode& status) const { if(U_SUCCESS(status)) { - return UCollationResult(source.compare(0, length, target)); + return static_cast(source.compare(0, length, target)); } else { return UCOL_EQUAL; } @@ -2112,7 +2112,7 @@ CollationKey& TestCollator::getCollationKey(const UnicodeString& source, int length = 100; length = source.extract(temp, length, nullptr, status); temp[length] = 0; - CollationKey tempkey((uint8_t*)temp, length); + CollationKey tempkey(reinterpret_cast(temp), length); key = tempkey; return key; } @@ -2131,7 +2131,7 @@ int32_t TestCollator::getSortKey(const UnicodeString& source, uint8_t* result, int32_t resultLength) const { UErrorCode status = U_ZERO_ERROR; - int32_t length = source.extract((char *)result, resultLength, nullptr, + int32_t length = source.extract(reinterpret_cast(result), resultLength, nullptr, status); result[length] = 0; return length; @@ -2230,7 +2230,7 @@ uint32_t TestCollator::getVariableTop(UErrorCode &status) const if (U_SUCCESS(status)) { return 0; } - return (uint32_t)(0xFFFFFFFFu); + return static_cast(0xFFFFFFFFu); } UnicodeSet * TestCollator::getTailoredSet(UErrorCode &status) const @@ -2262,7 +2262,7 @@ void CollationAPITest::TestSubclass() UErrorCode status = U_ZERO_ERROR; col1.getCollationKey(abc, key, status); int32_t length = 0; - const char* bytes = (const char *)key.getByteArray(length); + const char* bytes = reinterpret_cast(key.getByteArray(length)); UnicodeString keyarray(bytes, length, nullptr, status); if (abc != keyarray) { errln("TestCollator collationkey API is returning wrong values"); @@ -2287,7 +2287,7 @@ void CollationAPITest::TestSubclass() TestCollator col3(UCOL_TERTIARY, UNORM_NONE); UnicodeString a("a"); UnicodeString b("b"); - Collator::EComparisonResult result = Collator::EComparisonResult(a.compare(b)); + Collator::EComparisonResult result = static_cast(a.compare(b)); if(col1.compare(a, b) != result) { errln("Collator doesn't give default result"); } @@ -2304,8 +2304,8 @@ void CollationAPITest::TestNullptrCharTailoring() UErrorCode status = U_ZERO_ERROR; char16_t buf[256] = {0}; int32_t len = u_unescape("&a < '\\u0000'", buf, 256); - UnicodeString first((char16_t)0x0061); - UnicodeString second((char16_t)0); + UnicodeString first(static_cast(0x0061)); + UnicodeString second(static_cast(0)); RuleBasedCollator *coll = new RuleBasedCollator(UnicodeString(buf, len), status); if(U_FAILURE(status)) { delete coll; @@ -2381,22 +2381,22 @@ void CollationAPITest::TestCloneBinary() { return; } rbc->setAttribute(UCOL_STRENGTH, UCOL_PRIMARY, errorCode); - UnicodeString uUmlaut((char16_t)0xfc); + UnicodeString uUmlaut(static_cast(0xfc)); UnicodeString ue = UNICODE_STRING_SIMPLE("ue"); - assertEquals("rbc/primary: u-umlaut==ue", (int32_t)UCOL_EQUAL, rbc->compare(uUmlaut, ue, errorCode)); + assertEquals("rbc/primary: u-umlaut==ue", static_cast(UCOL_EQUAL), rbc->compare(uUmlaut, ue, errorCode)); uint8_t bin[25000]; int32_t binLength = rbc->cloneBinary(bin, UPRV_LENGTHOF(bin), errorCode); if(errorCode.errDataIfFailureAndReset("rbc->cloneBinary()")) { return; } - logln("rbc->cloneBinary() -> %d bytes", (int)binLength); + logln("rbc->cloneBinary() -> %d bytes", static_cast(binLength)); RuleBasedCollator rbc2(bin, binLength, rbRoot, errorCode); if(errorCode.errDataIfFailureAndReset("RuleBasedCollator(rbc binary)")) { return; } - assertEquals("rbc2.strength==primary", (int32_t)UCOL_PRIMARY, rbc2.getAttribute(UCOL_STRENGTH, errorCode)); - assertEquals("rbc2: u-umlaut==ue", (int32_t)UCOL_EQUAL, rbc2.compare(uUmlaut, ue, errorCode)); + assertEquals("rbc2.strength==primary", static_cast(UCOL_PRIMARY), rbc2.getAttribute(UCOL_STRENGTH, errorCode)); + assertEquals("rbc2: u-umlaut==ue", static_cast(UCOL_EQUAL), rbc2.compare(uUmlaut, ue, errorCode)); assertTrue("rbc==rbc2", *rbc == rbc2); uint8_t bin2[25000]; int32_t bin2Length = rbc2.cloneBinary(bin2, UPRV_LENGTHOF(bin2), errorCode); @@ -2407,8 +2407,8 @@ void CollationAPITest::TestCloneBinary() { if(errorCode.errDataIfFailureAndReset("RuleBasedCollator(rbc binary, length<0)")) { return; } - assertEquals("rbc3.strength==primary", (int32_t)UCOL_PRIMARY, rbc3.getAttribute(UCOL_STRENGTH, errorCode)); - assertEquals("rbc3: u-umlaut==ue", (int32_t)UCOL_EQUAL, rbc3.compare(uUmlaut, ue, errorCode)); + assertEquals("rbc3.strength==primary", static_cast(UCOL_PRIMARY), rbc3.getAttribute(UCOL_STRENGTH, errorCode)); + assertEquals("rbc3: u-umlaut==ue", static_cast(UCOL_EQUAL), rbc3.compare(uUmlaut, ue, errorCode)); assertTrue("rbc==rbc3", *rbc == rbc3); } @@ -2432,7 +2432,7 @@ void CollationAPITest::TestIterNumeric() { uiter_setUTF8(&iter40, "\x34\x30", 2); uiter_setUTF8(&iter72, "\x37\x32", 2); UCollationResult result = coll.compare(iter40, iter72, errorCode); - assertEquals("40<72", (int32_t)UCOL_LESS, (int32_t)result); + assertEquals("40<72", static_cast(UCOL_LESS), static_cast(result)); } void CollationAPITest::TestBadKeywords() { diff --git a/icu4c/source/test/intltest/astrotst.cpp b/icu4c/source/test/intltest/astrotst.cpp index c51e6f247462..be72136545a7 100644 --- a/icu4c/source/test/intltest/astrotst.cpp +++ b/icu4c/source/test/intltest/astrotst.cpp @@ -113,11 +113,15 @@ void AstroTest::TestLunarPosition() { for (int32_t i = 0; i < UPRV_LENGTHOF(tests); i++) { gc->clear(); - gc->set((int32_t)tests[i][0], (int32_t)tests[i][1]-1, (int32_t)tests[i][2], (int32_t)tests[i][3], (int32_t)tests[i][4]); + gc->set(static_cast(tests[i][0]), + static_cast(tests[i][1]) - 1, + static_cast(tests[i][2]), + static_cast(tests[i][3]), + static_cast(tests[i][4])); CalendarAstronomer astro(gc->getTime(status)); const CalendarAstronomer::Equatorial& result = astro.getMoonPosition(); - logln((UnicodeString)"Moon position is " + result.toString() + (UnicodeString)"; " /* + result->toHmsString()*/); + logln(UnicodeString("Moon position is ") + result.toString() + UnicodeString("; ") /* + result->toHmsString()*/); } close(status); @@ -134,7 +138,7 @@ void AstroTest::TestCoordinates() { CalendarAstronomer::Equatorial result; CalendarAstronomer astro; astro.eclipticToEquatorial(result, 139.686111 * CalendarAstronomer::PI / 180.0, 4.875278* CalendarAstronomer::PI / 180.0); - logln((UnicodeString)"result is " + result.toString() + (UnicodeString)"; " /* + result.toHmsString()*/ ); + logln(UnicodeString("result is ") + result.toString() + UnicodeString("; ") /* + result.toHmsString()*/); close(status); ASSERT_OK(status); } @@ -167,8 +171,8 @@ void AstroTest::TestCoverage() { CalendarAstronomer *anAstro = astronomers[i]; //logln("astro: " + astro); - logln((UnicodeString)" date: " + anAstro->getTime()); - logln((UnicodeString)" equ ecl: " + (anAstro->eclipticToEquatorial(eq,eclLat,eclLong)).toString()); + logln(UnicodeString(" date: ") + anAstro->getTime()); + logln(UnicodeString(" equ ecl: ") + (anAstro->eclipticToEquatorial(eq, eclLat, eclLong)).toString()); } delete myastro; @@ -265,21 +269,28 @@ void AstroTest::TestMoonAge(){ static const double precision = CalendarAstronomer::PI/32; for (int32_t i = 0; i < UPRV_LENGTHOF(testcase); i++) { gc->clear(); - logln((UnicodeString)"CASE["+i+"]: Year "+(int32_t)testcase[i][0]+" Month "+(int32_t)testcase[i][1]+" Day "+ - (int32_t)testcase[i][2]+" Hour "+(int32_t)testcase[i][3]+" Minutes "+(int32_t)testcase[i][4]+ - " Seconds "+(int32_t)testcase[i][5]); - gc->set((int32_t)testcase[i][0], (int32_t)testcase[i][1]-1, (int32_t)testcase[i][2], (int32_t)testcase[i][3], (int32_t)testcase[i][4], (int32_t)testcase[i][5]); + logln(UnicodeString("CASE[") + i + + "]: Year " + static_cast(testcase[i][0]) + + " Month " + static_cast(testcase[i][1]) + + " Day " + static_cast(testcase[i][2]) + + " Hour " + static_cast(testcase[i][3]) + + " Minutes " + static_cast(testcase[i][4]) + + " Seconds " + static_cast(testcase[i][5])); + gc->set(static_cast(testcase[i][0]), + static_cast(testcase[i][1]) - 1, + static_cast(testcase[i][2]), + static_cast(testcase[i][3]), + static_cast(testcase[i][4]), + static_cast(testcase[i][5])); CalendarAstronomer astro(gc->getTime(status)); double expectedAge = (angle[i]*CalendarAstronomer::PI)/180; double got = astro.getMoonAge(); //logln(testString); if(!(got>expectedAge-precision && got(strtoul(start, &end, 10)); if(end<=start || (!U_IS_INV_WHITESPACE(*end) && *end!=0 && *end!=';') || value>(UBIDI_MAX_EXPLICIT_LEVEL+1)) { - errln("\nError on line %d: Levels parse error at %s", (int)lineNumber, start); + errln("\nError on line %d: Levels parse error at %s", static_cast(lineNumber), start); printErrorLine(); return false; } - levels[levelsCount++]=(UBiDiLevel)value; + levels[levelsCount++] = static_cast(value); directionBits|=(1<<(value&1)); start=end; } @@ -107,13 +107,13 @@ UBool BiDiConformanceTest::parseOrdering(const char *start) { orderingCount=0; while(*start!=0 && *(start=u_skipWhitespace(start))!=0 && *start!=';') { char *end; - uint32_t value=(uint32_t)strtoul(start, &end, 10); + uint32_t value = static_cast(strtoul(start, &end, 10)); if(end<=start || (!U_IS_INV_WHITESPACE(*end) && *end!=0 && *end!=';') || value>=1000) { - errln("\nError on line %d: Reorder parse error at %s", (int)lineNumber, start); + errln("\nError on line %d: Reorder parse error at %s", static_cast(lineNumber), start); printErrorLine(); return false; } - ordering[orderingCount++]=(int32_t)value; + ordering[orderingCount++] = static_cast(value); start=end; } return true; @@ -250,7 +250,7 @@ UBool BiDiConformanceTest::parseInputStringFromBiDiClasses(const char *&start) { start+=biDiClassNameLength; continue; } - errln("\nError on line %d: BiDi class string not recognized at %s", (int)lineNumber, start); + errln("\nError on line %d: BiDi class string not recognized at %s", static_cast(lineNumber), start); printErrorLine(); return false; } @@ -284,7 +284,7 @@ void BiDiConformanceTest::TestBidiTest() { errorCount=0; // paraLevelName must be initialized in case the first non-comment line is in error paraLevelName="N/A"; - while(errorCount<10 && fgets(line, (int)sizeof(line), bidiTestFile.getAlias())!=nullptr) { + while (errorCount < 10 && fgets(line, static_cast(sizeof(line)), bidiTestFile.getAlias()) != nullptr) { ++lineNumber; // Remove trailing comments and whitespace. char *commentStart=strchr(line, '#'); @@ -320,7 +320,7 @@ void BiDiConformanceTest::TestBidiTest() { } start=u_skipWhitespace(start+1); char *end; - uint32_t bitset=(uint32_t)strtoul(start, &end, 16); + uint32_t bitset = static_cast(strtoul(start, &end, 16)); if(end<=start || (!U_IS_INV_WHITESPACE(*end) && *end!=';' && *end!=0)) { errln("input bitset parse error at %s", start); return; @@ -334,7 +334,7 @@ void BiDiConformanceTest::TestBidiTest() { paraLevels[i], nullptr, errorCode); const UBiDiLevel *actualLevels=ubidi_getLevels(ubidi.getAlias(), errorCode); if(errorCode.errIfFailureAndReset("ubidi_setPara() or ubidi_getLevels()")) { - errln("Input line %d: %s", (int)lineNumber, line); + errln("Input line %d: %s", static_cast(lineNumber), line); return; } paraLevelName=paraLevelNames[i]; @@ -446,7 +446,7 @@ void BiDiConformanceTest::TestBidiCharacterTest() { levelsCount=0; orderingCount=0; errorCount=0; - while(errorCount<20 && fgets(line, (int)sizeof(line), bidiTestFile.getAlias())!=nullptr) { + while (errorCount < 20 && fgets(line, static_cast(sizeof(line)), bidiTestFile.getAlias()) != nullptr) { ++lineNumber; paraLevelName="N/A"; inputString="N/A"; @@ -464,7 +464,7 @@ void BiDiConformanceTest::TestBidiCharacterTest() { char16_t *buffer=inputString.getBuffer(200); int32_t length=u_parseString(start, buffer, inputString.getCapacity(), nullptr, errorCode); if(errorCode.errIfFailureAndReset("Invalid string in field 0")) { - errln("Input line %d: %s", (int)lineNumber, line); + errln("Input line %d: %s", static_cast(lineNumber), line); inputString.remove(); continue; } @@ -472,12 +472,12 @@ void BiDiConformanceTest::TestBidiCharacterTest() { start=strchr(start, ';'); if(start==nullptr) { errorCount++; - errln("\nError on line %d: Missing ; separator on line: %s", (int)lineNumber, line); + errln("\nError on line %d: Missing ; separator on line: %s", static_cast(lineNumber), line); continue; } start=u_skipWhitespace(start+1); char *end; - int32_t paraDirection=(int32_t)strtol(start, &end, 10); + int32_t paraDirection = static_cast(strtol(start, &end, 10)); UBiDiLevel paraLevel=UBIDI_MAX_EXPLICIT_LEVEL+2; if(paraDirection==0) { paraLevel=0; @@ -496,34 +496,34 @@ void BiDiConformanceTest::TestBidiCharacterTest() { paraLevelName="Auto/RTL"; } else if(paraDirection<0 && -paraDirection<=(UBIDI_MAX_EXPLICIT_LEVEL+1)) { - paraLevel=(UBiDiLevel)(-paraDirection); - snprintf(levelNameString, sizeof(levelNameString), "%d", (int)paraLevel); + paraLevel = static_cast(-paraDirection); + snprintf(levelNameString, sizeof(levelNameString), "%d", static_cast(paraLevel)); paraLevelName=levelNameString; } if(end<=start || (!U_IS_INV_WHITESPACE(*end) && *end!=';' && *end!=0) || paraLevel==(UBIDI_MAX_EXPLICIT_LEVEL+2)) { - errln("\nError on line %d: Input paragraph direction incorrect at %s", (int)lineNumber, start); + errln("\nError on line %d: Input paragraph direction incorrect at %s", static_cast(lineNumber), start); printErrorLine(); continue; } start=u_skipWhitespace(end); if(*start!=';') { errorCount++; - errln("\nError on line %d: Missing ; separator on line: %s", (int)lineNumber, line); + errln("\nError on line %d: Missing ; separator on line: %s", static_cast(lineNumber), line); continue; } start++; - uint32_t resolvedParaLevel=(uint32_t)strtoul(start, &end, 10); + uint32_t resolvedParaLevel = static_cast(strtoul(start, &end, 10)); if(end<=start || (!U_IS_INV_WHITESPACE(*end) && *end!=';' && *end!=0) || resolvedParaLevel>1) { - errln("\nError on line %d: Resolved paragraph level incorrect at %s", (int)lineNumber, start); + errln("\nError on line %d: Resolved paragraph level incorrect at %s", static_cast(lineNumber), start); printErrorLine(); continue; } start=u_skipWhitespace(end); if(*start!=';') { errorCount++; - errln("\nError on line %d: Missing ; separator on line: %s", (int)lineNumber, line); + errln("\nError on line %d: Missing ; separator on line: %s", static_cast(lineNumber), line); return; } start++; @@ -543,14 +543,14 @@ void BiDiConformanceTest::TestBidiCharacterTest() { paraLevel, nullptr, errorCode); const UBiDiLevel *actualLevels=ubidi_getLevels(ubidi.getAlias(), errorCode); if(errorCode.errIfFailureAndReset("ubidi_setPara() or ubidi_getLevels()")) { - errln("Input line %d: %s", (int)lineNumber, line); + errln("Input line %d: %s", static_cast(lineNumber), line); continue; } UBiDiLevel actualLevel; if((actualLevel=ubidi_getParaLevel(ubidi.getAlias()))!=resolvedParaLevel) { printErrorLine(); errln("\nError on line %d: Wrong resolved paragraph level; expected %d actual %d", - (int)lineNumber, resolvedParaLevel, actualLevel); + static_cast(lineNumber), resolvedParaLevel, actualLevel); continue; } if(!checkLevels(actualLevels, ubidi_getProcessedLength(ubidi.getAlias()))) { @@ -582,7 +582,7 @@ UBool BiDiConformanceTest::checkLevels(const UBiDiLevel actualLevels[], int32_t UBool isOk=true; if(levelsCount!=actualCount) { errln("\nError on line %d: Wrong number of level values; expected %d actual %d", - (int)lineNumber, (int)levelsCount, (int)actualCount); + static_cast(lineNumber), static_cast(levelsCount), static_cast(actualCount)); isOk=false; } else { for(int32_t i=0; i(lineNumber), static_cast(i), levels[i], actualLevels[i]); isOk=false; break; } @@ -607,11 +607,11 @@ UBool BiDiConformanceTest::checkLevels(const UBiDiLevel actualLevels[], int32_t UnicodeString els("Expected levels: "); int32_t i; for(i=0; i(0x20)).append(printLevel(levels[i])); } UnicodeString als("Actual levels: "); for(i=0; i(0x20)).append(printLevel(actualLevels[i])); } errln(els); errln(als); @@ -634,7 +634,7 @@ UBool BiDiConformanceTest::checkOrdering(UBiDi *ubidi) { for(i=visualIndex=0; i(lineNumber), line); return false; } if(levels[logicalIndex]>=UBIDI_DEFAULT_LTR) { @@ -642,7 +642,7 @@ UBool BiDiConformanceTest::checkOrdering(UBiDi *ubidi) { } if(visualIndex(lineNumber), static_cast(visualIndex), ordering[visualIndex], logicalIndex); isOk=false; break; } @@ -652,20 +652,20 @@ UBool BiDiConformanceTest::checkOrdering(UBiDi *ubidi) { // which should match the length of the BidiTest.txt ordering. if(isOk && orderingCount!=visualIndex) { errln("\nError on line %d: Wrong number of ordering values; expected %d actual %d", - (int)lineNumber, (int)orderingCount, (int)visualIndex); + static_cast(lineNumber), static_cast(orderingCount), static_cast(visualIndex)); isOk=false; } if(!isOk) { printErrorLine(); UnicodeString eord("Expected ordering: "); for(i=0; i(0x20)).append(static_cast(0x30 + ordering[i])); } UnicodeString aord("Actual ordering: "); for(i=0; i(0x20)).append(static_cast(0x30 + logicalIndex)); } } errln(eord); @@ -676,7 +676,7 @@ UBool BiDiConformanceTest::checkOrdering(UBiDi *ubidi) { void BiDiConformanceTest::printErrorLine() { ++errorCount; - errln("Input line %5d: %s", (int)lineNumber, line); + errln("Input line %5d: %s", static_cast(lineNumber), line); errln(UnicodeString("Input string: ")+inputString); errln("Para level: %s", paraLevelName); } diff --git a/icu4c/source/test/intltest/bytestrietest.cpp b/icu4c/source/test/intltest/bytestrietest.cpp index 923eb6a4b59a..98b5cb39423c 100644 --- a/icu4c/source/test/intltest/bytestrietest.cpp +++ b/icu4c/source/test/intltest/bytestrietest.cpp @@ -176,10 +176,10 @@ void BytesTrieTest::TestBranches() { { "t", 0x400000 }, { "uu", 0x800000 }, { "vv", 0x7fffffff }, - { "zz", (int32_t)0x80000000 } + { "zz", static_cast(0x80000000) } }; for(int32_t length=2; length<=UPRV_LENGTHOF(data); ++length) { - logln("TestBranches length=%d", (int)length); + logln("TestBranches length=%d", static_cast(length)); checkData(data, length); } } @@ -223,7 +223,7 @@ void BytesTrieTest::TestLongBranch() { { "r", 0x333333 }, { "s2345", 0x4444444 }, { "t234567890", 0x77777777 }, - { "z", (int32_t)0x80000001 } + { "z", static_cast(0x80000001) } }; checkData(data, UPRV_LENGTHOF(data)); } @@ -633,17 +633,17 @@ void BytesTrieTest::TestDelta() { assertEquals(UnicodeString(u"differently encoded delta ") + delta + u" at byte index " + i, b0, b1); } - const uint8_t *start = (const uint8_t *)intBytes0; + const uint8_t* start = reinterpret_cast(intBytes0); const uint8_t *pos = BytesTrie::jumpByDelta(start); assertEquals(UnicodeString(u"roundtrip for delta ") + delta, - delta, (size_t)(pos - start) - length0); + delta, static_cast(pos - start) - length0); } } void BytesTrieTest::checkData(const StringAndValue data[], int32_t dataLength) { - logln("checkData(dataLength=%d, fast)", (int)dataLength); + logln("checkData(dataLength=%d, fast)", static_cast(dataLength)); checkData(data, dataLength, USTRINGTRIE_BUILD_FAST); - logln("checkData(dataLength=%d, small)", (int)dataLength); + logln("checkData(dataLength=%d, small)", static_cast(dataLength)); checkData(data, dataLength, USTRINGTRIE_BUILD_SMALL); } @@ -690,7 +690,7 @@ BytesTrie *BytesTrieTest::buildTrie(const StringAndValue data[], int32_t dataLen errln("builder.build().add(zzz) did not set U_NO_WRITE_PERMISSION"); } } - logln("serialized trie size: %ld bytes\n", (long)sp.length()); + logln("serialized trie size: %ld bytes\n", static_cast(sp.length())); StringPiece sp2=builder_->buildStringPiece(buildOption, errorCode); if(sp.data()==sp2.data()) { errln("builder.buildStringPiece() before & after build() returned same array"); @@ -743,8 +743,8 @@ void BytesTrieTest::checkNext(BytesTrie &trie, } else if(trie.getValue()!=data[i].value) { errln("trie value for %s is %ld=0x%lx instead of expected %ld=0x%lx", data[i].s, - (long)trie.getValue(), (long)trie.getValue(), - (long)data[i].value, (long)data[i].value); + static_cast(trie.getValue()), static_cast(trie.getValue()), + static_cast(data[i].value), static_cast(data[i].value)); } else if(result!=trie.current() || trie.getValue()!=data[i].value) { errln("trie value for %s changes when repeating current()/getValue()", data[i].s); } @@ -861,8 +861,8 @@ void BytesTrieTest::checkNextWithState(BytesTrie &trie, } else if(trie.getValue()!=data[i].value) { errln("trie value for %s is %ld=0x%lx instead of expected %ld=0x%lx", data[i].s, - (long)trie.getValue(), (long)trie.getValue(), - (long)data[i].value, (long)data[i].value); + static_cast(trie.getValue()), static_cast(trie.getValue()), + static_cast(data[i].value), static_cast(data[i].value)); } trie.reset(); } @@ -916,8 +916,8 @@ void BytesTrieTest::checkNextWithState64(BytesTrie &trie, } else if(trie.getValue()!=data[i].value) { errln("trie value for %s is %ld=0x%lx instead of expected %ld=0x%lx", data[i].s, - (long)trie.getValue(), (long)trie.getValue(), - (long)data[i].value, (long)data[i].value); + static_cast(trie.getValue()), static_cast(trie.getValue()), + static_cast(data[i].value), static_cast(data[i].value)); } trie.reset(); } @@ -957,26 +957,26 @@ void BytesTrieTest::checkIterator(BytesTrie::Iterator &iter, IcuTestErrorCode errorCode(*this, "checkIterator()"); for(int32_t i=0; i(i), data[i].s); break; } UBool hasNext=iter.next(errorCode); - if(errorCode.errIfFailureAndReset("trie iterator next() for item %d: %s", (int)i, data[i].s)) { + if (errorCode.errIfFailureAndReset("trie iterator next() for item %d: %s", static_cast(i), data[i].s)) { break; } if(!hasNext) { - errln("trie iterator next()=false for item %d: %s", (int)i, data[i].s); + errln("trie iterator next()=false for item %d: %s", static_cast(i), data[i].s); break; } if(iter.getString()!=StringPiece(data[i].s)) { errln("trie iterator next().getString()=%s but expected %s for item %d", - iter.getString().data(), data[i].s, (int)i); + iter.getString().data(), data[i].s, static_cast(i)); } if(iter.getValue()!=data[i].value) { errln("trie iterator next().getValue()=%ld=0x%lx but expected %ld=0x%lx for item %d: %s", - (long)iter.getValue(), (long)iter.getValue(), - (long)data[i].value, (long)data[i].value, - (int)i, data[i].s); + static_cast(iter.getValue()), static_cast(iter.getValue()), + static_cast(data[i].value), static_cast(data[i].value), + static_cast(i), data[i].s); } } if(iter.hasNext()) { diff --git a/icu4c/source/test/intltest/calcasts.cpp b/icu4c/source/test/intltest/calcasts.cpp index 9c125d9af5a7..c07d4c1dea1f 100644 --- a/icu4c/source/test/intltest/calcasts.cpp +++ b/icu4c/source/test/intltest/calcasts.cpp @@ -95,14 +95,14 @@ UBool CalendarCaseTest::checkField(Calendar *cal, UCalendarDateFields field, int if(U_FAILURE(status)) return false; int32_t res = cal->get(field, status); if(U_FAILURE(status)) { - errln((UnicodeString)"Checking field " + fieldName(field) + " and got " + u_errorName(status)); + errln(UnicodeString("Checking field ") + fieldName(field) + " and got " + u_errorName(status)); return false; } if(res != value) { - errln((UnicodeString)"FAIL: Checking field " + fieldName(field) + " expected " + value + " and got " + res + UnicodeString("\n")); + errln(UnicodeString("FAIL: Checking field ") + fieldName(field) + " expected " + value + " and got " + res + UnicodeString("\n")); return false; } else { - logln((UnicodeString)"Checking field " + fieldName(field) + " == " + value + UnicodeString("\n")); + logln(UnicodeString("Checking field ") + fieldName(field) + " == " + value + UnicodeString("\n")); } return true; } @@ -183,9 +183,9 @@ void CalendarCaseTest::IslamicCivil() } fmt->setTimeZone(*TimeZone::getGMT()); - fmt->format((UDate)2486076.5, result); + fmt->format(static_cast(2486076.5), result); if (result != expectedUChars) { - errln((UnicodeString)"FAIL: DateFormatting failed. Got " + result + " and expected " + UnicodeString(expectedUChars) + UnicodeString("\n")); + errln(UnicodeString("FAIL: DateFormatting failed. Got ") + result + " and expected " + UnicodeString(expectedUChars) + UnicodeString("\n")); errln("Maybe the resource aliasing isn't working"); } delete fmt; diff --git a/icu4c/source/test/intltest/callimts.cpp b/icu4c/source/test/intltest/callimts.cpp index 3ab6166ac5cc..bbac90cea1f7 100644 --- a/icu4c/source/test/intltest/callimts.cpp +++ b/icu4c/source/test/intltest/callimts.cpp @@ -216,7 +216,7 @@ void CalendarLimitTest::TestLimitsThread(int32_t threadNum) { continue; } if (uprv_strcmp(cal->getType(), testCase.type) != 0) { - errln((UnicodeString)"FAIL: Wrong calendar type: " + cal->getType() + errln(UnicodeString("FAIL: Wrong calendar type: ") + cal->getType() + " Requested: " + testCase.type); continue; } @@ -251,12 +251,12 @@ CalendarLimitTest::doTheoreticalLimitsTest(Calendar& cal, UBool leapMonth) { if (!leapMonth) { expected = maxM*maxDOM; if (maxDOY > expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of DAY_OF_YEAR is too big: " + errln(UnicodeString("FAIL: [") + calType + "] Maximum value of DAY_OF_YEAR is too big: " + maxDOY + "/expected: <=" + expected); } expected = lmaxM*lmaxDOM; if (lmaxDOW < expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of DAY_OF_YEAR is too small: " + errln(UnicodeString("FAIL: [") + calType + "] Least maximum value of DAY_OF_YEAR is too small: " + lmaxDOW + "/expected: >=" + expected); } } @@ -264,36 +264,36 @@ CalendarLimitTest::doTheoreticalLimitsTest(Calendar& cal, UBool leapMonth) { // Week of year expected = maxDOY/nDOW + 1; if (maxWOY > expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of WEEK_OF_YEAR is too big: " + errln(UnicodeString("FAIL: [") + calType + "] Maximum value of WEEK_OF_YEAR is too big: " + maxWOY + "/expected: <=" + expected); } expected = lmaxDOW/nDOW; if (lmaxWOY < expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of WEEK_OF_YEAR is too small: " + errln(UnicodeString("FAIL: [") + calType + "] Least maximum value of WEEK_OF_YEAR is too small: " + lmaxWOY + "/expected >=" + expected); } // Day of week in month expected = (maxDOM + nDOW - 1)/nDOW; if (maxDOWIM != expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + errln(UnicodeString("FAIL: [") + calType + "] Maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + maxDOWIM + "/expected: " + expected); } expected = (lmaxDOM + nDOW - 1)/nDOW; if (lmaxDOWIM != expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + errln(UnicodeString("FAIL: [") + calType + "] Least maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + lmaxDOWIM + "/expected: " + expected); } // Week of month expected = (maxDOM + (nDOW - 1) + (nDOW - minDaysInFirstWeek)) / nDOW; if (maxWOM != expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of WEEK_OF_MONTH is incorrect: " + errln(UnicodeString("FAIL: [") + calType + "] Maximum value of WEEK_OF_MONTH is incorrect: " + maxWOM + "/expected: " + expected); } expected = (lmaxDOM + (nDOW - minDaysInFirstWeek)) / nDOW; if (lmaxWOM != expected) { - errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of WEEK_OF_MONTH is incorrect: " + errln(UnicodeString("FAIL: [") + calType + "] Least maximum value of WEEK_OF_MONTH is incorrect: " + lmaxWOM + "/expected: " + expected); } } @@ -345,7 +345,7 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, if (failure(status, "GregorianCalendar::setTime")) { return; } - logln((UnicodeString)"Start: " + startDate); + logln(UnicodeString("Start: ") + startDate); if (fieldsToTest == nullptr) { fieldsToTest = FIELDS; @@ -372,7 +372,7 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, : ucal_getNow() < millis; ++i) { if (ucal_getNow() >= mark) { - logln((UnicodeString)"(" + i + " days)"); + logln(UnicodeString("(") + i + " days)"); mark += 5000; // 5 sec } UDate testMillis = greg.getTime(status); @@ -382,7 +382,7 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, return; } for (j = 0; fieldsToTest[j] >= 0; ++j) { - UCalendarDateFields f = (UCalendarDateFields)fieldsToTest[j]; + UCalendarDateFields f = static_cast(fieldsToTest[j]); int32_t v = cal.get(f, status); int32_t minActual = cal.getActualMinimum(f, status); int32_t maxActual = cal.getActualMaximum(f, status); @@ -409,21 +409,21 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, } if (minActual < minLow || minActual > minHigh) { - errln((UnicodeString)"Fail: [" + cal.getType() + "] " + + errln(UnicodeString("Fail: [") + cal.getType() + "] " + ymdToString(cal, ymd) + " Range for min of " + FIELD_NAME[f] + "(" + f + ")=" + minLow + ".." + minHigh + ", actual_min=" + minActual); } if (maxActual < maxLow || maxActual > maxHigh) { - errln((UnicodeString)"Fail: [" + cal.getType() + "] " + + errln(UnicodeString("Fail: [") + cal.getType() + "] " + ymdToString(cal, ymd) + " Range for max of " + FIELD_NAME[f] + "(" + f + ")=" + maxLow + ".." + maxHigh + ", actual_max=" + maxActual); } if (v < minActual || v > maxActual) { - errln((UnicodeString)"Fail: [" + cal.getType() + "] " + + errln(UnicodeString("Fail: [") + cal.getType() + "] " + ymdToString(cal, ymd) + " " + FIELD_NAME[f] + "(" + f + ")=" + v + ", actual=" + minActual + ".." + maxActual + @@ -443,10 +443,10 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, for (j = 0; fieldsToTest[j] >= 0; ++j) { int32_t rangeLow, rangeHigh; UBool fullRangeSeen = true; - UCalendarDateFields f = (UCalendarDateFields)fieldsToTest[j]; + UCalendarDateFields f = static_cast(fieldsToTest[j]); buf.remove(); - buf.append((UnicodeString)"[" + cal.getType() + "] " + FIELD_NAME[f]); + buf.append(UnicodeString("[") + cal.getType() + "] " + FIELD_NAME[f]); // Minimum rangeLow = cal.getMinimum(f); @@ -454,8 +454,8 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, if (limits[j][0] != rangeLow || limits[j][1] != rangeHigh) { fullRangeSeen = false; } - buf.append((UnicodeString)" minima range=" + rangeLow + ".." + rangeHigh); - buf.append((UnicodeString)" minima actual=" + limits[j][0] + ".." + limits[j][1]); + buf.append(UnicodeString(" minima range=") + rangeLow + ".." + rangeHigh); + buf.append(UnicodeString(" minima actual=") + limits[j][0] + ".." + limits[j][1]); // Maximum rangeLow = cal.getLeastMaximum(f); @@ -463,27 +463,27 @@ CalendarLimitTest::doLimitsTest(Calendar& cal, if (limits[j][2] != rangeLow || limits[j][3] != rangeHigh) { fullRangeSeen = false; } - buf.append((UnicodeString)" maxima range=" + rangeLow + ".." + rangeHigh); - buf.append((UnicodeString)" maxima actual=" + limits[j][2] + ".." + limits[j][3]); + buf.append(UnicodeString(" maxima range=") + rangeLow + ".." + rangeHigh); + buf.append(UnicodeString(" maxima actual=") + limits[j][2] + ".." + limits[j][3]); if (fullRangeSeen) { - logln((UnicodeString)"OK: " + buf); + logln(UnicodeString("OK: ") + buf); } else { // This may or may not be an error -- if the range of dates // we scan over doesn't happen to contain a minimum or // maximum, it doesn't mean some other range won't. - logln((UnicodeString)"Warning: " + buf); + logln(UnicodeString("Warning: ") + buf); } } - logln((UnicodeString)"End: " + greg.getTime(status)); + logln(UnicodeString("End: ") + greg.getTime(status)); } UnicodeString& CalendarLimitTest::ymdToString(const Calendar& cal, UnicodeString& str) { UErrorCode status = U_ZERO_ERROR; str.remove(); - str.append((UnicodeString)"" + cal.get(UCAL_EXTENDED_YEAR, status) + str.append(UnicodeString("") + cal.get(UCAL_EXTENDED_YEAR, status) + "/" + (cal.get(UCAL_MONTH, status) + 1) + (cal.get(UCAL_IS_LEAP_MONTH, status) == 1 ? "(leap)" : "") + "/" + cal.get(UCAL_DATE, status) diff --git a/icu4c/source/test/intltest/calregts.cpp b/icu4c/source/test/intltest/calregts.cpp index da458413e902..82fb3eade63f 100644 --- a/icu4c/source/test/intltest/calregts.cpp +++ b/icu4c/source/test/intltest/calregts.cpp @@ -1007,8 +1007,8 @@ void CalendarRegressionTest::test4103271() UBool fail = false; for (int32_t firstDay=1; firstDay<=2; firstDay++) { for (int32_t minDays=1; minDays<=7; minDays++) { - testCal->setMinimalDaysInFirstWeek((uint8_t)minDays); - testCal->setFirstDayOfWeek((UCalendarDaysOfWeek)firstDay); + testCal->setMinimalDaysInFirstWeek(static_cast(minDays)); + testCal->setFirstDayOfWeek(static_cast(firstDay)); testDesc = (UnicodeString("Test") + firstDay + minDays); logln(testDesc + " => 1st day of week=" + firstDay + @@ -1047,7 +1047,7 @@ void CalendarRegressionTest::test4103271() for (int32_t j=0; j<44; j+=22) { logln(UnicodeString("Minimal days in first week = ") + DATA[j] + " Week starts on Sunday"); - testCal->setMinimalDaysInFirstWeek((uint8_t)DATA[j]); + testCal->setMinimalDaysInFirstWeek(static_cast(DATA[j])); testCal->set(1997, UCAL_DECEMBER, 21); for (int32_t i=0; i<21; ++i) { int32_t woy = testCal->get(UCAL_WEEK_OF_YEAR,status); @@ -1352,13 +1352,13 @@ void CalendarRegressionTest::test4114578() for (int32_t i=0; i<32; i+=4) { UDate date = DATA[i]; - int32_t amt = (int32_t) DATA[i+2]; + int32_t amt = static_cast(DATA[i + 2]); double expectedChange = DATA[i+3]; log(UnicodeString("") + date); cal->setTime(date,status); - switch ((int32_t) DATA[i+1]) { + switch (static_cast(DATA[i + 1])) { case ADD: log(UnicodeString(" add (HOUR,") + (amt<0?"":"+")+amt + ")= "); cal->add(UCAL_HOUR, amt,status); @@ -1556,20 +1556,20 @@ void CalendarRegressionTest::Test13745() } // this line would overflow before fix 13745 - cal->setGregorianChange(((double)INT32_MAX+1.0) * MILLIS_IN_DAY, status); + cal->setGregorianChange((static_cast(INT32_MAX) + 1.0) * MILLIS_IN_DAY, status); if(U_FAILURE(status)) { errln("%s:%d Failure setting INT32_MAX+1 change on calendar: %s\n", __FILE__, __LINE__, u_errorName(status)); return; } - assertEquals("getGregorianChange()", (double)INT32_MAX * MILLIS_IN_DAY, cal->getGregorianChange()); + assertEquals("getGregorianChange()", static_cast(INT32_MAX) * MILLIS_IN_DAY, cal->getGregorianChange()); // test underflow - cal->setGregorianChange(((double)INT32_MIN-1.0) * MILLIS_IN_DAY, status); + cal->setGregorianChange((static_cast(INT32_MIN) - 1.0) * MILLIS_IN_DAY, status); if(U_FAILURE(status)) { errln("%s:%d Failure setting INT32_MAX-1 change on calendar: %s\n", __FILE__, __LINE__, u_errorName(status)); return; } - assertEquals("getGregorianChange()", (double)INT32_MIN * MILLIS_IN_DAY, cal->getGregorianChange()); + assertEquals("getGregorianChange()", static_cast(INT32_MIN) * MILLIS_IN_DAY, cal->getGregorianChange()); delete cal; } @@ -1590,7 +1590,7 @@ void CalendarRegressionTest::test4142933() return; } //try { - calendar->roll((UCalendarDateFields)-1, true, status); + calendar->roll(static_cast(-1), true, status); if(U_SUCCESS(status)) errln("Test failed, no exception thrown"); //} @@ -1700,9 +1700,9 @@ void CalendarRegressionTest::test4147269() // Note: In the bug report, getActualMaximum() was called instead // of getMaximum() -- this was an error. The validation code doesn't // use getActualMaximum(), since that's too costly. - int32_t max = calendar->getMaximum((UCalendarDateFields)field); + int32_t max = calendar->getMaximum(static_cast(field)); int32_t value = max+1; - calendar->set((UCalendarDateFields)field, value); + calendar->set(static_cast(field), value); //try { calendar->getTime(status); // Force time computation // We expect an exception to be thrown. If we fall through @@ -1914,7 +1914,7 @@ CalendarRegressionTest::Test4166109() errln("get(D_O_M) failed"); for(int32_t firstInWeek = UCAL_SUNDAY; firstInWeek <= UCAL_SATURDAY; firstInWeek++) { - calendar->setFirstDayOfWeek((UCalendarDaysOfWeek)firstInWeek); + calendar->setFirstDayOfWeek(static_cast(firstInWeek)); int32_t returned = calendar->getActualMaximum(field, status); int32_t expected = (31 + ((firstInMonth - firstInWeek + 7)% 7) + 6) / 7; @@ -1998,7 +1998,7 @@ CalendarRegressionTest::Test4167060() errln("getTime() failed"); int32_t newYear = calendar->get(field, status); if(U_FAILURE(status)) - errln(UnicodeString("get(") + (int32_t)field + ") failed"); + errln(UnicodeString("get(") + static_cast(field) + ") failed"); calendar->setTime(dateBefore, status); // restore calendar for next use if(U_FAILURE(status)) errln("setTime() failed"); @@ -2102,7 +2102,7 @@ void CalendarRegressionTest::TestJ81() { UDate days = ONE_DAY; days = cutover/days; logln(UnicodeString("Cutover: {") + - fmt.format(cutover, temp) + "}(epoch days-" + (int)days + ", jd" + (2440588 + days) +")"); + fmt.format(cutover, temp) + "}(epoch days-" + static_cast(days) + ", jd" + (2440588 + days) + ")"); // Check woy and doy handling. Reference data: /* w40 d274 Mon 1 Oct 1582 @@ -2155,14 +2155,14 @@ void CalendarRegressionTest::TestJ81() { break; } if (woy != DOY_DATA[i+1] || doy != DOY_DATA[i+2] || dow != DOY_DATA[i+3]) { - errln((UnicodeString)"Fail: expect woy=" + DOY_DATA[i+1] + + errln(UnicodeString("Fail: expect woy=") + DOY_DATA[i+1] + ", doy=" + DOY_DATA[i+2] + ", dow=" + DOY_DATA[i+3] + " on " + fmt.format(cal.getTime(status), temp.remove()) + " set(1582,OCTOBER, " + DOY_DATA[i] + ")"); logln(CalendarTest::calToStr(cal)); status = U_ZERO_ERROR; } else { - logln((UnicodeString)"PASS: expect woy=" + DOY_DATA[i+1] + + logln(UnicodeString("PASS: expect woy=") + DOY_DATA[i+1] + ", doy=" + DOY_DATA[i+2] + ", dow=" + DOY_DATA[i+3] + " on " + fmt.format(cal.getTime(status), temp.remove())); logln(CalendarTest::calToStr(cal)); @@ -2179,7 +2179,7 @@ void CalendarRegressionTest::TestJ81() { break; } if (dom != DOY_DATA[i]) { - errln((UnicodeString)"Fail: set woy=" + DOY_DATA[i+1] + + errln(UnicodeString("Fail: set woy=") + DOY_DATA[i+1] + " dow=" + DOY_DATA[i+3] + " => " + fmt.format(cal.getTime(status), temp.remove()) + ", expected 1582 Oct " + DOY_DATA[i]); @@ -2197,7 +2197,7 @@ void CalendarRegressionTest::TestJ81() { break; } if (dom != DOY_DATA[i]) { - errln((UnicodeString)"Fail: set doy=" + DOY_DATA[i+2] + + errln(UnicodeString("Fail: set doy=") + DOY_DATA[i+2] + " => " + fmt.format(cal.getTime(status), temp.remove()) + ", expected 1582 Oct " + DOY_DATA[i]); @@ -2236,11 +2236,11 @@ void CalendarRegressionTest::TestJ81() { // Now run the tests for (i=0; i(action + 1)) { if (!(DATA[i].actionMask & action)) { continue; } - for (Sign sign=PLUS; sign<=MINUS; sign=(Sign)(sign+1)) { + for (Sign sign = PLUS; sign <= MINUS; sign = static_cast(sign + 1)) { if (!(DATA[i].signMask & sign)) { continue; } @@ -2252,7 +2252,7 @@ void CalendarRegressionTest::TestJ81() { (sign==PLUS ? DATA[i].after : DATA[i].before); cal.setTime(date, status); if (U_FAILURE(status)) { - errln((UnicodeString)"FAIL: setTime returned error code " + u_errorName(status)); + errln(UnicodeString("FAIL: setTime returned error code ") + u_errorName(status)); continue; } if (action == ADD) { @@ -2261,18 +2261,18 @@ void CalendarRegressionTest::TestJ81() { cal.roll(DATA[i].field, amount, status); } if (U_FAILURE(status)) { - errln((UnicodeString)"FAIL: " + + errln(UnicodeString("FAIL: ") + (action==ADD?"add ":"roll ") + FIELD_NAME[DATA[i].field] + " returned error code " + u_errorName(status)); continue; } UDate result = cal.getTime(status); if (U_FAILURE(status)) { - errln((UnicodeString)"FAIL: getTime returned error code " + u_errorName(status)); + errln(UnicodeString("FAIL: getTime returned error code ") + u_errorName(status)); continue; } if (result == expected) { - logln((UnicodeString)"Ok: {" + + logln(UnicodeString("Ok: {") + fmt.format(date, temp.remove()) + "}(" + date/ONE_DAY + (action==ADD?") add ":") roll ") + @@ -2280,7 +2280,7 @@ void CalendarRegressionTest::TestJ81() { fmt.format(result, temp2.remove()) + "}(" + result/ONE_DAY + ")"); } else { - errln((UnicodeString)"FAIL: {" + + errln(UnicodeString("FAIL: {") + fmt.format(date, temp.remove()) + "}(" + date/ONE_DAY + (action==ADD?") add ":") roll ") + @@ -2463,7 +2463,7 @@ static const CoptEthCalTestItem coptEthCalTestItems[] = { { 1724, 12, 1, UCAL_DATE, +8, 1725, 0, 4 }, { 1723, 12, 1, UCAL_DATE, +8, 1724, 0, 3 }, // 1723 is a leap year { 1724, 0, 1, UCAL_DATE, -1, 1723, 12, 6 }, // 1723 is a leap year - { 0, 0, 0, (UCalendarDateFields)0, 0, 0, 0, 0 } // terminator + { 0, 0, 0, static_cast(0), 0, 0, 0, 0 } // terminator }; typedef struct { @@ -2484,7 +2484,7 @@ void CalendarRegressionTest::TestT6745() UErrorCode status = U_ZERO_ERROR; Calendar *cal = Calendar::createInstance(Locale(testLocalePtr->locale), status); if ( U_FAILURE(status) ) { - dataerrln((UnicodeString)"FAIL: Calendar::createInstance, locale " + testLocalePtr->locale + ", status " + u_errorName(status)); + dataerrln(UnicodeString("FAIL: Calendar::createInstance, locale ") + testLocalePtr->locale + ", status " + u_errorName(status)); continue; } const CoptEthCalTestItem * testItemPtr; @@ -2493,7 +2493,7 @@ void CalendarRegressionTest::TestT6745() cal->set( testItemPtr->startYear + testLocalePtr->yearOffset, testItemPtr->startMonth, testItemPtr->startDay, 9, 0 ); cal->add( testItemPtr->fieldToChange, testItemPtr->fieldDelta, status ); if ( U_FAILURE(status) ) { - errln((UnicodeString)"FAIL: Calendar::add, locale " + testLocalePtr->locale + ", field/delta " + + errln(UnicodeString("FAIL: Calendar::add, locale ") + testLocalePtr->locale + ", field/delta " + testItemPtr->fieldToChange + "/" + testItemPtr->fieldDelta + ", status " + u_errorName(status)); continue; } @@ -2502,7 +2502,7 @@ void CalendarRegressionTest::TestT6745() int32_t month = cal->get(UCAL_MONTH, status); int32_t day = cal->get(UCAL_DATE, status); if ( U_FAILURE(status) || year != endYear || month != testItemPtr->endMonth || day != testItemPtr->endDay ) { - errln((UnicodeString)"ERROR: Calendar::add, locale " + testLocalePtr->locale + ", field/delta " + + errln(UnicodeString("ERROR: Calendar::add, locale ") + testLocalePtr->locale + ", field/delta " + testItemPtr->fieldToChange + "/" + testItemPtr->fieldDelta + ", status " + u_errorName(status) + ", expected " + endYear + "/" + testItemPtr->endMonth + "/" + testItemPtr->endDay + ", got " + year + "/" + month + "/" + day ); @@ -2541,9 +2541,9 @@ void CalendarRegressionTest::TestLeapFieldDifference() { return; } if (d == 0) { - logln((UnicodeString)"Ok: 2004/Feb/29 - 2000/Feb/29 = " + y + " years, " + d + " days"); + logln(UnicodeString("Ok: 2004/Feb/29 - 2000/Feb/29 = ") + y + " years, " + d + " days"); } else { - errln((UnicodeString)"FAIL: 2004/Feb/29 - 2000/Feb/29 = " + y + " years, " + d + " days"); + errln(UnicodeString("FAIL: 2004/Feb/29 - 2000/Feb/29 = ") + y + " years, " + d + " days"); } cal->setTime(date2004, ec); y = cal->fieldDifference(date2000, UCAL_YEAR, ec); @@ -2554,9 +2554,9 @@ void CalendarRegressionTest::TestLeapFieldDifference() { return; } if (d == 0) { - logln((UnicodeString)"Ok: 2000/Feb/29 - 2004/Feb/29 = " + y + " years, " + d + " days"); + logln(UnicodeString("Ok: 2000/Feb/29 - 2004/Feb/29 = ") + y + " years, " + d + " days"); } else { - errln((UnicodeString)"FAIL: 2000/Feb/29 - 2004/Feb/29 = " + y + " years, " + d + " days"); + errln(UnicodeString("FAIL: 2000/Feb/29 - 2004/Feb/29 = ") + y + " years, " + d + " days"); } // Test large difference cal->set(2001, UCAL_APRIL, 5); // 2452005 @@ -2577,9 +2577,9 @@ void CalendarRegressionTest::TestLeapFieldDifference() { return; } if (d == -d2 && d == 13359) { - logln((UnicodeString)"Ok: large field difference symmetrical " + d); + logln(UnicodeString("Ok: large field difference symmetrical ") + d); } else { - logln((UnicodeString)"FAIL: large field difference incorrect " + d + ", " + d2 + + logln(UnicodeString("FAIL: large field difference incorrect ") + d + ", " + d2 + ", expect +/- 13359"); } delete cal; @@ -2611,7 +2611,7 @@ void CalendarRegressionTest::TestWeekShift() { dataerrln("Fail GregorianCalendar: %s", u_errorName(ec)); return; } - cal.setTime(UDate(997257600000.0), ec); // Wed Aug 08 01:00:00 PDT 2001 + cal.setTime(static_cast(997257600000.0), ec); // Wed Aug 08 01:00:00 PDT 2001 // In pass one, change the first day of week so that the weeks // shift in August 2001. In pass two, change the minimal days // in the first week so that the weeks shift in August 2001. @@ -2666,10 +2666,10 @@ void CalendarRegressionTest::TestWeekShift() { // logln(time1); } if (woy1 == woy2 && wom1 == wom2) { - logln((UnicodeString)"Ok: WEEK_OF_YEAR: " + woy1 + + logln(UnicodeString("Ok: WEEK_OF_YEAR: ") + woy1 + ", WEEK_OF_MONTH: " + wom1); } else { - errln((UnicodeString)"FAIL: WEEK_OF_YEAR: " + woy1 + " => " + woy2 + + errln(UnicodeString("FAIL: WEEK_OF_YEAR: ") + woy1 + " => " + woy2 + ", WEEK_OF_MONTH: " + wom1 + " => " + wom2 + " after week shift"); } @@ -2787,8 +2787,8 @@ void CalendarRegressionTest::TestDeprecates() c1->setTime(c2->getTime(status),status); // *c1 = *c2; - c1->roll(Calendar::HOUR,(int32_t)3,status); - c2->roll(UCAL_HOUR,(int32_t)3,status); + c1->roll(Calendar::HOUR, static_cast(3), status); + c2->roll(UCAL_HOUR, static_cast(3), status); if(U_FAILURE(status)) { errln("Error code when trying to roll"); @@ -2797,8 +2797,8 @@ void CalendarRegressionTest::TestDeprecates() } c1->setTime(c2->getTime(status),status); - c1->roll(Calendar::HOUR,(UBool)false,status); - c2->roll(UCAL_HOUR,(UBool)false,status); + c1->roll(Calendar::HOUR, static_cast(false), status); + c2->roll(UCAL_HOUR, static_cast(false), status); if(U_FAILURE(status)) { errln("Error code when trying to roll(UBool)"); @@ -2823,13 +2823,13 @@ void CalendarRegressionTest::TestDeprecates() c1->setTime(c2->getTime(status),status); //*c1 = *c2; - c1->add(Calendar::HOUR,(int32_t)1,status); + c1->add(Calendar::HOUR, static_cast(1), status); if(U_FAILURE(status)) { errln("Error code when trying to add Calendar::HOUR - %s", u_errorName(status)); } - c2->add(UCAL_HOUR,(int32_t)1,status); + c2->add(UCAL_HOUR, static_cast(1), status); if(U_FAILURE(status)) { errln("Error code when trying to add - UCAL_HOUR %s", u_errorName(status)); @@ -2854,8 +2854,8 @@ void CalendarRegressionTest::TestDeprecates() c1->setTime(c2->getTime(status),status); //*c1 = *c2; - c1->add(Calendar::YEAR,(int32_t)9,status); - c2->add(UCAL_YEAR,(int32_t)9,status); + c1->add(Calendar::YEAR, static_cast(9), status); + c2->add(UCAL_YEAR, static_cast(9), status); if(U_FAILURE(status)) { errln("Error code when trying to add YEARs"); @@ -2895,7 +2895,7 @@ void CalendarRegressionTest::TestT8057() { t = cal->getTime(status); if (U_SUCCESS(status)) { if (t != expected) { - dataerrln((UnicodeString)"FAIL: wrong date after add: expected=" + expected + " returned=" + t); + dataerrln(UnicodeString("FAIL: wrong date after add: expected=") + expected + " returned=" + t); } } else { errln("FAIL: error while adding one year"); @@ -2941,7 +2941,7 @@ void CalendarRegressionTest::TestT8596() { } if (maxWeeks != 53) { - errln((UnicodeString)"FAIL: Max week in 2009 in ISO calendar is 53, but got " + maxWeeks); + errln(UnicodeString("FAIL: Max week in 2009 in ISO calendar is 53, but got ") + maxWeeks); } delete gc; @@ -3237,7 +3237,7 @@ void CalendarRegressionTest::TestWeekOfYear13548() { int32_t resultYear = cal->get(UCAL_YEAR, status); failure(status, "get(UCAL_YEAR, status)"); if (year != resultYear) { - errln((UnicodeString)"Fail: Expected year=" + year + ", actual=" + resultYear); + errln(UnicodeString("Fail: Expected year=") + year + ", actual=" + resultYear); } } @@ -3273,7 +3273,7 @@ void CalendarRegressionTest::TestRespectUExtensionFw() { // ICU-22226 UCalendarDaysOfWeek actual = cal->getFirstDayOfWeek(status); failure(status, "Calendar::getFirstDayOfWeek(status)"); - assertEquals((UnicodeString)"Calendar.getFirstDayOfWeek() ignores the 'fw' extension u in '" + assertEquals(UnicodeString("Calendar.getFirstDayOfWeek() ignores the 'fw' extension u in '") + localeId + "' locale", expected, actual); } } diff --git a/icu4c/source/test/intltest/caltest.cpp b/icu4c/source/test/intltest/caltest.cpp index 8f59e4301e04..95dcc4799d07 100644 --- a/icu4c/source/test/intltest/caltest.cpp +++ b/icu4c/source/test/intltest/caltest.cpp @@ -68,7 +68,7 @@ UnicodeString CalendarTest::calToStr(const Calendar & cal) int i; UDate d; for(i = 0;i(i)) + "=" + cal.get(static_cast(i), status) + UnicodeString(" ")); } out += "[" + UnicodeString(cal.getType()) + "]"; @@ -245,7 +245,7 @@ UnicodeString CalendarTest::fieldName(UCalendarDateFields f) { FIELD_NAME_STR( UCAL_MILLISECONDS_IN_DAY ); #undef FIELD_NAME_STR default: - return UnicodeString("") + ((int32_t)f); + return UnicodeString("") + static_cast(f); } } @@ -284,11 +284,11 @@ CalendarTest::TestGenericAPI() cal->after(*cal2, status) || U_FAILURE(status)) errln("FAIL: equals/before/after failed"); - logln(UnicodeString("cal=") +cal->getTime(status) + UnicodeString(calToStr(*cal))); - logln(UnicodeString("cal2=") +cal2->getTime(status) + UnicodeString(calToStr(*cal2))); + logln(UnicodeString("cal=") + cal->getTime(status) + (calToStr(*cal))); + logln(UnicodeString("cal2=") + cal2->getTime(status) + (calToStr(*cal2))); logln("cal2->setTime(when+1000)"); cal2->setTime(when + 1000, status); - logln(UnicodeString("cal2=") +cal2->getTime(status) + UnicodeString(calToStr(*cal2))); + logln(UnicodeString("cal2=") + cal2->getTime(status) + (calToStr(*cal2))); if (failure(status, "Calendar::setTime")) return; if (cal->equals(*cal2, status) || @@ -297,10 +297,10 @@ CalendarTest::TestGenericAPI() U_FAILURE(status)) errln("FAIL: equals/before/after failed after setTime(+1000)"); logln("cal->roll(UCAL_SECOND)"); - cal->roll(UCAL_SECOND, (UBool) true, status); - logln(UnicodeString("cal=") +cal->getTime(status) + UnicodeString(calToStr(*cal))); - cal->roll(UCAL_SECOND, (int32_t)0, status); - logln(UnicodeString("cal=") +cal->getTime(status) + UnicodeString(calToStr(*cal))); + cal->roll(UCAL_SECOND, static_cast(true), status); + logln(UnicodeString("cal=") + cal->getTime(status) + (calToStr(*cal))); + cal->roll(UCAL_SECOND, static_cast(0), status); + logln(UnicodeString("cal=") + cal->getTime(status) + (calToStr(*cal))); if (failure(status, "Calendar::roll")) return; if (!(eq=cal->equals(*cal2, status)) || @@ -311,12 +311,12 @@ CalendarTest::TestGenericAPI() eq?'T':'F', b4?'T':'F', af?'T':'F'); - logln(UnicodeString("cal=") +cal->getTime(status) + UnicodeString(calToStr(*cal))); - logln(UnicodeString("cal2=") +cal2->getTime(status) + UnicodeString(calToStr(*cal2))); + logln(UnicodeString("cal=") + cal->getTime(status) + (calToStr(*cal))); + logln(UnicodeString("cal2=") + cal2->getTime(status) + (calToStr(*cal2))); } // Roll back to January - cal->roll(UCAL_MONTH, (int32_t)(1 + UCAL_DECEMBER - cal->get(UCAL_MONTH, status)), status); + cal->roll(UCAL_MONTH, static_cast(1 + UCAL_DECEMBER - cal->get(UCAL_MONTH, status)), status); if (failure(status, "Calendar::roll")) return; if (cal->equals(*cal2, status) || cal2->before(*cal, status) || @@ -339,7 +339,7 @@ CalendarTest::TestGenericAPI() for (i=UCAL_SUNDAY; i<=UCAL_SATURDAY; ++i) { - cal->setFirstDayOfWeek((UCalendarDaysOfWeek)i); + cal->setFirstDayOfWeek(static_cast(i)); if (cal->getFirstDayOfWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); UErrorCode aStatus = U_ZERO_ERROR; if (cal->getFirstDayOfWeek(aStatus) != i || U_FAILURE(aStatus)) errln("FAIL: getFirstDayOfWeek(status) failed"); @@ -347,17 +347,17 @@ CalendarTest::TestGenericAPI() for (i=1; i<=7; ++i) { - cal->setMinimalDaysInFirstWeek((uint8_t)i); + cal->setMinimalDaysInFirstWeek(static_cast(i)); if (cal->getMinimalDaysInFirstWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); } for (i=0; igetMinimum((UCalendarDateFields)i) > cal->getGreatestMinimum((UCalendarDateFields)i)) + if (cal->getMinimum(static_cast(i)) > cal->getGreatestMinimum(static_cast(i))) errln(UnicodeString("FAIL: getMinimum larger than getGreatestMinimum for field ") + i); - if (cal->getLeastMaximum((UCalendarDateFields)i) > cal->getMaximum((UCalendarDateFields)i)) + if (cal->getLeastMaximum(static_cast(i)) > cal->getMaximum(static_cast(i))) errln(UnicodeString("FAIL: getLeastMaximum larger than getMaximum for field ") + i); - if (cal->getMinimum((UCalendarDateFields)i) >= cal->getMaximum((UCalendarDateFields)i)) + if (cal->getMinimum(static_cast(i)) >= cal->getMaximum(static_cast(i))) errln(UnicodeString("FAIL: getMinimum not less than getMaximum for field ") + i); } @@ -385,13 +385,13 @@ CalendarTest::TestGenericAPI() case UCAL_YEAR: case UCAL_MONTH: case UCAL_DATE: case UCAL_HOUR_OF_DAY: case UCAL_MINUTE: case UCAL_SECOND: case UCAL_EXTENDED_YEAR: - if (!cal->isSet((UCalendarDateFields)i)) errln("FAIL: Calendar::isSet F, should be T " + fieldName((UCalendarDateFields)i)); + if (!cal->isSet(static_cast(i))) errln("FAIL: Calendar::isSet F, should be T " + fieldName(static_cast(i))); break; default: - if (cal->isSet((UCalendarDateFields)i)) errln("FAIL: Calendar::isSet = T, should be F " + fieldName((UCalendarDateFields)i)); + if (cal->isSet(static_cast(i))) errln("FAIL: Calendar::isSet = T, should be F " + fieldName(static_cast(i))); } - cal->clear((UCalendarDateFields)i); - if (cal->isSet((UCalendarDateFields)i)) errln("FAIL: Calendar::clear/isSet failed " + fieldName((UCalendarDateFields)i)); + cal->clear(static_cast(i)); + if (cal->isSet(static_cast(i))) errln("FAIL: Calendar::clear/isSet failed " + fieldName(static_cast(i))); } if(cal->getActualMinimum(Calendar::SECOND, status) != 0){ @@ -399,7 +399,7 @@ CalendarTest::TestGenericAPI() } Calendar *cal3 = Calendar::createInstance(status); - cal3->roll(Calendar::SECOND, (int32_t)0, status); + cal3->roll(Calendar::SECOND, static_cast(0), status); if (failure(status, "Calendar::roll(EDateFields, int32_t, UErrorCode)")) return; delete cal; @@ -454,9 +454,9 @@ CalendarTest::TestGenericAPI() gc = new GregorianCalendar(1998, 10, 14, 21, 43, status); if (gc->getTime(status) != (d =date(98, 10, 14, 21, 43) )|| U_FAILURE(status)) - errln("FAIL: new GregorianCalendar(ymdhm) failed with " + UnicodeString(u_errorName(status)) + ", cal=" + gc->getTime(status) + UnicodeString(calToStr(*gc)) + ", d=" + d); + errln("FAIL: new GregorianCalendar(ymdhm) failed with " + UnicodeString(u_errorName(status)) + ", cal=" + gc->getTime(status) + (calToStr(*gc)) + ", d=" + d); else - logln(UnicodeString("GOOD: cal=") +gc->getTime(status) + UnicodeString(calToStr(*gc)) + ", d=" + d); + logln(UnicodeString("GOOD: cal=") + gc->getTime(status) + calToStr(*gc) + ", d=" + d); delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55, status); @@ -475,7 +475,7 @@ CalendarTest::TestGenericAPI() if (failure(status, "Calendar::createInstance #6")) { return; }else { - cal->roll(UCAL_HOUR, (int32_t)100, status); + cal->roll(UCAL_HOUR, static_cast(100), status); cal->clear(UCAL_HOUR); #if !UCONFIG_NO_SERVICE URegistryKey key = cal->registerFactory(nullptr, status); @@ -489,7 +489,7 @@ CalendarTest::TestGenericAPI() if (failure(status, "Calendar::createInstance #7")) { return; } else { - cal->roll(Calendar::MONTH, (int32_t)100, status); + cal->roll(Calendar::MONTH, static_cast(100), status); } LocalPointer values( @@ -588,17 +588,17 @@ void CalendarTest::dowTest(UBool lenient) cal->set(1997, UCAL_AUGUST, 12); cal->getTime(status); if (U_FAILURE(status)) { errln("Calendar::getTime failed"); return; } - logln((lenient?UnicodeString("LENIENT0: "):UnicodeString("nonlenient0: ")) + UnicodeString(calToStr(*cal))); + logln((lenient ? UnicodeString("LENIENT0: ") : UnicodeString("nonlenient0: ")) + (calToStr(*cal))); cal->setLenient(lenient); logln("cal - Dec 1, 1996\n"); cal->set(1996, UCAL_DECEMBER, 1); - logln((lenient?UnicodeString("LENIENT: "):UnicodeString("nonlenient: ")) + UnicodeString(calToStr(*cal))); + logln((lenient ? UnicodeString("LENIENT: ") : UnicodeString("nonlenient: ")) + (calToStr(*cal))); int32_t dow = cal->get(UCAL_DAY_OF_WEEK, status); if (U_FAILURE(status)) { errln("Calendar::get failed [%s]", u_errorName(status)); return; } int32_t min = cal->getMinimum(UCAL_DAY_OF_WEEK); int32_t max = cal->getMaximum(UCAL_DAY_OF_WEEK); if (dow < min || - dow > max) errln(UnicodeString("FAIL: Day of week ") + (int32_t)dow + " out of range"); + dow > max) errln(UnicodeString("FAIL: Day of week ") + dow + " out of range"); if (dow != UCAL_SUNDAY) errln("FAIL: Day of week should be SUNDAY[%d] not %d", UCAL_SUNDAY, dow); if (min != UCAL_SUNDAY || max != UCAL_SATURDAY) errln("FAIL: Min/max bad"); @@ -780,8 +780,8 @@ CalendarTest::verify765(const UnicodeString& msg, Calendar* c, int32_t year, int if (U_FAILURE(status)) { errln("Calendar::getTime failed"); return; } } else { - errln("FAIL: " + msg + dateToString(c->getTime(status), str) + "; expected " + (int32_t)year + "/" + (int32_t)(month + 1) + "/" + (int32_t)day + - "; got " + (int32_t)y + "/" + (int32_t)(m + 1) + "/" + (int32_t)d + " for Locale: " + c->getLocaleID(ULOC_ACTUAL_LOCALE,status)); + errln("FAIL: " + msg + dateToString(c->getTime(status), str) + "; expected " + year + "/" + static_cast(month + 1) + "/" + day + + "; got " + y + "/" + static_cast(m + 1) + "/" + d + " for Locale: " + c->getLocaleID(ULOC_ACTUAL_LOCALE, status)); if (U_FAILURE(status)) { errln("Calendar::getTime failed"); return; } } } @@ -827,11 +827,11 @@ CalendarTest::test4064654(int32_t yr, int32_t mo, int32_t dt, int32_t hr, int32_ if (U_FAILURE(status)) { errln("Calendar::createInstance failed"); return; } cal->setTime(date, status); if (U_FAILURE(status)) { errln("Calendar::setTime failed"); return; } - int32_t offset = cal->getTimeZone().getOffset((uint8_t)cal->get(UCAL_ERA, status), + int32_t offset = cal->getTimeZone().getOffset(static_cast(cal->get(UCAL_ERA, status)), cal->get(UCAL_YEAR, status), cal->get(UCAL_MONTH, status), cal->get(UCAL_DATE, status), - (uint8_t)cal->get(UCAL_DAY_OF_WEEK, status), + static_cast(cal->get(UCAL_DAY_OF_WEEK, status)), cal->get(UCAL_MILLISECOND, status), status); if (U_FAILURE(status)) { errln("Calendar::get failed"); return; } logln("offset for " + dateToString(date, str) + "= " + (offset / 1000 / 60 / 60.0) + "hr"); @@ -998,7 +998,7 @@ CalendarTest::TestAddRollExtensive() } check520(temp, y, m, d, hr, min, sec, ms, e); - e = (UCalendarDateFields) ((int32_t) e + 1); + e = static_cast(static_cast(e) + 1); } logln("Testing GregorianCalendar roll..."); @@ -1011,20 +1011,20 @@ CalendarTest::TestAddRollExtensive() logln(calToStr(*temp) + UnicodeString(" " ) + fieldName(e) + UnicodeString("++") ); temp->roll(e, 1, status); if (U_FAILURE(status)) { - logln("caltest.cpp:%d e=%d, i=%d - roll(+) err %s\n", __LINE__, (int) e, (int) i, u_errorName(status)); + logln("caltest.cpp:%d e=%d, i=%d - roll(+) err %s\n", __LINE__, static_cast(e), static_cast(i), u_errorName(status)); logln(calToStr(*temp)); limit = i; status = U_ZERO_ERROR; } } for (i = 0; i < limit; i++) { - logln("caltest.cpp:%d e=%d, i=%d\n", __LINE__, (int) e, (int) i); + logln("caltest.cpp:%d e=%d, i=%d\n", __LINE__, static_cast(e), static_cast(i)); logln(calToStr(*temp) + UnicodeString(" " ) + fieldName(e) + UnicodeString("--") ); temp->roll(e, -1, status); if (U_FAILURE(status)) { errln(UnicodeString("GregorianCalendar::roll ") + CalendarTest::fieldName(e) + " count=" + UnicodeString('@'+i) + " by -1 failed with " + u_errorName(status) ); return; } } check520(temp, y, m, d, hr, min, sec, ms, e); - e = (UCalendarDateFields) ((int32_t) e + 1); + e = static_cast(static_cast(e) + 1); } delete temp; @@ -1046,7 +1046,7 @@ CalendarTest::check520(Calendar* c, c->get(UCAL_MINUTE, status) != min || c->get(UCAL_SECOND, status) != sec || c->get(UCAL_MILLISECOND, status) != ms) { - errln(UnicodeString("U_FAILURE for field ") + (int32_t)field + + errln(UnicodeString("U_FAILURE for field ") + static_cast(field) + ": Expected y/m/d h:m:s:ms of " + y + "/" + (m + 1) + "/" + d + " " + hr + ":" + min + ":" + sec + ":" + ms + @@ -1252,9 +1252,9 @@ UnicodeString CalendarTest::value(Calendar* calendar) { UErrorCode status = U_ZERO_ERROR; - return UnicodeString("") + (int32_t)calendar->get(UCAL_YEAR, status) + - "/" + (int32_t)calendar->get(UCAL_MONTH, status) + - "/" + (int32_t)calendar->get(UCAL_DATE, status) + + return UnicodeString("") + calendar->get(UCAL_YEAR, status) + + "/" + calendar->get(UCAL_MONTH, status) + + "/" + calendar->get(UCAL_DATE, status) + (U_FAILURE(status) ? " FAIL: Calendar::get failed" : ""); } @@ -1275,11 +1275,11 @@ CalendarTest::TestFields060() calendar = new GregorianCalendar(year, month, dDate, status); if (failure(status, "new GregorianCalendar", true)) return; for (int32_t i = 0; i < EXPECTED_FIELDS_length;) { - UCalendarDateFields field = (UCalendarDateFields)EXPECTED_FIELDS[i++]; + UCalendarDateFields field = static_cast(EXPECTED_FIELDS[i++]); int32_t expected = EXPECTED_FIELDS[i++]; if (calendar->get(field, status) != expected) { - errln(UnicodeString("Expected field ") + (int32_t)field + " to have value " + (int32_t)expected + - "; received " + (int32_t)calendar->get(field, status) + " instead"); + errln(UnicodeString("Expected field ") + static_cast(field) + " to have value " + expected + + "; received " + calendar->get(field, status) + " instead"); if (U_FAILURE(status)) { errln("Calendar::get failed"); return; } } } @@ -1295,7 +1295,7 @@ int32_t CalendarTest::EXPECTED_FIELDS[] = { UCAL_DAY_OF_YEAR, 295 }; -const int32_t CalendarTest::EXPECTED_FIELDS_length = (int32_t)(sizeof(CalendarTest::EXPECTED_FIELDS) / +const int32_t CalendarTest::EXPECTED_FIELDS_length = static_cast(sizeof(CalendarTest::EXPECTED_FIELDS) / sizeof(CalendarTest::EXPECTED_FIELDS[0])); // ------------------------------------- @@ -1327,9 +1327,9 @@ CalendarTest::TestEpochStartFields() c->setTime(d, status); if (U_FAILURE(status)) { errln("Calendar::setTime failed"); return; } for (int32_t i = 0; i < UCAL_ZONE_OFFSET;++i) { - if (c->get((UCalendarDateFields)i, status) != EPOCH_FIELDS[i]) + if (c->get(static_cast(i), status) != EPOCH_FIELDS[i]) dataerrln(UnicodeString("Expected field ") + i + " to have value " + EPOCH_FIELDS[i] + - "; saw " + c->get((UCalendarDateFields)i, status) + " instead"); + "; saw " + c->get(static_cast(i), status) + " instead"); if (U_FAILURE(status)) { errln("Calendar::get failed"); return; } } if (c->get(UCAL_ZONE_OFFSET, status) != z->getRawOffset()) @@ -1463,9 +1463,9 @@ void CalendarTest::yearAddTest(Calendar& cal, UErrorCode& status) { int32_t day2 = cal.get(UCAL_DATE, status); fmt.format(cal.getTime(status), str); if (y2 != (y+1) || mon2 != mon || day2 != day) { - str += (UnicodeString)", expected year " + + str += UnicodeString(", expected year ") + (y+1) + ", month " + (mon+1) + ", day " + day; - errln((UnicodeString)"FAIL: " + str); + errln(UnicodeString("FAIL: ") + str); logln( UnicodeString(" -> ") + CalendarTest::calToStr(cal) ); } else { logln(str); @@ -1481,9 +1481,9 @@ void CalendarTest::yearAddTest(Calendar& cal, UErrorCode& status) { int32_t dow2 = cal.get(UCAL_DOW_LOCAL, status); fmt.format(cal.getTime(status), str); if (ywy2 != (ywy+1) || woy2 != woy || dow2 != dow) { - str += (UnicodeString)", expected yearWOY " + + str += UnicodeString(", expected yearWOY ") + (ywy+1) + ", woy " + woy + ", dowLocal " + dow; - errln((UnicodeString)"FAIL: " + str); + errln(UnicodeString("FAIL: ") + str); logln( UnicodeString(" -> ") + CalendarTest::calToStr(cal) ); } else { logln(str); @@ -1521,9 +1521,9 @@ void CalendarTest::loop_addroll(Calendar *cal, /*SimpleDateFormat *sdf,*/ int ti for(i = 0; iclone(); - cal->roll(field,(int32_t)1,errorCode); + cal->roll(field, static_cast(1), errorCode); if (U_FAILURE(errorCode)) { errln("Error in roll"); delete calclone; return; } - calclone->roll(field2,(int32_t)1,errorCode); + calclone->roll(field2, static_cast(1), errorCode); if (U_FAILURE(errorCode)) { errln("Error in roll"); delete calclone; return; } if(cal->getTime(errorCode) != calclone->getTime(errorCode)) { delete calclone; @@ -1573,14 +1573,14 @@ CalendarTest::doYEAR_WOYLoop(Calendar *cal, SimpleDateFormat *sdf, tstres->set(UCAL_DOW_LOCAL, cal->get(UCAL_DOW_LOCAL, errorCode)); if(cal->get(UCAL_YEAR, errorCode) != tstres->get(UCAL_YEAR, errorCode)) { errln("FAIL: Different Year!"); - logln((UnicodeString)"Expected "+cal->get(UCAL_YEAR, errorCode)); - logln((UnicodeString)"Got "+tstres->get(UCAL_YEAR, errorCode)); + logln(UnicodeString("Expected ") + cal->get(UCAL_YEAR, errorCode)); + logln(UnicodeString("Got ") + tstres->get(UCAL_YEAR, errorCode)); return; } if(cal->get(UCAL_DAY_OF_YEAR, errorCode) != tstres->get(UCAL_DAY_OF_YEAR, errorCode)) { errln("FAIL: Different Day Of Year!"); - logln((UnicodeString)"Expected "+cal->get(UCAL_DAY_OF_YEAR, errorCode)); - logln((UnicodeString)"Got "+tstres->get(UCAL_DAY_OF_YEAR, errorCode)); + logln(UnicodeString("Expected ") + cal->get(UCAL_DAY_OF_YEAR, errorCode)); + logln(UnicodeString("Got ") + tstres->get(UCAL_DAY_OF_YEAR, errorCode)); return; } //logln(calToStr(*cal)); @@ -1675,7 +1675,7 @@ void CalendarTest::TestWOY() { SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy', WOY' w"), status); if (failure(status, "Cannot construct calendar/format", true)) return; - UCalendarDaysOfWeek fdw = (UCalendarDaysOfWeek) 0; + UCalendarDaysOfWeek fdw = static_cast(0); //for (int8_t pass=2; pass<=2; ++pass) { for (int8_t pass=1; pass<=2; ++pass) { @@ -1982,20 +1982,20 @@ void CalendarTest::TestJD() void CalendarTest::TestDebug() { for(int32_t t=0;t<=UDBG_ENUM_COUNT;t++) { - int32_t count = udbg_enumCount((UDebugEnumType)t); + int32_t count = udbg_enumCount(static_cast(t)); if(count == -1) { logln("enumCount(%d) returned -1", count); continue; } for(int32_t i=0;i<=count;i++) { if(t<=UDBG_HIGHEST_CONTIGUOUS_ENUM && i(t), i)) { + errln("FAIL: udbg_enumArrayValue(%d,%d) returned %d, expected %d", t, i, udbg_enumArrayValue(static_cast(t), i), i); } } else { logln("Testing count+1:"); } - const char *name = udbg_enumName((UDebugEnumType)t,i); + const char* name = udbg_enumName(static_cast(t), i); if(name==nullptr) { if(i==count || t>UDBG_HIGHEST_CONTIGUOUS_ENUM ) { logln(" null name - expected.\n"); @@ -2005,13 +2005,13 @@ void CalendarTest::TestDebug() name = "(null)"; } logln("udbg_enumArrayValue(%d,%d) = %s, returned %d", t, i, - name, udbg_enumArrayValue((UDebugEnumType)t,i)); - logln("udbg_enumString = " + udbg_enumString((UDebugEnumType)t,i)); + name, udbg_enumArrayValue(static_cast(t), i)); + logln("udbg_enumString = " + udbg_enumString(static_cast(t), i)); } - if(udbg_enumExpectedCount((UDebugEnumType)t) != count && t<=UDBG_HIGHEST_CONTIGUOUS_ENUM) { - errln("FAIL: udbg_enumExpectedCount(%d): %d, != UCAL_FIELD_COUNT=%d ", t, udbg_enumExpectedCount((UDebugEnumType)t), count); + if (udbg_enumExpectedCount(static_cast(t)) != count && t <= UDBG_HIGHEST_CONTIGUOUS_ENUM) { + errln("FAIL: udbg_enumExpectedCount(%d): %d, != UCAL_FIELD_COUNT=%d ", t, udbg_enumExpectedCount(static_cast(t)), count); } else { - logln("udbg_ucal_fieldCount: %d, UCAL_FIELD_COUNT=udbg_enumCount %d ", udbg_enumExpectedCount((UDebugEnumType)t), count); + logln("udbg_ucal_fieldCount: %d, UCAL_FIELD_COUNT=udbg_enumCount %d ", udbg_enumExpectedCount(static_cast(t)), count); } } } @@ -3483,7 +3483,7 @@ void CalendarTest::TestIslamicUmAlQura() { month = tstCal->get(UCAL_MONTH,status); year = tstCal->get(UCAL_YEAR,status); TEST_CHECK_STATUS; - tstCal->roll(UCAL_DAY_OF_MONTH, (UBool)true, status); + tstCal->roll(UCAL_DAY_OF_MONTH, static_cast(true), status); TEST_CHECK_STATUS; } @@ -3650,8 +3650,8 @@ void CalendarTest::TestWeekData() { // Weekdays and Weekends for (int32_t d = UCAL_SUNDAY; d <= UCAL_SATURDAY; d++) { status = U_ZERO_ERROR; - UCalendarWeekdayType wdt1 = cal1->getDayOfWeekType((UCalendarDaysOfWeek)d, status); - UCalendarWeekdayType wdt2 = cal2->getDayOfWeekType((UCalendarDaysOfWeek)d, status); + UCalendarWeekdayType wdt1 = cal1->getDayOfWeekType(static_cast(d), status); + UCalendarWeekdayType wdt2 = cal2->getDayOfWeekType(static_cast(d), status); TEST_CHECK_STATUS; TEST_ASSERT(wdt1 == wdt2); } diff --git a/icu4c/source/test/intltest/canittst.cpp b/icu4c/source/test/intltest/canittst.cpp index ebb457d3b309..2b1b58895a7e 100644 --- a/icu4c/source/test/intltest/canittst.cpp +++ b/icu4c/source/test/intltest/canittst.cpp @@ -93,7 +93,7 @@ void CanonicalIteratorTest::TestExhaustive() { s = i; characterTest(s, i, it); - s += (UChar32)0x0345; //"\\u0345"; + s += static_cast(0x0345); //"\\u0345"; characterTest(s, i, it); } } @@ -197,7 +197,7 @@ void CanonicalIteratorTest::characterTest(UnicodeString &s, UChar32 ch, Canonica } if (!gotSource || !gotDecomp || !gotComp) { - errln("FAIL CanonicalIterator: " + s + (int)ch); + errln("FAIL CanonicalIterator: " + s + static_cast(ch)); } } diff --git a/icu4c/source/test/intltest/citrtest.cpp b/icu4c/source/test/intltest/citrtest.cpp index 332d027242d0..706d065071c8 100644 --- a/icu4c/source/test/intltest/citrtest.cpp +++ b/icu4c/source/test/intltest/citrtest.cpp @@ -393,7 +393,7 @@ void CharIterTest::TestIteration() { if (iterText != text) errln("iter.getText() failed"); - if (iter.current() != text[(int32_t)5]) + if (iter.current() != text[static_cast(5)]) errln("Iterator didn't start out in the right place."); c = iter.first(); @@ -407,7 +407,7 @@ void CharIterTest::TestIteration() { if (c == CharacterIterator::DONE && i != text.length()) errln("Iterator reached end prematurely"); else if (c != text[i]) - errln((UnicodeString)"Character mismatch at position " + i + + errln(UnicodeString("Character mismatch at position ") + i + ", iterator has " + UCharToUnicodeString(c) + ", string has " + UCharToUnicodeString(text[i])); @@ -436,7 +436,7 @@ void CharIterTest::TestIteration() { if (c == CharacterIterator::DONE && i >= 0) errln("Iterator reached end prematurely"); else if (c != text[i]) - errln((UnicodeString)"Character mismatch at position " + i + + errln(UnicodeString("Character mismatch at position ") + i + ", iterator has " + UCharToUnicodeString(c) + ", string has " + UCharToUnicodeString(text[i])); @@ -462,10 +462,10 @@ void CharIterTest::TestIteration() { i = 0; c=iter.firstPostInc(); if(c != text[i]) - errln((UnicodeString)"firstPostInc failed. Expected->" + + errln(UnicodeString("firstPostInc failed. Expected->") + UCharToUnicodeString(text[i]) + " Got->" + UCharToUnicodeString(c)); if(iter.getIndex() != i+1) - errln((UnicodeString)"getIndex() after firstPostInc() failed"); + errln(UnicodeString("getIndex() after firstPostInc() failed")); iter.setToStart(); i=0; @@ -478,9 +478,9 @@ void CharIterTest::TestIteration() { c = iter.nextPostInc(); if(c != text[i]) - errln((UnicodeString)"Character mismatch at position " + i + - (UnicodeString)", iterator has " + UCharToUnicodeString(c) + - (UnicodeString)", string has " + UCharToUnicodeString(text[i])); + errln(UnicodeString("Character mismatch at position ") + i + + UnicodeString(", iterator has ") + UCharToUnicodeString(c) + + UnicodeString(", string has ") + UCharToUnicodeString(text[i])); i++; if(iter.getIndex() != i) @@ -498,7 +498,7 @@ void CharIterTest::TestIteration() { if (iter.startIndex() != 5 || iter.endIndex() != 15) errln("creation of a restricted-range iterator failed"); - if (iter.getIndex() != 10 || iter.current() != text[(int32_t)10]) + if (iter.getIndex() != 10 || iter.current() != text[static_cast(10)]) errln("starting the iterator in the middle didn't work"); c = iter.first(); @@ -509,7 +509,7 @@ void CharIterTest::TestIteration() { if (c == CharacterIterator::DONE && i != 15) errln("Iterator reached end prematurely"); else if (c != text[i]) - errln((UnicodeString)"Character mismatch at position " + i + + errln(UnicodeString("Character mismatch at position ") + i + ", iterator has " + UCharToUnicodeString(c) + ", string has " + UCharToUnicodeString(text[i])); @@ -534,7 +534,7 @@ void CharIterTest::TestIteration() { if (c == CharacterIterator::DONE && i >= 5) errln("Iterator reached end prematurely"); else if (c != text[i]) - errln((UnicodeString)"Character mismatch at position " + i + + errln(UnicodeString("Character mismatch at position ") + i + ", iterator has " + UCharToUnicodeString(c) + ", string has " + UCharToUnicodeString(text[i])); @@ -567,7 +567,7 @@ void CharIterTest::TestIterationUChar32() { if (iterText != text) errln("iter.getText() failed"); - if (iter.current32() != text[(int32_t)1]) + if (iter.current32() != text[static_cast(1)]) errln("Iterator didn't start out in the right place."); c=iter.setToStart(); @@ -641,9 +641,9 @@ void CharIterTest::TestIterationUChar32() { logln("Testing backward iteration..."); do { if (c == CharacterIterator::DONE && i >= 0) - errln((UnicodeString)"Iterator reached start prematurely for i=" + i); + errln(UnicodeString("Iterator reached start prematurely for i=") + i); else if(iter.hasPrevious() == false && i>0) - errln((UnicodeString)"Iterator reached start prematurely for i=" + i); + errln(UnicodeString("Iterator reached start prematurely for i=") + i); else if (c != text.char32At(i)) errln("Character mismatch at position %d, iterator has %X, string has %X", i, c, text.char32At(i)); @@ -674,7 +674,7 @@ void CharIterTest::TestIterationUChar32() { if(c != text.char32At(i)) errln("first32PostInc failed. Expected->%X Got->%X", text.char32At(i), c); if(iter.getIndex() != U16_LENGTH(c) + i) - errln((UnicodeString)"getIndex() after first32PostInc() failed"); + errln(UnicodeString("getIndex() after first32PostInc() failed")); iter.setToStart(); i=0; @@ -820,14 +820,14 @@ void CharIterTest::TestUCharIterator(UCharIterator *iter, CharacterIterator &ci, case '2': h=h2=false; - c=(UChar32)iter->move(iter, 2, UITER_CURRENT); - c2=(UChar32)ci.move(2, CharacterIterator::kCurrent); + c = static_cast(iter->move(iter, 2, UITER_CURRENT)); + c2 = static_cast(ci.move(2, CharacterIterator::kCurrent)); break; case '8': h=h2=false; - c=(UChar32)iter->move(iter, -2, UITER_CURRENT); - c2=(UChar32)ci.move(-2, CharacterIterator::kCurrent); + c = static_cast(iter->move(iter, -2, UITER_CURRENT)); + c2 = static_cast(ci.move(-2, CharacterIterator::kCurrent)); break; case 0: @@ -839,7 +839,7 @@ void CharIterTest::TestUCharIterator(UCharIterator *iter, CharacterIterator &ci, // compare results if(c2==0xffff) { - c2=(UChar32)-1; + c2 = static_cast(-1); } if(c!=c2 || h!=h2 || ci.getIndex()!=iter->getIndex(iter, UITER_CURRENT)) { errln("error: UCharIterator(%s) misbehaving at \"%s\"[%d]='%c'", which, moves, m, moves[m]); @@ -918,34 +918,34 @@ void CharIterTest::TestUCharIterator() { } - if(cIter.getIndex(&cIter, (enum UCharIteratorOrigin)-1) != -1) + if (cIter.getIndex(&cIter, static_cast(-1)) != -1) { errln("error: UCharIterator(char iter).getIndex did not return error value"); } - if(cIter.move(&cIter, 0, (enum UCharIteratorOrigin)-1) != -1) + if (cIter.move(&cIter, 0, static_cast(-1)) != -1) { errln("error: UCharIterator(char iter).move did not return error value"); } - if(rIter.getIndex(&rIter, (enum UCharIteratorOrigin)-1) != -1) + if (rIter.getIndex(&rIter, static_cast(-1)) != -1) { errln("error: UCharIterator(repl iter).getIndex did not return error value"); } - if(rIter.move(&rIter, 0, (enum UCharIteratorOrigin)-1) != -1) + if (rIter.move(&rIter, 0, static_cast(-1)) != -1) { errln("error: UCharIterator(repl iter).move did not return error value"); } - if(sIter.getIndex(&sIter, (enum UCharIteratorOrigin)-1) != -1) + if (sIter.getIndex(&sIter, static_cast(-1)) != -1) { errln("error: UCharIterator(string iter).getIndex did not return error value"); } - if(sIter.move(&sIter, 0, (enum UCharIteratorOrigin)-1) != -1) + if (sIter.move(&sIter, 0, static_cast(-1)) != -1) { errln("error: UCharIterator(string iter).move did not return error value"); } diff --git a/icu4c/source/test/intltest/collationtest.cpp b/icu4c/source/test/intltest/collationtest.cpp index 4439dc2f7e16..78b8c1a947bd 100644 --- a/icu4c/source/test/intltest/collationtest.cpp +++ b/icu4c/source/test/intltest/collationtest.cpp @@ -176,19 +176,19 @@ void CollationTest::TestMinMax() { rbc->internalGetCEs(UnicodeString(false, s, 2), ces, errorCode); errorCode.assertSuccess(); if(ces.size() != 2) { - errln("expected 2 CEs for , got %d", (int)ces.size()); + errln("expected 2 CEs for , got %d", static_cast(ces.size())); return; } int64_t ce = ces.elementAti(0); int64_t expected = Collation::makeCE(Collation::MERGE_SEPARATOR_PRIMARY); if(ce != expected) { - errln("CE(U+fffe)=%04lx != 02..", (long)ce); + errln("CE(U+fffe)=%04lx != 02..", static_cast(ce)); } ce = ces.elementAti(1); expected = Collation::makeCE(Collation::MAX_PRIMARY); if(ce != expected) { - errln("CE(U+ffff)=%04lx != max..", (long)ce); + errln("CE(U+ffff)=%04lx != max..", static_cast(ce)); } } @@ -261,18 +261,18 @@ void CollationTest::TestImplicits() { } if(ce == Collation::NO_CE || ce2 != Collation::NO_CE) { errln("%s: CollationIterator.nextCE(U+%04lx) did not yield exactly one CE", - setName, (long)c); + setName, static_cast(c)); continue; } if((ce & 0xffffffff) != Collation::COMMON_SEC_AND_TER_CE) { errln("%s: CollationIterator.nextCE(U+%04lx) has non-common sec/ter weights: %08lx", - setName, (long)c, (long)(ce & 0xffffffff)); + setName, static_cast(c), static_cast(ce & 0xffffffff)); continue; } - uint32_t primary = (uint32_t)(ce >> 32); + uint32_t primary = static_cast(ce >> 32); if(!(primary > prevPrimary) && inOrder.contains(c) && inOrder.contains(prev)) { errln("%s: CE(U+%04lx)=%04lx.. not greater than CE(U+%04lx)=%04lx..", - setName, (long)c, (long)primary, (long)prev, (long)prevPrimary); + setName, static_cast(c), static_cast(primary), static_cast(prev), static_cast(prevPrimary)); } prev = c; prevPrimary = primary; @@ -298,7 +298,7 @@ void CollationTest::TestNulTerminated() { return; } if(ce1 != ce2) { - errln("CollationIterator.nextCE(with length) != nextCE(NUL-terminated) at CE %d", (int)i); + errln("CollationIterator.nextCE(with length) != nextCE(NUL-terminated) at CE %d", static_cast(i)); break; } if(ce1 == Collation::NO_CE) { break; } @@ -332,7 +332,7 @@ void CollationTest::TestIllegalUTF8() { UCollationResult order = coll->compareUTF8(fffd, illegal, errorCode); if(order != UCOL_EQUAL) { errln("compareUTF8(pair %d: U+FFFD, illegal UTF-8)=%d != UCOL_EQUAL", - (int)i, order); + static_cast(i), order); } } } @@ -400,7 +400,7 @@ class CodePointIterator { UChar32 next() { return (pos < length) ? cp[pos++] : U_SENTINEL; } UChar32 previous() { return (pos > 0) ? cp[--pos] : U_SENTINEL; } int32_t getLength() const { return length; } - int getIndex() const { return (int)pos; } + int getIndex() const { return static_cast(pos); } private: const UChar32 *cp; int32_t length; @@ -417,7 +417,7 @@ void CollationTest::checkFCD(const char *name, UChar32 c2 = cpi.next(); if(c1 != c2) { errln("%s.nextCodePoint(to limit, 1st pass) = U+%04lx != U+%04lx at %d", - name, (long)c1, (long)c2, cpi.getIndex()); + name, static_cast(c1), static_cast(c2), cpi.getIndex()); return; } if(c1 < 0) { break; } @@ -429,7 +429,7 @@ void CollationTest::checkFCD(const char *name, UChar32 c2 = cpi.previous(); if(c1 != c2) { errln("%s.previousCodePoint() = U+%04lx != U+%04lx at %d", - name, (long)c1, (long)c2, cpi.getIndex()); + name, static_cast(c1), static_cast(c2), cpi.getIndex()); return; } } @@ -440,7 +440,7 @@ void CollationTest::checkFCD(const char *name, UChar32 c2 = cpi.next(); if(c1 != c2) { errln("%s.nextCodePoint(to limit again) = U+%04lx != U+%04lx at %d", - name, (long)c1, (long)c2, cpi.getIndex()); + name, static_cast(c1), static_cast(c2), cpi.getIndex()); return; } if(c1 < 0) { break; } @@ -452,7 +452,7 @@ void CollationTest::checkFCD(const char *name, UChar32 c2 = cpi.previous(); if(c1 != c2) { errln("%s.previousCodePoint(to start) = U+%04lx != U+%04lx at %d", - name, (long)c1, (long)c2, cpi.getIndex()); + name, static_cast(c1), static_cast(c2), cpi.getIndex()); return; } if(c1 < 0) { break; } @@ -526,7 +526,7 @@ void CollationTest::checkAllocWeights(CollationWeights &cw, int32_t someLength, int32_t minCount) { if(!cw.allocWeights(lowerLimit, upperLimit, n)) { errln("CollationWeights::allocWeights(%lx, %lx, %ld) = false", - (long)lowerLimit, (long)upperLimit, (long)n); + static_cast(lowerLimit), static_cast(upperLimit), static_cast(n)); return; } uint32_t previous = lowerLimit; @@ -536,14 +536,14 @@ void CollationTest::checkAllocWeights(CollationWeights &cw, if(w == 0xffffffff) { errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() " "returns only %ld weights", - (long)lowerLimit, (long)upperLimit, (long)n, (long)i); + static_cast(lowerLimit), static_cast(upperLimit), static_cast(n), static_cast(i)); return; } if(!(previous < w && w < upperLimit)) { errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() " "number %ld -> %lx not between %lx and %lx", - (long)lowerLimit, (long)upperLimit, (long)n, - (long)(i + 1), (long)w, (long)previous, (long)upperLimit); + static_cast(lowerLimit), static_cast(upperLimit), static_cast(n), + static_cast(i + 1), static_cast(w), static_cast(previous), static_cast(upperLimit)); return; } if(CollationWeights::lengthOfWeight(w) == someLength) { ++count; } @@ -551,8 +551,8 @@ void CollationTest::checkAllocWeights(CollationWeights &cw, if(count < minCount) { errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() " "returns only %ld < %ld weights of length %d", - (long)lowerLimit, (long)upperLimit, (long)n, - (long)count, (long)minCount, (int)someLength); + static_cast(lowerLimit), static_cast(upperLimit), static_cast(n), + static_cast(count), static_cast(minCount), static_cast(someLength)); } } @@ -696,8 +696,8 @@ UBool isValidCE(const CollationRootElements &re, const CollationData &data, } UBool isValidCE(const CollationRootElements &re, const CollationData &data, int64_t ce) { - uint32_t p = (uint32_t)(ce >> 32); - uint32_t secTer = (uint32_t)ce; + uint32_t p = static_cast(ce >> 32); + uint32_t secTer = static_cast(ce); return isValidCE(re, data, p, secTer >> 16, secTer & 0xffff); } @@ -707,7 +707,7 @@ class RootElementsIterator { : data(root), elements(root.rootElements), length(root.rootElementsLength), pri(0), secTer(0), - index((int32_t)elements[CollationRootElements::IX_FIRST_TERTIARY_INDEX]) {} + index(static_cast(elements[CollationRootElements::IX_FIRST_TERTIARY_INDEX])) {} UBool next() { if(index >= length) { return false; } @@ -720,7 +720,7 @@ class RootElementsIterator { } if((p & CollationRootElements::PRIMARY_STEP_MASK) != 0) { // End of a range, enumerate the primaries in the range. - int32_t step = (int32_t)p & CollationRootElements::PRIMARY_STEP_MASK; + int32_t step = static_cast(p) & CollationRootElements::PRIMARY_STEP_MASK; p &= 0xffffff00; if(pri == p) { // Finished the range, return the next CE after it. @@ -810,7 +810,7 @@ void CollationTest::TestRootElements() { // CollationRootElements CEs must have 0 case and quaternary bits. if((secTer & Collation::CASE_AND_QUATERNARY_MASK) != 0) { errln("CollationRootElements CE has non-zero case and/or quaternary bits: %08lx %08lx", - (long)pri, (long)secTer); + static_cast(pri), static_cast(secTer)); } uint32_t sec = secTer >> 16; uint32_t ter = secTer & Collation::ONLY_TERTIARY_MASK; @@ -821,7 +821,7 @@ void CollationTest::TestRootElements() { ctq |= 0x8000; } if(!isValidCE(rootElements, *root, pri, sec, ctq)) { - errln("invalid root CE %08lx %08lx", (long)pri, (long)secTer); + errln("invalid root CE %08lx %08lx", static_cast(pri), static_cast(secTer)); } else { if(pri != prevPri) { uint32_t newWeight = 0; @@ -831,21 +831,21 @@ void CollationTest::TestRootElements() { } else if(root->isCompressiblePrimary(prevPri)) { if(!cw1c.allocWeights(prevPri, pri, 1)) { errln("no primary/compressible tailoring gap between %08lx and %08lx", - (long)prevPri, (long)pri); + static_cast(prevPri), static_cast(pri)); } else { newWeight = cw1c.nextWeight(); } } else { if(!cw1u.allocWeights(prevPri, pri, 1)) { errln("no primary/uncompressible tailoring gap between %08lx and %08lx", - (long)prevPri, (long)pri); + static_cast(prevPri), static_cast(pri)); } else { newWeight = cw1u.nextWeight(); } } if(newWeight != 0 && !(prevPri < newWeight && newWeight < pri)) { errln("mis-allocated primary weight, should get %08lx < %08lx < %08lx", - (long)prevPri, (long)newWeight, (long)pri); + static_cast(prevPri), static_cast(newWeight), static_cast(pri)); } } else if(sec != prevSec) { uint32_t lowerLimit = @@ -856,7 +856,7 @@ void CollationTest::TestRootElements() { uint32_t newWeight = cw2.nextWeight(); if(!(prevSec < newWeight && newWeight < sec)) { errln("mis-allocated secondary weight, should get %04x < %04x < %04x", - (long)lowerLimit, (long)newWeight, (long)sec); + static_cast(lowerLimit), static_cast(newWeight), static_cast(sec)); } } } else if(ter != prevTer) { @@ -868,11 +868,11 @@ void CollationTest::TestRootElements() { uint32_t newWeight = cw3.nextWeight(); if(!(prevTer < newWeight && newWeight < ter)) { errln("mis-allocated secondary weight, should get %04x < %04x < %04x", - (long)lowerLimit, (long)newWeight, (long)ter); + static_cast(lowerLimit), static_cast(newWeight), static_cast(ter)); } } } else { - errln("duplicate root CE %08lx %08lx", (long)pri, (long)secTer); + errln("duplicate root CE %08lx %08lx", static_cast(pri), static_cast(secTer)); } } prevPri = pri; @@ -954,7 +954,7 @@ void CollationTest::TestTailoredElements() { int64_t ce = ces.elementAti(i); if(!isValidCE(rootElements, *root, ce)) { errln("invalid tailored CE %016llx at CE index %d from string:", - (long long)ce, (int)i); + static_cast(ce), static_cast(i)); infoln(prettify(s)); } } @@ -967,12 +967,12 @@ void CollationTest::TestTailoredElements() { UnicodeString CollationTest::printSortKey(const uint8_t *p, int32_t length) { UnicodeString s; for(int32_t i = 0; i < length; ++i) { - if(i > 0) { s.append((char16_t)0x20); } + if (i > 0) { s.append(static_cast(0x20)); } uint8_t b = p[i]; if(b == 0) { - s.append((char16_t)0x2e); // period + s.append(static_cast(0x2e)); // period } else if(b == 1) { - s.append((char16_t)0x7c); // vertical bar + s.append(static_cast(0x7c)); // vertical bar } else { appendHex(b, 2, s); } @@ -998,7 +998,7 @@ UBool CollationTest::readNonEmptyLine(UCHARBUF *f, IcuTestErrorCode &errorCode) // Strip trailing CR/LF, comments, and spaces. const char16_t *comment = u_memchr(line, 0x23, lineLength); // '#' if(comment != nullptr) { - lineLength = (int32_t)(comment - line); + lineLength = static_cast(comment - line); } else { while(lineLength > 0 && isCROrLF(line[lineLength - 1])) { --lineLength; } } @@ -1016,11 +1016,11 @@ void CollationTest::parseString(int32_t &start, UnicodeString &prefix, UnicodeSt int32_t length = fileLine.length(); int32_t i; for(i = start; i < length && !isSpace(fileLine[i]); ++i) {} - int32_t pipeIndex = fileLine.indexOf((char16_t)0x7c, start, i - start); // '|' + int32_t pipeIndex = fileLine.indexOf(static_cast(0x7c), start, i - start); // '|' if(pipeIndex >= 0) { prefix = fileLine.tempSubStringBetween(start, pipeIndex).unescape(); if(prefix.isEmpty()) { - errln("empty prefix on line %d", (int)fileLineNumber); + errln("empty prefix on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode = U_PARSE_ERROR; return; @@ -1031,7 +1031,7 @@ void CollationTest::parseString(int32_t &start, UnicodeString &prefix, UnicodeSt } s = fileLine.tempSubStringBetween(start, i).unescape(); if(s.isEmpty()) { - errln("empty string on line %d", (int)fileLineNumber); + errln("empty string on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode = U_PARSE_ERROR; return; @@ -1076,7 +1076,7 @@ Collation::Level CollationTest::parseRelationAndString(UnicodeString &s, IcuTest start = 0; } if(start == 0 || !isSpace(fileLine[start])) { - errln("no relation (= < <1 <2 (fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return Collation::NO_LEVEL; @@ -1085,13 +1085,13 @@ Collation::Level CollationTest::parseRelationAndString(UnicodeString &s, IcuTest UnicodeString prefix; parseString(start, prefix, s, errorCode); if(errorCode.isSuccess() && !prefix.isEmpty()) { - errln("prefix string not allowed for test string: on line %d", (int)fileLineNumber); + errln("prefix string not allowed for test string: on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return Collation::NO_LEVEL; } if(start < fileLine.length()) { - errln("unexpected line contents after test string on line %d", (int)fileLineNumber); + errln("unexpected line contents after test string on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return Collation::NO_LEVEL; @@ -1135,13 +1135,13 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { // Parse attributes even if the Collator could not be created, // in order to report syntax errors. int32_t start = skipSpaces(1); - int32_t equalPos = fileLine.indexOf((char16_t)0x3d); + int32_t equalPos = fileLine.indexOf(static_cast(0x3d)); if(equalPos < 0) { if(fileLine.compare(start, 7, UNICODE_STRING("reorder", 7)) == 0) { parseAndSetReorderCodes(start + 7, errorCode); return; } - errln("missing '=' on line %d", (int)fileLineNumber); + errln("missing '=' on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return; @@ -1160,7 +1160,7 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { } else if(valueString == UNICODE_STRING("currency", 8)) { max = UCOL_REORDER_CODE_CURRENCY; } else { - errln("invalid attribute value name on line %d", (int)fileLineNumber); + errln("invalid attribute value name on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return; @@ -1169,7 +1169,7 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { coll->setMaxVariable(max, errorCode); if(errorCode.isFailure()) { errln("setMaxVariable() failed on line %d: %s", - (int)fileLineNumber, errorCode.errorName()); + static_cast(fileLineNumber), errorCode.errorName()); infoln(fileLine); return; } @@ -1181,7 +1181,7 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { UColAttribute attr; for(int32_t i = 0;; ++i) { if(i == UPRV_LENGTHOF(attributes)) { - errln("invalid attribute name on line %d", (int)fileLineNumber); + errln("invalid attribute name on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return; @@ -1195,7 +1195,7 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { UColAttributeValue value; for(int32_t i = 0;; ++i) { if(i == UPRV_LENGTHOF(attributeValues)) { - errln("invalid attribute value name on line %d", (int)fileLineNumber); + errln("invalid attribute value name on line %d", static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return; @@ -1210,7 +1210,7 @@ void CollationTest::parseAndSetAttribute(IcuTestErrorCode &errorCode) { coll->setAttribute(attr, value, errorCode); if(errorCode.isFailure()) { errln("illegal attribute=value combination on line %d: %s", - (int)fileLineNumber, errorCode.errorName()); + static_cast(fileLineNumber), errorCode.errorName()); infoln(fileLine); return; } @@ -1231,7 +1231,7 @@ void CollationTest::parseAndSetReorderCodes(int32_t start, IcuTestErrorCode &err if(uprv_stricmp(name.data(), "default") == 0) { code = UCOL_REORDER_CODE_DEFAULT; // -1 } else { - errln("invalid reorder code '%s' on line %d", name.data(), (int)fileLineNumber); + errln("invalid reorder code '%s' on line %d", name.data(), static_cast(fileLineNumber)); infoln(fileLine); errorCode.set(U_PARSE_ERROR); return; @@ -1244,7 +1244,7 @@ void CollationTest::parseAndSetReorderCodes(int32_t start, IcuTestErrorCode &err coll->setReorderCodes(reorderCodes.getBuffer(), reorderCodes.size(), errorCode); if(errorCode.isFailure()) { errln("setReorderCodes() failed on line %d: %s", - (int)fileLineNumber, errorCode.errorName()); + static_cast(fileLineNumber), errorCode.errorName()); infoln(fileLine); return; } @@ -1272,7 +1272,7 @@ void CollationTest::buildTailoring(UCHARBUF *f, IcuTestErrorCode &errorCode) { if(errorCode.isFailure()) { dataerrln("RuleBasedCollator(rules) failed - %s", errorCode.errorName()); infoln(UnicodeString(" reason: ") + reason); - if(parseError.offset >= 0) { infoln(" rules offset: %d", (int)parseError.offset); } + if (parseError.offset >= 0) { infoln(" rules offset: %d", static_cast(parseError.offset)); } if(parseError.preContext[0] != 0 || parseError.postContext[0] != 0) { infoln(UnicodeString(" snippet: ...") + parseError.preContext + "(!)" + parseError.postContext + "..."); @@ -1300,9 +1300,9 @@ void CollationTest::setLocaleCollator(IcuTestErrorCode &errorCode) { if(errorCode.isFailure()) { return; } delete coll; coll = nullptr; - int32_t at = fileLine.indexOf((char16_t)0x40, 9); // @ is not invariant + int32_t at = fileLine.indexOf(static_cast(0x40), 9); // @ is not invariant if(at >= 0) { - fileLine.setCharAt(at, (char16_t)0x2a); // * + fileLine.setCharAt(at, static_cast(0x2a)); // * } CharString localeID; localeID.appendInvariantChars(fileLine.tempSubString(9), errorCode); @@ -1311,7 +1311,7 @@ void CollationTest::setLocaleCollator(IcuTestErrorCode &errorCode) { } Locale locale(localeID.data()); if(fileLine.length() == 9 || errorCode.isFailure() || locale.isBogus()) { - errln("invalid language tag on line %d", (int)fileLineNumber); + errln("invalid language tag on line %d", static_cast(fileLineNumber)); infoln(fileLine); if(errorCode.isSuccess()) { errorCode.set(U_PARSE_ERROR); } return; @@ -1321,7 +1321,7 @@ void CollationTest::setLocaleCollator(IcuTestErrorCode &errorCode) { coll = Collator::createInstance(locale, errorCode); if(errorCode.isFailure()) { dataerrln("unable to create a collator for locale %s on line %d", - locale.getName(), (int)fileLineNumber); + locale.getName(), static_cast(fileLineNumber)); infoln(fileLine); delete coll; coll = nullptr; @@ -1336,7 +1336,7 @@ UBool CollationTest::needsNormalization(const UnicodeString &s, UErrorCode &erro // those composites must be decomposed. // Check if s contains 0F71 immediately followed by 0F73 or 0F75 or 0F81. int32_t index = 0; - while((index = s.indexOf((char16_t)0xf71, index)) >= 0) { + while ((index = s.indexOf(static_cast(0xf71), index)) >= 0) { if(++index < s.length()) { char16_t c = s[index]; if(c == 0xf73 || c == 0xf75 || c == 0xf81) { return true; } @@ -1416,7 +1416,7 @@ UBool CollationTest::getCollationKey(const char *norm, const UnicodeString &line if(numLevelSeparators != (numLevels - 1)) { infoln(fileTestName); errln("Collator(%s).getCollationKey() has %d level separators for %d levels", - norm, (int)numLevelSeparators, (int)numLevels); + norm, static_cast(numLevelSeparators), static_cast(numLevels)); infoln(line); infoln(printCollationKey(key)); return false; @@ -1430,14 +1430,14 @@ UBool CollationTest::getCollationKey(const char *norm, const UnicodeString &line if(!getSortKeyParts(s, length, parts, 32, errorCode)) { infoln(fileTestName); errln("Collator(%s).internalNextSortKeyPart(%d) failed: %s", - norm, (int)partSize, errorCode.errorName()); + norm, static_cast(partSize), errorCode.errorName()); infoln(line); return false; } if(keyLength != parts.length() || uprv_memcmp(keyBytes, parts.data(), keyLength) != 0) { infoln(fileTestName); errln("Collator(%s).getCollationKey() != internalNextSortKeyPart(%d)", - norm, (int)partSize); + norm, static_cast(partSize)); infoln(line); infoln(printCollationKey(key)); infoln(printSortKey(reinterpret_cast(parts.data()), parts.length())); @@ -1523,7 +1523,7 @@ const UnicodeString &surrogatesToFFFD(const UnicodeString &s, UnicodeString &buf if(buffer.length() < i) { buffer.append(s, buffer.length(), i - buffer.length()); } - buffer.append((char16_t)0xfffd); + buffer.append(static_cast(0xfffd)); } i += U16_LENGTH(c); } @@ -1580,7 +1580,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != expectedOrder || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compare(previous, current) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1591,7 +1591,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != -expectedOrder || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compare(current, previous) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, -expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, -expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1599,13 +1599,13 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev return false; } // Test NUL-termination if the strings do not contain NUL characters. - UBool containNUL = prevString.indexOf((char16_t)0) >= 0 || s.indexOf((char16_t)0) >= 0; + UBool containNUL = prevString.indexOf(static_cast(0)) >= 0 || s.indexOf(static_cast(0)) >= 0; if(!containNUL) { order = coll->compare(prevString.getBuffer(), -1, s.getBuffer(), -1, errorCode); if(order != expectedOrder || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compare(previous-NUL, current-NUL) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1616,7 +1616,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != -expectedOrder || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compare(current-NUL, previous-NUL) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, -expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, -expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1646,7 +1646,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != expectedUTF8Order || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compareUTF8(previous, current) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedUTF8Order, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedUTF8Order, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1657,7 +1657,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != -expectedUTF8Order || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).compareUTF8(current, previous) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, -expectedUTF8Order, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, -expectedUTF8Order, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1670,7 +1670,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != expectedUTF8Order || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).internalCompareUTF8(previous-NUL, current-NUL) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedUTF8Order, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedUTF8Order, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1681,7 +1681,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != -expectedUTF8Order || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).internalCompareUTF8(current-NUL, previous-NUL) wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, -expectedUTF8Order, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, -expectedUTF8Order, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1699,7 +1699,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev infoln(fileTestName); errln("line %d Collator(%s).compare(UCharIterator: previous, current) " "wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1711,7 +1711,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(order != expectedOrder || errorCode.isFailure()) { infoln(fileTestName); errln("line %d Collator(%s).getCollationKey(previous, current).compareTo() wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1724,7 +1724,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev if(level != expectedLevel) { infoln(fileTestName); errln("line %d Collator(%s).getCollationKey(previous, current).compareTo()=%d wrong level: %d != %d", - (int)fileLineNumber, norm, order, level, expectedLevel); + static_cast(fileLineNumber), norm, order, level, expectedLevel); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1749,7 +1749,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev infoln(fileTestName); errln("line %d ucol_mergeSortkeys(Collator(%s).getCollationKey" "(previous, current segments between U+FFFE)).compareTo() wrong order: %d != %d (%s)", - (int)fileLineNumber, norm, order, expectedOrder, errorCode.errorName()); + static_cast(fileLineNumber), norm, order, expectedOrder, errorCode.errorName()); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1762,7 +1762,7 @@ UBool CollationTest::checkCompareTwo(const char *norm, const UnicodeString &prev infoln(fileTestName); errln("line %d ucol_mergeSortkeys(Collator(%s).getCollationKey" "(previous, current segments between U+FFFE)).compareTo()=%d wrong level: %d != %d", - (int)fileLineNumber, norm, order, mergedLevel, level); + static_cast(fileLineNumber), norm, order, mergedLevel, level); infoln(prevFileLine); infoln(fileLine); infoln(printCollationKey(prevKey)); @@ -1845,7 +1845,7 @@ void CollationTest::TestDataDriven() { // Sub-parsers leave the first line set that they do not handle. while(errorCode.isSuccess() && (!fileLine.isEmpty() || readNonEmptyLine(f.getAlias(), errorCode))) { if(!isSectionStarter(fileLine[0])) { - errln("syntax error on line %d", (int)fileLineNumber); + errln("syntax error on line %d", static_cast(fileLineNumber)); infoln(fileLine); return; } @@ -1866,7 +1866,7 @@ void CollationTest::TestDataDriven() { } else if(fileLine == UNICODE_STRING("* compare", 9)) { checkCompareStrings(f.getAlias(), errorCode); } else { - errln("syntax error on line %d", (int)fileLineNumber); + errln("syntax error on line %d", static_cast(fileLineNumber)); infoln(fileLine); return; } diff --git a/icu4c/source/test/intltest/colldata.cpp b/icu4c/source/test/intltest/colldata.cpp index d989d4f42003..b40c4e4e46fc 100644 --- a/icu4c/source/test/intltest/colldata.cpp +++ b/icu4c/source/test/intltest/colldata.cpp @@ -75,7 +75,7 @@ CEList::CEList(UCollator *coll, const UnicodeString &string, UErrorCode &status) order &= strengthMask; - if (toShift && variableTop > (uint32_t)order && (order & UCOL_PRIMARYORDERMASK) != 0) { + if (toShift && variableTop > static_cast(order) && (order & UCOL_PRIMARYORDERMASK) != 0) { if (strength >= UCOL_QUATERNARY) { order &= UCOL_PRIMARYORDERMASK; } else { @@ -138,7 +138,7 @@ uint32_t CEList::get(int32_t index) const return ces[index]; } - return (uint32_t)UCOL_NULLORDER; + return static_cast(UCOL_NULLORDER); } uint32_t &CEList::operator[](int32_t index) const @@ -451,7 +451,7 @@ CollData::CollData(UCollator *collator, UErrorCode &status) maxHan = 0; for(int32_t h = 0; h < hanList.size(); h += 2) { - uint32_t han = (uint32_t) hanList[h]; + uint32_t han = hanList[h]; if (han < minHan) { minHan = han; diff --git a/icu4c/source/test/intltest/compactdecimalformattest.cpp b/icu4c/source/test/intltest/compactdecimalformattest.cpp index e7a566058f0b..6ebd5bce1156 100644 --- a/icu4c/source/test/intltest/compactdecimalformattest.cpp +++ b/icu4c/source/test/intltest/compactdecimalformattest.cpp @@ -404,7 +404,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { actual.remove(); pos.setBeginIndex(0); pos.setEndIndex(0); - cdf->format((double)123456.0, actual, pos); + cdf->format(123456.0, actual, pos); if (actual != expected || pos.getEndIndex() != 3) { errln(UnicodeString("Fail format(double,UnicodeString&,FieldPosition&): Expected: \"") + expected + "\", pos 3; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex()); @@ -414,7 +414,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((double)123456.0, actual, pos, status); + cdf->format(123456.0, actual, pos, status); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(double,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", pos 3, status U_ZERO_ERROR; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex() + ", status " + u_errorName(status)); @@ -424,7 +424,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((double)123456.0, actual, &posIter, status); + cdf->format(123456.0, actual, &posIter, status); posIter.next(pos); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(int32_t,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", first pos 3, status U_ZERO_ERROR; " + @@ -434,7 +434,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { actual.remove(); pos.setBeginIndex(0); pos.setEndIndex(0); - cdf->format((int32_t)123456, actual, pos); + cdf->format(static_cast(123456), actual, pos); if (actual != expected || pos.getEndIndex() != 3) { errln(UnicodeString("Fail format(int32_t,UnicodeString&,FieldPosition&): Expected: \"") + expected + "\", pos 3; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex()); @@ -444,7 +444,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((int32_t)123456, actual, pos, status); + cdf->format(static_cast(123456), actual, pos, status); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(int32_t,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", pos 3, status U_ZERO_ERROR; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex() + ", status " + u_errorName(status)); @@ -454,7 +454,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((int32_t)123456, actual, &posIter, status); + cdf->format(static_cast(123456), actual, &posIter, status); posIter.next(pos); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(int32_t,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", first pos 3, status U_ZERO_ERROR; " + @@ -464,7 +464,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { actual.remove(); pos.setBeginIndex(0); pos.setEndIndex(0); - cdf->format((int64_t)123456, actual, pos); + cdf->format(static_cast(123456), actual, pos); if (actual != expected || pos.getEndIndex() != 3) { errln(UnicodeString("Fail format(int64_t,UnicodeString&,FieldPosition&): Expected: \"") + expected + "\", pos 3; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex()); @@ -474,7 +474,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((int64_t)123456, actual, pos, status); + cdf->format(static_cast(123456), actual, pos, status); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(int64_t,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", pos 3, status U_ZERO_ERROR; " + "Got: \"" + actual + "\", pos " + pos.getEndIndex() + ", status " + u_errorName(status)); @@ -484,7 +484,7 @@ void CompactDecimalFormatTest::TestAPIVariants() { pos.setBeginIndex(0); pos.setEndIndex(0); status = U_ZERO_ERROR; - cdf->format((int64_t)123456, actual, &posIter, status); + cdf->format(static_cast(123456), actual, &posIter, status); posIter.next(pos); if (actual != expected || pos.getEndIndex() != 3 || status != U_ZERO_ERROR) { errln(UnicodeString("Fail format(int32_t,UnicodeString&,FieldPosition&,UErrorCode&): Expected: \"") + expected + "\", first pos 3, status U_ZERO_ERROR; " + diff --git a/icu4c/source/test/intltest/convtest.cpp b/icu4c/source/test/intltest/convtest.cpp index 9c2fef3b8a37..981d577543d9 100644 --- a/icu4c/source/test/intltest/convtest.cpp +++ b/icu4c/source/test/intltest/convtest.cpp @@ -263,7 +263,7 @@ ConversionTest::TestFromUnicode() { s=testCase->getString("callback", errorCode); cc.setSub=0; // default: no subchar - if((index=s.indexOf((char16_t)0))>0) { + if ((index = s.indexOf(static_cast(0))) > 0) { // read NUL-separated subchar first, if any // copy the subchar from Latin-1 characters // start after the NUL @@ -271,13 +271,13 @@ ConversionTest::TestFromUnicode() { length=index+1; p+=length; length=s.length()-length; - if(length<=0 || length>=(int32_t)sizeof(cc.subchar)) { + if (length <= 0 || length >= static_cast(sizeof(cc.subchar))) { errorCode=U_ILLEGAL_ARGUMENT_ERROR; } else { int32_t j; for(j=0; j(p[j]); } // NUL-terminate the subchar cc.subchar[j]=0; @@ -286,7 +286,7 @@ ConversionTest::TestFromUnicode() { // remove the NUL and subchar from s s.truncate(index); - } else if((index=s.indexOf((char16_t)0x3d))>0) /* '=' */ { + } else if ((index = s.indexOf(static_cast(0x3d))) > 0) /* '=' */ { // read a substitution string, separated by an equal sign p=s.getBuffer()+index+1; length=s.length()-(index+1); @@ -430,7 +430,7 @@ ConversionTest::TestGetUnicodeSet() { continue; } - ucnv_getUnicodeSet(cnv.getAlias(), cnvSetPtr->toUSet(), (UConverterUnicodeSet)which, &errorCode); + ucnv_getUnicodeSet(cnv.getAlias(), cnvSetPtr->toUSet(), static_cast(which), &errorCode); if(U_FAILURE(errorCode)) { errln("error in ucnv_getUnicodeSet(\"%s\") for conversion/getUnicodeSet test case %d - %s", @@ -509,26 +509,26 @@ ConversionTest::TestGetUnicodeSet2() { char16_t c2; // low BMP for(c=0; c<=0xd7ff; ++c) { - *s++=(char16_t)c; + *s++ = static_cast(c); } // trail surrogates for(c=0xdc00; c<=0xdfff; ++c) { - *s++=(char16_t)c; + *s++ = static_cast(c); } // lead surrogates // (after trails so that there is not even one surrogate pair in between) for(c=0xd800; c<=0xdbff; ++c) { - *s++=(char16_t)c; + *s++ = static_cast(c); } // high BMP for(c=0xe000; c<=0xffff; ++c) { - *s++=(char16_t)c; + *s++ = static_cast(c); } // supplementary code points = surrogate pairs if(cpLimit==0x110000) { for(c=0xd800; c<=0xdbff; ++c) { for(c2=0xdc00; c2<=0xdfff; ++c2) { - *s++=(char16_t)c; + *s++ = static_cast(c); *s++=c2; } } @@ -568,7 +568,7 @@ ConversionTest::TestGetUnicodeSet2() { continue; } UConverterUnicodeSet which; - for(which=UCNV_ROUNDTRIP_SET; which(static_cast(which) + 1)) { if(which==UCNV_ROUNDTRIP_AND_FALLBACK_SET) { ucnv_setFallback(cnv.getAlias(), true); } @@ -577,7 +577,7 @@ ConversionTest::TestGetUnicodeSet2() { UBool flush; do { char *t=buffer; - flush=(UBool)(s==s0+s0Length); + flush = static_cast(s == s0 + s0Length); ucnv_fromUnicode(cnv.getAlias(), &t, buffer+sizeof(buffer), (const char16_t **)&s, s0+s0Length, nullptr, flush, &errorCode); if(U_FAILURE(errorCode)) { if(errorCode==U_BUFFER_OVERFLOW_ERROR) { @@ -742,7 +742,7 @@ ConversionTest::TestUTF8ToUTF8Overflow() { buffer16, &pivotSource, &pivotTarget, pivotLimit, false, false, errorCode); assertEquals("overflow", U_BUFFER_OVERFLOW_ERROR, errorCode.reset()); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("number of bytes written", 2, length); assertEquals("next byte not clobbered", 5, result[2]); @@ -753,7 +753,7 @@ ConversionTest::TestUTF8ToUTF8Overflow() { false, true, errorCode); assertSuccess("UTF-8->UTF-8", errorCode); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("3 bytes", 3, length); if (length == 3) { assertTrue("result same as input", memcmp(text, result, length) == 0); @@ -775,7 +775,7 @@ ConversionTest::TestUTF8ToUTF8Overflow() { buffer16, &pivotSource, &pivotTarget, pivotLimit, false, false, errorCode); assertEquals("text2 overflow", U_BUFFER_OVERFLOW_ERROR, errorCode.reset()); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("text2 number of bytes written", 3, length); assertEquals("text2 next byte not clobbered", 5, result[3]); @@ -786,7 +786,7 @@ ConversionTest::TestUTF8ToUTF8Overflow() { false, true, errorCode); assertSuccess("text2 UTF-8->UTF-8", errorCode); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("text2 5 bytes", 5, length); if (length == 5) { assertTrue("text2 result same as input", memcmp(text2, result, length) == 0); @@ -812,14 +812,14 @@ ConversionTest::TestUTF8ToUTF8Overflow() { buffer16, &pivotSource, &pivotTarget, pivotLimit, false, true, errorCode); assertEquals("illFormed truncated", U_TRUNCATED_CHAR_FOUND, errorCode.reset()); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("illFormed number of bytes written", 0, length); errorLength = UPRV_LENGTHOF(errorBytes); ucnv_getInvalidChars(cnv1.getAlias(), errorBytes, &errorLength, errorCode); - assertEquals("illFormed truncated errorLength", 2, (int32_t)errorLength); + assertEquals("illFormed truncated errorLength", 2, static_cast(errorLength)); if (errorLength == 2) { assertEquals("illFormed truncated errorBytes", 0xf191, - ((int32_t)(uint8_t)errorBytes[0] << 8) | (uint8_t)errorBytes[1]); + (static_cast(static_cast(errorBytes[0])) << 8) | static_cast(errorBytes[1])); } // Continue conversion starting with a trail byte. @@ -829,13 +829,13 @@ ConversionTest::TestUTF8ToUTF8Overflow() { false, true, errorCode); assertEquals("illFormed trail byte", U_ILLEGAL_CHAR_FOUND, errorCode.reset()); - length = (int32_t)(target - result); + length = static_cast(target - result); assertEquals("illFormed trail byte number of bytes written", 0, length); errorLength = UPRV_LENGTHOF(errorBytes); ucnv_getInvalidChars(cnv1.getAlias(), errorBytes, &errorLength, errorCode); - assertEquals("illFormed trail byte errorLength", 1, (int32_t)errorLength); + assertEquals("illFormed trail byte errorLength", 1, static_cast(errorLength)); if (errorLength == 1) { - assertEquals("illFormed trail byte errorBytes", 0x93, (int32_t)(uint8_t)errorBytes[0]); + assertEquals("illFormed trail byte errorBytes", 0x93, static_cast(static_cast(errorBytes[0]))); } } @@ -858,7 +858,7 @@ ConversionTest::TestUTF8ToUTF8Streaming() { char result[128]; - int32_t sourceLen = (int32_t)strlen(text); + int32_t sourceLen = static_cast(strlen(text)); const char* source = text; const char* sourceLimit = text + chunk1; @@ -877,7 +877,7 @@ ConversionTest::TestUTF8ToUTF8Streaming() { buffer16, &pivotSource, &pivotTarget, pivotLimit, false, false, errorCode); - length = (int32_t)(target - result); + length = static_cast(target - result); targetLen -= length; assertEquals("First chunk -1 doesn't match converted length", chunk1 - 1, length); @@ -890,7 +890,7 @@ ConversionTest::TestUTF8ToUTF8Streaming() { buffer16, &pivotSource, &pivotTarget, pivotLimit, false, true, errorCode); - length = (int32_t)(target - result - length); + length = static_cast(target - result - length); targetLen -= length; assertEquals("Second chunk + 2 doesn't match converted length", chunk2 + 1, length); @@ -918,7 +918,7 @@ ConversionTest::cnv_open(const char *name, UErrorCode &errorCode) { static inline char hexDigit(uint8_t digit) { - return digit<=9 ? (char)('0'+digit) : (char)('a'-10+digit); + return digit <= 9 ? static_cast('0' + digit) : static_cast('a' - 10 + digit); } static char * @@ -928,16 +928,16 @@ printBytes(const uint8_t *bytes, int32_t length, char *out) { if(length>0) { b=*bytes++; --length; - *out++=hexDigit((uint8_t)(b>>4)); - *out++=hexDigit((uint8_t)(b&0xf)); + *out++ = hexDigit(static_cast(b >> 4)); + *out++ = hexDigit(static_cast(b & 0xf)); } while(length>0) { b=*bytes++; --length; *out++=' '; - *out++=hexDigit((uint8_t)(b>>4)); - *out++=hexDigit((uint8_t)(b&0xf)); + *out++ = hexDigit(static_cast(b >> 4)); + *out++ = hexDigit(static_cast(b & 0xf)); } *out++=0; return out; @@ -958,12 +958,12 @@ printUnicode(const char16_t *unicode, int32_t length, char *out) { *out++='1'; } if(c>=0x10000) { - *out++=hexDigit((uint8_t)((c>>16)&0xf)); + *out++ = hexDigit(static_cast((c >> 16) & 0xf)); } - *out++=hexDigit((uint8_t)((c>>12)&0xf)); - *out++=hexDigit((uint8_t)((c>>8)&0xf)); - *out++=hexDigit((uint8_t)((c>>4)&0xf)); - *out++=hexDigit((uint8_t)(c&0xf)); + *out++ = hexDigit(static_cast((c >> 12) & 0xf)); + *out++ = hexDigit(static_cast((c >> 8) & 0xf)); + *out++ = hexDigit(static_cast((c >> 4) & 0xf)); + *out++ = hexDigit(static_cast(c & 0xf)); } *out++=0; return out; @@ -989,10 +989,10 @@ printOffsets(const int32_t *offsets, int32_t length, char *out) { *out++='x'; } else if(o<0) { *out++='-'; - *out++=(char)('0'-o); + *out++ = static_cast('0' - o); } else if(o<=99) { - *out++=(d=o/10)==0 ? ' ' : (char)('0'+d); - *out++=(char)('0'+o%10); + *out++ = (d = o / 10) == 0 ? ' ' : static_cast('0' + d); + *out++ = static_cast('0' + o % 10); } else /* o>99 */ { *out++='x'; *out++='x'; @@ -1014,7 +1014,7 @@ stepToUnicode(ConversionCase &cc, UConverter *cnv, char16_t *target, *targetLimit, *resultLimit; UBool flush; - source=(const char *)cc.bytes; + source = reinterpret_cast(cc.bytes); target=result; bytesLimit=source+cc.bytesLength; resultLimit=result+resultCapacity; @@ -1085,7 +1085,7 @@ stepToUnicode(ConversionCase &cc, UConverter *cnv, // the partial conversion succeeded, set a new limit and continue sourceLimit=(bytesLimit-source)>=step ? source+step : bytesLimit; - flush=(UBool)(cc.finalFlush && sourceLimit==bytesLimit); + flush = static_cast(cc.finalFlush && sourceLimit == bytesLimit); } } } else /* step<0 */ { @@ -1126,7 +1126,7 @@ stepToUnicode(ConversionCase &cc, UConverter *cnv, break; } if(c<=0xffff) { - *target++=(char16_t)c; + *target++ = static_cast(c); } else { *target++=U16_LEAD(c); if(target==resultLimit) { @@ -1158,7 +1158,7 @@ stepToUnicode(ConversionCase &cc, UConverter *cnv, ucnv_toUnicode(cnv, &target, targetLimit, &source, sourceLimit, - nullptr, (UBool)(sourceLimit==bytesLimit), pErrorCode); + nullptr, static_cast(sourceLimit == bytesLimit), pErrorCode); // check pointers and errors if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) { @@ -1191,7 +1191,7 @@ stepToUnicode(ConversionCase &cc, UConverter *cnv, } } - return (int32_t)(target-result); + return static_cast(target - result); } UBool @@ -1279,7 +1279,7 @@ ConversionTest::ToUnicodeCase(ConversionCase &cc, UConverterToUCallback callback errln("toUnicode[%d](%s) Conversion wrote too much to offsets at index %d", cc.caseNr, cc.charset, resultLength); } - if (result[resultLength] != (char16_t)-1) { + if (result[resultLength] != static_cast(-1)) { errln("toUnicode[%d](%s) Conversion wrote too much to result at index %d", cc.caseNr, cc.charset, resultLength); } @@ -1293,7 +1293,7 @@ ConversionTest::ToUnicodeCase(ConversionCase &cc, UConverterToUCallback callback errorCode.reset(); resultLength=ucnv_toUChars(cnv.getAlias(), result, UPRV_LENGTHOF(result), - (const char *)cc.bytes, cc.bytesLength, + reinterpret_cast(cc.bytes), cc.bytesLength, errorCode); ok=checkToUnicode( cc, cnv.getAlias(), "toUChars", @@ -1309,7 +1309,7 @@ ConversionTest::ToUnicodeCase(ConversionCase &cc, UConverterToUCallback callback errorCode.reset(); resultLength=ucnv_toUChars(cnv.getAlias(), nullptr, 0, - (const char *)cc.bytes, cc.bytesLength, + reinterpret_cast(cc.bytes), cc.bytesLength, errorCode); if(errorCode.get()==U_STRING_NOT_TERMINATED_WARNING || errorCode.get()==U_BUFFER_OVERFLOW_ERROR) { errorCode.reset(); @@ -1379,11 +1379,11 @@ ConversionTest::checkToUnicode(ConversionCase &cc, UConverter *cnv, const char * s=printOffsets(cc.offsets, cc.unicodeLength, offsetsString=s); s=printOffsets(resultOffsets, resultLength, resultOffsetsString=s); s=printBytes(cc.invalidChars, cc.invalidLength, invalidCharsString=s); - s=printBytes((uint8_t *)resultInvalidChars, resultInvalidLength, resultInvalidCharsString=s); + s = printBytes(reinterpret_cast(resultInvalidChars), resultInvalidLength, resultInvalidCharsString = s); - if((s-buffer)>(int32_t)sizeof(buffer)) { + if (s - buffer > static_cast(sizeof(buffer))) { errln("toUnicode[%d](%s cb=\"%s\" fb=%d flush=%d %s) fatal error: checkToUnicode() test output buffer overflow writing %d chars\n", - cc.caseNr, cc.charset, cc.cbopt, cc.fallbacks, cc.finalFlush, name, (int)(s-buffer)); + cc.caseNr, cc.charset, cc.cbopt, cc.fallbacks, cc.finalFlush, name, static_cast(s - buffer)); exit(1); } @@ -1509,11 +1509,11 @@ stepFromUTF8(ConversionCase &cc, // the partial conversion succeeded, set a new limit and continue sourceLimit=(utf8Limit-source)>=step ? source+step : utf8Limit; - flush=(UBool)(cc.finalFlush && sourceLimit==utf8Limit); + flush = static_cast(cc.finalFlush && sourceLimit == utf8Limit); } } - return (int32_t)(target-result); + return static_cast(target - result); } static int32_t @@ -1596,11 +1596,11 @@ stepFromUnicode(ConversionCase &cc, UConverter *cnv, // the partial conversion succeeded, set a new limit and continue sourceLimit=(unicodeLimit-source)>=step ? source+step : unicodeLimit; - flush=(UBool)(cc.finalFlush && sourceLimit==unicodeLimit); + flush = static_cast(cc.finalFlush && sourceLimit == unicodeLimit); } } - return (int32_t)(target-result); + return static_cast(target - result); } UBool @@ -1637,8 +1637,8 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call int32_t length; if(cc.setSub>0) { - length=(int32_t)strlen(cc.subchar); - ucnv_setSubstChars(cnv, cc.subchar, (int8_t)length, &errorCode); + length = static_cast(strlen(cc.subchar)); + ucnv_setSubstChars(cnv, cc.subchar, static_cast(length), &errorCode); if(U_FAILURE(errorCode)) { errln("fromUnicode[%d](%s cb=\"%s\" fb=%d flush=%d) ucnv_setSubstChars() failed - %s", cc.caseNr, cc.charset, cc.cbopt, cc.fallbacks, cc.finalFlush, u_errorName(errorCode)); @@ -1700,7 +1700,7 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call step, &errorCode); ok=checkFromUnicode( cc, cnv, steps[i].name, - (uint8_t *)result, resultLength, + reinterpret_cast(result), resultLength, cc.offsets!=nullptr ? resultOffsets : nullptr, errorCode); if(U_FAILURE(errorCode) || !cc.finalFlush) { @@ -1712,7 +1712,7 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call errln("fromUnicode[%d](%s) Conversion wrote too much to offsets at index %d", cc.caseNr, cc.charset, resultLength); } - if (result[resultLength] != (char)-1) { + if (result[resultLength] != static_cast(-1)) { errln("fromUnicode[%d](%s) Conversion wrote too much to result at index %d", cc.caseNr, cc.charset, resultLength); } @@ -1728,7 +1728,7 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call step, &errorCode); ok=checkFromUnicode( cc, cnv, steps[i].utf8Name, - (uint8_t *)result, resultLength, + reinterpret_cast(result), resultLength, nullptr, errorCode); if(U_FAILURE(errorCode) || !cc.finalFlush) { @@ -1752,7 +1752,7 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call &errorCode); ok=checkFromUnicode( cc, cnv, "fromUChars", - (uint8_t *)result, resultLength, + reinterpret_cast(result), resultLength, nullptr, errorCode); if(!ok) { @@ -1771,7 +1771,7 @@ ConversionTest::FromUnicodeCase(ConversionCase &cc, UConverterFromUCallback call } ok=checkFromUnicode( cc, cnv, "preflight fromUChars", - (uint8_t *)result, resultLength, + reinterpret_cast(result), resultLength, nullptr, errorCode); break; @@ -1836,9 +1836,9 @@ ConversionTest::checkFromUnicode(ConversionCase &cc, UConverter *cnv, const char s=printUnicode(cc.invalidUChars, cc.invalidLength, invalidCharsString=s); s=printUnicode(resultInvalidUChars, resultInvalidLength, resultInvalidUCharsString=s); - if((s-buffer)>(int32_t)sizeof(buffer)) { + if (s - buffer > static_cast(sizeof(buffer))) { errln("fromUnicode[%d](%s cb=\"%s\" fb=%d flush=%d %s) fatal error: checkFromUnicode() test output buffer overflow writing %d chars\n", - cc.caseNr, cc.charset, cc.cbopt, cc.fallbacks, cc.finalFlush, name, (int)(s-buffer)); + cc.caseNr, cc.charset, cc.cbopt, cc.fallbacks, cc.finalFlush, name, static_cast(s - buffer)); exit(1); } diff --git a/icu4c/source/test/intltest/cpdtrtst.cpp b/icu4c/source/test/intltest/cpdtrtst.cpp index 69999afaff3d..b5d6cc7cf7e6 100644 --- a/icu4c/source/test/intltest/cpdtrtst.cpp +++ b/icu4c/source/test/intltest/cpdtrtst.cpp @@ -277,8 +277,8 @@ void CompoundTransliteratorTest::TestGetSetAdoptTransliterator(){ ct1->setTransliterators(transarray, count); if(ct1->getCount() != count || ct1->getID() != ID2){ - errln((UnicodeString)"Error: setTransliterators() failed.\n\t Count:- expected->" + count + (UnicodeString)". got->" + ct1->getCount() + - (UnicodeString)"\n\tID :- expected->" + ID2 + (UnicodeString)". got->" + ct1->getID()); + errln(UnicodeString("Error: setTransliterators() failed.\n\t Count:- expected->") + count + UnicodeString(". got->") + ct1->getCount() + + UnicodeString("\n\tID :- expected->") + ID2 + UnicodeString(". got->") + ct1->getID()); } else{ logln("OK: setTransliterators() passed"); @@ -303,8 +303,8 @@ void CompoundTransliteratorTest::TestGetSetAdoptTransliterator(){ ct1->adoptTransliterators(transarray2, 1); } if(ct1->getCount() != 1 || ct1->getID() != ID3){ - errln((UnicodeString)"Error: adoptTransliterators() failed.\n\t Count:- expected->1" + (UnicodeString)". got->" + ct1->getCount() + - (UnicodeString)"\n\tID :- expected->" + ID3 + (UnicodeString)". got->" + ct1->getID()); + errln(UnicodeString("Error: adoptTransliterators() failed.\n\t Count:- expected->1") + UnicodeString(". got->") + ct1->getCount() + + UnicodeString("\n\tID :- expected->") + ID3 + UnicodeString(". got->") + ct1->getID()); } else{ logln("OK: adoptTranslterator() passed"); diff --git a/icu4c/source/test/intltest/dadrcal.cpp b/icu4c/source/test/intltest/dadrcal.cpp index 725c8327565b..773fdfc818a7 100644 --- a/icu4c/source/test/intltest/dadrcal.cpp +++ b/icu4c/source/test/intltest/dadrcal.cpp @@ -223,7 +223,7 @@ void DataDrivenCalendarTest::testOps(TestData *testData, // Is the calendar sane after being set? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); - errln((UnicodeString)"FAIL: "+caseString + errln(UnicodeString("FAIL: ") + caseString +", SET SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { @@ -238,17 +238,17 @@ void DataDrivenCalendarTest::testOps(TestData *testData, /// perform op for (int q=0; q(q))) { if (operation == kROLL) { - toCalendar->roll((UCalendarDateFields)q, - paramsSet.get((UCalendarDateFields)q), status); + toCalendar->roll(static_cast(q), + paramsSet.get(static_cast(q)), status); } else if (operation == kADD) { - toCalendar->add((UCalendarDateFields)q, - paramsSet.get((UCalendarDateFields)q), status); + toCalendar->add(static_cast(q), + paramsSet.get(static_cast(q)), status); } else { errln(caseString+ " FAIL: unknown operation "+ operation); } - logln(operation + " of "+ paramsSet.get((UCalendarDateFields)q) + logln(operation + " of " + paramsSet.get(static_cast(q)) +" -> "+u_errorName(status)); } } @@ -271,7 +271,7 @@ void DataDrivenCalendarTest::testOps(TestData *testData, } } else if (!toSet.matches(toCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(toSet, status); - errln((UnicodeString)"FAIL: "+caseString+" - , "+caseContentsString + errln(UnicodeString("FAIL: ") + caseString + " - , " + caseContentsString +" Differences: "+ diffs +"', status: " + u_errorName(status)); }else if (U_FAILURE(status)) { @@ -290,7 +290,7 @@ void DataDrivenCalendarTest::testConvert(int32_t n, const CalendarFieldsSet &fromSet, Calendar *fromCalendar, const CalendarFieldsSet &toSet, Calendar *toCalendar, UBool forward) { UErrorCode status = U_ZERO_ERROR; - UnicodeString thisString = (UnicodeString)"#"+n+" "+(forward ? "forward" + UnicodeString thisString = UnicodeString("#") + n + " " + (forward ? "forward" : "reverse")+" "+fromCalendar->getType()+"->"+toCalendar->getType(); fromCalendar->clear(); @@ -307,7 +307,7 @@ void DataDrivenCalendarTest::testConvert(int32_t n, // Is the calendar sane at the first? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); - errln((UnicodeString)"FAIL: "+thisString + errln(UnicodeString("FAIL: ") + thisString +", SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { @@ -329,7 +329,7 @@ void DataDrivenCalendarTest::testConvert(int32_t n, // Is the calendar sane after being set? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); - errln((UnicodeString)"FAIL: "+thisString + errln(UnicodeString("FAIL: ") + thisString +", SET SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { @@ -349,7 +349,7 @@ void DataDrivenCalendarTest::testConvert(int32_t n, diffSet.clear(); if (!toSet.matches(toCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(toSet, status); - errln((UnicodeString)"FAIL: "+thisString+", Differences: "+ diffs + errln(UnicodeString("FAIL: ") + thisString + ", Differences: " + diffs +"', status: "+ u_errorName(status)); SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy G"), status); UnicodeString fromString; @@ -433,12 +433,10 @@ void DataDrivenCalendarTest::testConvert(TestData *testData, // now, do it. if (forward) { - logln((UnicodeString)"#"+n+" "+locale+"/"+from+" >>> "+toCalLoc+"/" - +to); + logln(UnicodeString("#") + n + " " + locale + "/" + from + " >>> " + toCalLoc + "/" + to); testConvert(n, fromSet, fromCalendar.getAlias(), toSet, toCalendar.getAlias(), forward); } else { - logln((UnicodeString)"#"+n+" "+locale+"/"+from+" <<< "+toCalLoc+"/" - +to); + logln(UnicodeString("#") + n + " " + locale + "/" + from + " <<< " + toCalLoc + "/" + to); testConvert(n, toSet, toCalendar.getAlias(), fromSet, fromCalendar.getAlias(), forward); } } diff --git a/icu4c/source/test/intltest/dadrfmt.cpp b/icu4c/source/test/intltest/dadrfmt.cpp index 0eeef271280b..8dd1c8927e4c 100644 --- a/icu4c/source/test/intltest/dadrfmt.cpp +++ b/icu4c/source/test/intltest/dadrfmt.cpp @@ -174,7 +174,9 @@ void DataDrivenFormatTest::testConvertDate(TestData *testData, errln("case %d: could not parse spec as style fields: %s", n, u_errorName(status)); continue; } - format = DateFormat::createDateTimeInstance((DateFormat::EStyle)styleSet.getDateStyle(), (DateFormat::EStyle)styleSet.getTimeStyle(), loc); + format = DateFormat::createDateTimeInstance( + static_cast(styleSet.getDateStyle()), + static_cast(styleSet.getTimeStyle()), loc); if(format == nullptr ) { errln("case %d: could not create SimpleDateFormat from styles.", n); continue; @@ -212,14 +214,14 @@ void DataDrivenFormatTest::testConvertDate(TestData *testData, cal->clear(); cal->setTime(now, status); for (int q=0; q(q))) { //int32_t oldv = cal->get((UCalendarDateFields)q, status); if (q == UCAL_DATE) { - cal->add((UCalendarDateFields)q, - fromSet.get((UCalendarDateFields)q), status); + cal->add(static_cast(q), + fromSet.get(static_cast(q)), status); } else { - cal->set((UCalendarDateFields)q, - fromSet.get((UCalendarDateFields)q)); + cal->set(static_cast(q), + fromSet.get(static_cast(q))); } //int32_t newv = cal->get((UCalendarDateFields)q, status); } @@ -305,7 +307,7 @@ void DataDrivenFormatTest::testConvertDate(TestData *testData, // diffSet.clear(); if (!fromSet.matches(cal, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); - errln((UnicodeString)"FAIL: "+caseString + errln(UnicodeString("FAIL: ") + caseString +", Differences: '"+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { diff --git a/icu4c/source/test/intltest/datadrivennumberformattestsuite.cpp b/icu4c/source/test/intltest/datadrivennumberformattestsuite.cpp index 353b0478239f..efc58d58d19b 100644 --- a/icu4c/source/test/intltest/datadrivennumberformattestsuite.cpp +++ b/icu4c/source/test/intltest/datadrivennumberformattestsuite.cpp @@ -119,7 +119,7 @@ DataDrivenNumberFormatTestSuite::~DataDrivenNumberFormatTestSuite() { } UBool DataDrivenNumberFormatTestSuite::breaksC() { - return (NFTT_GET_FIELD(fTuple, breaks, "").toUpper().indexOf((char16_t)0x43) != -1); + return (NFTT_GET_FIELD(fTuple, breaks, "").toUpper().indexOf(static_cast(0x43)) != -1); } void DataDrivenNumberFormatTestSuite::setTupleField(UErrorCode &status) { @@ -170,14 +170,13 @@ void DataDrivenNumberFormatTestSuite::showLineInfo() { } void DataDrivenNumberFormatTestSuite::showError(const char *message) { - errln("line %d: %s", (int) fFileLineNumber, message); + errln("line %d: %s", static_cast(fFileLineNumber), message); showLineInfo(); } void DataDrivenNumberFormatTestSuite::showFailure(const UnicodeString &message) { char16_t lineStr[20]; - uprv_itou( - lineStr, UPRV_LENGTHOF(lineStr), (uint32_t) fFileLineNumber, 10, 1); + uprv_itou(lineStr, UPRV_LENGTHOF(lineStr), static_cast(fFileLineNumber), 10, 1); UnicodeString fullMessage("line "); dataerrln(fullMessage.append(lineStr).append(": ") .append(prettify(message))); diff --git a/icu4c/source/test/intltest/dcfmapts.cpp b/icu4c/source/test/intltest/dcfmapts.cpp index 18d04c5ceace..9794b338209a 100644 --- a/icu4c/source/test/intltest/dcfmapts.cpp +++ b/icu4c/source/test/intltest/dcfmapts.cpp @@ -32,16 +32,16 @@ void IntlTestDecimalFormatAPI::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ ) { - if (exec) logln((UnicodeString)"TestSuite DecimalFormatAPI"); + if (exec) logln(UnicodeString("TestSuite DecimalFormatAPI")); switch (index) { case 0: name = "DecimalFormat API test"; if (exec) { - logln((UnicodeString)"DecimalFormat API test---"); logln((UnicodeString)""); + logln(UnicodeString("DecimalFormat API test---")); logln(UnicodeString("")); UErrorCode status = U_ZERO_ERROR; Locale saveLocale; Locale::setDefault(Locale::getEnglish(), status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not set default locale, test may not give correct results"); + errln(UnicodeString("ERROR: Could not set default locale, test may not give correct results")); } testAPI(/*par*/); Locale::setDefault(saveLocale, status); @@ -49,55 +49,55 @@ void IntlTestDecimalFormatAPI::runIndexedTest( int32_t index, UBool exec, const break; case 1: name = "Rounding test"; if(exec) { - logln((UnicodeString)"DecimalFormat Rounding test---"); + logln(UnicodeString("DecimalFormat Rounding test---")); testRounding(/*par*/); } break; case 2: name = "Test6354"; if(exec) { - logln((UnicodeString)"DecimalFormat Rounding Increment test---"); + logln(UnicodeString("DecimalFormat Rounding Increment test---")); testRoundingInc(/*par*/); } break; case 3: name = "TestCurrencyPluralInfo"; if(exec) { - logln((UnicodeString)"CurrencyPluralInfo API test---"); + logln(UnicodeString("CurrencyPluralInfo API test---")); TestCurrencyPluralInfo(); } break; case 4: name = "TestScale"; if(exec) { - logln((UnicodeString)"Scale test---"); + logln(UnicodeString("Scale test---")); TestScale(); } break; case 5: name = "TestFixedDecimal"; if(exec) { - logln((UnicodeString)"TestFixedDecimal ---"); + logln(UnicodeString("TestFixedDecimal ---")); TestFixedDecimal(); } break; case 6: name = "TestBadFastpath"; if(exec) { - logln((UnicodeString)"TestBadFastpath ---"); + logln(UnicodeString("TestBadFastpath ---")); TestBadFastpath(); } break; case 7: name = "TestRequiredDecimalPoint"; if(exec) { - logln((UnicodeString)"TestRequiredDecimalPoint ---"); + logln(UnicodeString("TestRequiredDecimalPoint ---")); TestRequiredDecimalPoint(); } break; case 8: name = "testErrorCode"; if(exec) { - logln((UnicodeString)"testErrorCode ---"); + logln(UnicodeString("testErrorCode ---")); testErrorCode(); } break; case 9: name = "testInvalidObject"; if(exec) { - logln((UnicodeString) "testInvalidObject ---"); + logln(UnicodeString("testInvalidObject ---")); testInvalidObject(); } break; @@ -115,7 +115,7 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) // ======= Test constructors - logln((UnicodeString)"Testing DecimalFormat constructors"); + logln(UnicodeString("Testing DecimalFormat constructors")); DecimalFormat def(status); if(U_FAILURE(status)) { @@ -137,7 +137,7 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) DecimalFormat df("0", {"en", status}, status); UnicodeString result; assertEquals("pat 0: ", 0, df.getGroupingSize()); - assertEquals("pat 0: ", (UBool) false, (UBool) df.isGroupingUsed()); + assertEquals("pat 0: ", static_cast(false), df.isGroupingUsed()); df.setGroupingUsed(false); assertEquals("pat 0 then disabled: ", 0, df.getGroupingSize()); assertEquals("pat 0 then disabled: ", u"1111", df.format(1111, result.remove())); @@ -149,7 +149,7 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) DecimalFormat df("#,##0", {"en", status}, status); UnicodeString result; assertEquals("pat #,##0: ", 3, df.getGroupingSize()); - assertEquals("pat #,##0: ", (UBool) true, (UBool) df.isGroupingUsed()); + assertEquals("pat #,##0: ", static_cast(true), df.isGroupingUsed()); df.setGroupingUsed(false); assertEquals("pat #,##0 then disabled: ", 3, df.getGroupingSize()); assertEquals("pat #,##0 then disabled: ", u"1111", df.format(1111, result.remove())); @@ -163,21 +163,21 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) const UnicodeString pattern("#,##0.# FF"); DecimalFormat pat(pattern, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern)"); + errln(UnicodeString("ERROR: Could not create DecimalFormat (pattern)")); return; } status = U_ZERO_ERROR; DecimalFormatSymbols *symbols = new DecimalFormatSymbols(Locale::getFrench(), status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (French)"); + errln(UnicodeString("ERROR: Could not create DecimalFormatSymbols (French)")); return; } status = U_ZERO_ERROR; DecimalFormat cust1(pattern, *symbols, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols)"); + errln(UnicodeString("ERROR: Could not create DecimalFormat (pattern, symbols)")); } // NOTE: The test where you pass "symbols" as a pointer has to come second-- the DecimalFormat @@ -188,33 +188,33 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) status = U_ZERO_ERROR; DecimalFormat cust2(pattern, symbols, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); + errln(UnicodeString("ERROR: Could not create DecimalFormat (pattern, symbols*)")); } DecimalFormat copy(pat); // ======= Test clone(), assignment, and equality - logln((UnicodeString)"Testing clone(), assignment and equality operators"); + logln(UnicodeString("Testing clone(), assignment and equality operators")); if( ! (copy == pat) || copy != pat) { - errln((UnicodeString)"ERROR: Copy constructor or == failed"); + errln(UnicodeString("ERROR: Copy constructor or == failed")); } copy = cust1; if(copy != cust1) { - errln((UnicodeString)"ERROR: Assignment (or !=) failed"); + errln(UnicodeString("ERROR: Assignment (or !=) failed")); } Format *clone = def.clone(); if( ! (*clone == def) ) { - errln((UnicodeString)"ERROR: Clone() failed"); + errln(UnicodeString("ERROR: Clone() failed")); } delete clone; // ======= Test various format() methods - logln((UnicodeString)"Testing various format() methods"); + logln(UnicodeString("Testing various format() methods")); double d = -10456.0037; int32_t l = 100000000; @@ -225,28 +225,28 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) FieldPosition pos1(FieldPosition::DONT_CARE), pos2(FieldPosition::DONT_CARE), pos3(FieldPosition::DONT_CARE), pos4(FieldPosition::DONT_CARE); res1 = def.format(d, res1, pos1); - logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res1); + logln(UnicodeString("") + static_cast(d) + " formatted to " + res1); res2 = pat.format(l, res2, pos2); - logln((UnicodeString) "" + (int32_t) l + " formatted to " + res2); + logln(UnicodeString("") + l + " formatted to " + res2); status = U_ZERO_ERROR; res3 = cust1.format(fD, res3, pos3, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: format(Formattable [double]) failed"); + errln(UnicodeString("ERROR: format(Formattable [double]) failed")); } - logln((UnicodeString) "" + (int32_t) fD.getDouble() + " formatted to " + res3); + logln(UnicodeString("") + static_cast(fD.getDouble()) + " formatted to " + res3); status = U_ZERO_ERROR; res4 = cust2.format(fL, res4, pos4, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: format(Formattable [long]) failed"); + errln(UnicodeString("ERROR: format(Formattable [long]) failed")); } - logln((UnicodeString) "" + fL.getLong() + " formatted to " + res4); + logln(UnicodeString("") + fL.getLong() + " formatted to " + res4); // ======= Test parse() - logln((UnicodeString)"Testing parse()"); + logln(UnicodeString("Testing parse()")); UnicodeString text("-10,456.0037"); Formattable result1, result2; @@ -255,148 +255,148 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) status = U_ZERO_ERROR; pat.applyPattern(patt, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern() failed"); + errln(UnicodeString("ERROR: applyPattern() failed")); } pat.parse(text, result1, pos); if(result1.getType() != Formattable::kDouble && result1.getDouble() != d) { - errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); + errln(UnicodeString("ERROR: Roundtrip failed (via parse()) for ") + text); } - logln(text + " parsed into " + (int32_t) result1.getDouble()); + logln(text + " parsed into " + static_cast(result1.getDouble())); status = U_ZERO_ERROR; pat.parse(text, result2, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: parse() failed"); + errln(UnicodeString("ERROR: parse() failed")); } if(result2.getType() != Formattable::kDouble && result2.getDouble() != d) { - errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); + errln(UnicodeString("ERROR: Roundtrip failed (via parse()) for ") + text); } - logln(text + " parsed into " + (int32_t) result2.getDouble()); + logln(text + " parsed into " + static_cast(result2.getDouble())); // ======= Test getters and setters - logln((UnicodeString)"Testing getters and setters"); + logln(UnicodeString("Testing getters and setters")); const DecimalFormatSymbols *syms = pat.getDecimalFormatSymbols(); DecimalFormatSymbols *newSyms = new DecimalFormatSymbols(*syms); def.setDecimalFormatSymbols(*newSyms); def.adoptDecimalFormatSymbols(newSyms); // don't use newSyms after this if( *(pat.getDecimalFormatSymbols()) != *(def.getDecimalFormatSymbols())) { - errln((UnicodeString)"ERROR: adopt or set DecimalFormatSymbols() failed"); + errln(UnicodeString("ERROR: adopt or set DecimalFormatSymbols() failed")); } UnicodeString posPrefix; pat.setPositivePrefix("+"); posPrefix = pat.getPositivePrefix(posPrefix); - logln((UnicodeString)"Positive prefix (should be +): " + posPrefix); + logln(UnicodeString("Positive prefix (should be +): ") + posPrefix); if(posPrefix != "+") { - errln((UnicodeString)"ERROR: setPositivePrefix() failed"); + errln(UnicodeString("ERROR: setPositivePrefix() failed")); } UnicodeString negPrefix; pat.setNegativePrefix("-"); negPrefix = pat.getNegativePrefix(negPrefix); - logln((UnicodeString)"Negative prefix (should be -): " + negPrefix); + logln(UnicodeString("Negative prefix (should be -): ") + negPrefix); if(negPrefix != "-") { - errln((UnicodeString)"ERROR: setNegativePrefix() failed"); + errln(UnicodeString("ERROR: setNegativePrefix() failed")); } UnicodeString posSuffix; pat.setPositiveSuffix("_"); posSuffix = pat.getPositiveSuffix(posSuffix); - logln((UnicodeString)"Positive suffix (should be _): " + posSuffix); + logln(UnicodeString("Positive suffix (should be _): ") + posSuffix); if(posSuffix != "_") { - errln((UnicodeString)"ERROR: setPositiveSuffix() failed"); + errln(UnicodeString("ERROR: setPositiveSuffix() failed")); } UnicodeString negSuffix; pat.setNegativeSuffix("~"); negSuffix = pat.getNegativeSuffix(negSuffix); - logln((UnicodeString)"Negative suffix (should be ~): " + negSuffix); + logln(UnicodeString("Negative suffix (should be ~): ") + negSuffix); if(negSuffix != "~") { - errln((UnicodeString)"ERROR: setNegativeSuffix() failed"); + errln(UnicodeString("ERROR: setNegativeSuffix() failed")); } int32_t multiplier = 0; pat.setMultiplier(8); multiplier = pat.getMultiplier(); - logln((UnicodeString)"Multiplier (should be 8): " + multiplier); + logln(UnicodeString("Multiplier (should be 8): ") + multiplier); if(multiplier != 8) { - errln((UnicodeString)"ERROR: setMultiplier() failed"); + errln(UnicodeString("ERROR: setMultiplier() failed")); } int32_t groupingSize = 0; pat.setGroupingSize(2); groupingSize = pat.getGroupingSize(); - logln((UnicodeString)"Grouping size (should be 2): " + (int32_t) groupingSize); + logln(UnicodeString("Grouping size (should be 2): ") + groupingSize); if(groupingSize != 2) { - errln((UnicodeString)"ERROR: setGroupingSize() failed"); + errln(UnicodeString("ERROR: setGroupingSize() failed")); } pat.setDecimalSeparatorAlwaysShown(true); UBool tf = pat.isDecimalSeparatorAlwaysShown(); - logln((UnicodeString)"DecimalSeparatorIsAlwaysShown (should be true) is " + (UnicodeString) (tf ? "true" : "false")); + logln(UnicodeString("DecimalSeparatorIsAlwaysShown (should be true) is ") + UnicodeString(tf ? "true" : "false")); if(tf != true) { - errln((UnicodeString)"ERROR: setDecimalSeparatorAlwaysShown() failed"); + errln(UnicodeString("ERROR: setDecimalSeparatorAlwaysShown() failed")); } // Added by Ken Liu testing set/isExponentSignAlwaysShown pat.setExponentSignAlwaysShown(true); UBool esas = pat.isExponentSignAlwaysShown(); - logln((UnicodeString)"ExponentSignAlwaysShown (should be true) is " + (UnicodeString) (esas ? "true" : "false")); + logln(UnicodeString("ExponentSignAlwaysShown (should be true) is ") + UnicodeString(esas ? "true" : "false")); if(esas != true) { - errln((UnicodeString)"ERROR: ExponentSignAlwaysShown() failed"); + errln(UnicodeString("ERROR: ExponentSignAlwaysShown() failed")); } // Added by Ken Liu testing set/isScientificNotation pat.setScientificNotation(true); UBool sn = pat.isScientificNotation(); - logln((UnicodeString)"isScientificNotation (should be true) is " + (UnicodeString) (sn ? "true" : "false")); + logln(UnicodeString("isScientificNotation (should be true) is ") + UnicodeString(sn ? "true" : "false")); if(sn != true) { - errln((UnicodeString)"ERROR: setScientificNotation() failed"); + errln(UnicodeString("ERROR: setScientificNotation() failed")); } // Added by Ken Liu testing set/getMinimumExponentDigits int8_t MinimumExponentDigits = 0; pat.setMinimumExponentDigits(2); MinimumExponentDigits = pat.getMinimumExponentDigits(); - logln((UnicodeString)"MinimumExponentDigits (should be 2) is " + (int8_t) MinimumExponentDigits); + logln(UnicodeString("MinimumExponentDigits (should be 2) is ") + MinimumExponentDigits); if(MinimumExponentDigits != 2) { - errln((UnicodeString)"ERROR: setMinimumExponentDigits() failed"); + errln(UnicodeString("ERROR: setMinimumExponentDigits() failed")); } // Added by Ken Liu testing set/getRoundingIncrement double RoundingIncrement = 0.0; pat.setRoundingIncrement(2.0); RoundingIncrement = pat.getRoundingIncrement(); - logln((UnicodeString)"RoundingIncrement (should be 2.0) is " + (double) RoundingIncrement); + logln(UnicodeString("RoundingIncrement (should be 2.0) is ") + RoundingIncrement); if(RoundingIncrement != 2.0) { - errln((UnicodeString)"ERROR: setRoundingIncrement() failed"); + errln(UnicodeString("ERROR: setRoundingIncrement() failed")); } //end of Ken's Adding UnicodeString funkyPat; funkyPat = pat.toPattern(funkyPat); - logln((UnicodeString)"Pattern is " + funkyPat); + logln(UnicodeString("Pattern is ") + funkyPat); UnicodeString locPat; locPat = pat.toLocalizedPattern(locPat); - logln((UnicodeString)"Localized pattern is " + locPat); + logln(UnicodeString("Localized pattern is ") + locPat); // ======= Test applyPattern() - logln((UnicodeString)"Testing applyPattern()"); + logln(UnicodeString("Testing applyPattern()")); pat = DecimalFormat(status); // reset UnicodeString p1("#,##0.0#;(#,##0.0#)"); - logln((UnicodeString)"Applying pattern " + p1); + logln(UnicodeString("Applying pattern ") + p1); status = U_ZERO_ERROR; pat.applyPattern(p1, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); + errln(UnicodeString("ERROR: applyPattern() failed with ") + static_cast(status)); } UnicodeString s2; s2 = pat.toPattern(s2); - logln((UnicodeString)"Extracted pattern is " + s2); + logln(UnicodeString("Extracted pattern is ") + s2); assertEquals("toPattern() result did not match pattern applied", p1, s2); if(pat.getSecondaryGroupingSize() != 0) { @@ -408,26 +408,26 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) } UnicodeString p2("#,##,##0.0# FF;(#,##,##0.0# FF)"); - logln((UnicodeString)"Applying pattern " + p2); + logln(UnicodeString("Applying pattern ") + p2); status = U_ZERO_ERROR; pat.applyLocalizedPattern(p2, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); + errln(UnicodeString("ERROR: applyPattern() failed with ") + static_cast(status)); } UnicodeString s3; s3 = pat.toLocalizedPattern(s3); - logln((UnicodeString)"Extracted pattern is " + s3); + logln(UnicodeString("Extracted pattern is ") + s3); assertEquals("toLocalizedPattern() result did not match pattern applied", p2, s3); status = U_ZERO_ERROR; UParseError pe; pat.applyLocalizedPattern(p2, pe, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern((with ParseError)) failed with " + (int32_t) status); + errln(UnicodeString("ERROR: applyPattern((with ParseError)) failed with ") + static_cast(status)); } UnicodeString s4; s4 = pat.toLocalizedPattern(s3); - logln((UnicodeString)"Extracted pattern is " + s4); + logln(UnicodeString("Extracted pattern is ") + s4); assertEquals("toLocalizedPattern(with ParseErr) result did not match pattern applied", p2, s4); if(pat.getSecondaryGroupingSize() != 2) { @@ -440,16 +440,16 @@ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) // ======= Test getStaticClassID() - logln((UnicodeString)"Testing getStaticClassID()"); + logln(UnicodeString("Testing getStaticClassID()")); status = U_ZERO_ERROR; NumberFormat *test = new DecimalFormat(status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Couldn't create a DecimalFormat"); + errln(UnicodeString("ERROR: Couldn't create a DecimalFormat")); } if(test->getDynamicClassID() != DecimalFormat::getStaticClassID()) { - errln((UnicodeString)"ERROR: getDynamicClassID() didn't return the expected value"); + errln(UnicodeString("ERROR: getDynamicClassID() didn't return the expected value")); } delete test; @@ -460,29 +460,29 @@ void IntlTestDecimalFormatAPI::TestCurrencyPluralInfo(){ LocalPointercpi(new CurrencyPluralInfo(status), status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: CurrencyPluralInfo(UErrorCode) could not be created"); + errln(UnicodeString("ERROR: CurrencyPluralInfo(UErrorCode) could not be created")); return; } CurrencyPluralInfo cpi1 = *cpi; if(cpi->getDynamicClassID() != CurrencyPluralInfo::getStaticClassID()){ - errln((UnicodeString)"ERROR: CurrencyPluralInfo::getDynamicClassID() didn't return the expected value"); + errln(UnicodeString("ERROR: CurrencyPluralInfo::getDynamicClassID() didn't return the expected value")); } cpi->setCurrencyPluralPattern("","",status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: CurrencyPluralInfo::setCurrencyPluralPattern"); + errln(UnicodeString("ERROR: CurrencyPluralInfo::setCurrencyPluralPattern")); } cpi->setLocale(Locale::getCanada(), status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: CurrencyPluralInfo::setLocale"); + errln(UnicodeString("ERROR: CurrencyPluralInfo::setLocale")); } cpi->setPluralRules("",status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: CurrencyPluralInfo::setPluralRules"); + errln(UnicodeString("ERROR: CurrencyPluralInfo::setPluralRules")); } LocalPointerdf(new DecimalFormat(status)); @@ -523,23 +523,23 @@ void IntlTestDecimalFormatAPI::testRounding(/*char *par*/) UnicodeString message; UnicodeString resultStr; for(mode=0;mode < 7;mode++){ - pat.setRoundingMode((DecimalFormat::ERoundingMode)mode); - if(pat.getRoundingMode() != (DecimalFormat::ERoundingMode)mode){ - errln((UnicodeString)"SetRoundingMode or GetRoundingMode failed for mode=" + mode); + pat.setRoundingMode(static_cast(mode)); + if (pat.getRoundingMode() != static_cast(mode)) { + errln(UnicodeString("SetRoundingMode or GetRoundingMode failed for mode=") + mode); } //for +2.55 with RoundingIncrement=1.0 pat.setRoundingIncrement(1.0); pat.format(Roundingnumber, resultStr); - message= (UnicodeString)"round(" + (double)Roundingnumber + UnicodeString(",") + mode + UnicodeString(",false) with RoundingIncrement=1.0==>"); + message = UnicodeString("round(") + Roundingnumber + UnicodeString(",") + mode + UnicodeString(",false) with RoundingIncrement=1.0==>"); verify(message, resultStr, result[i++]); message.remove(); resultStr.remove(); //for -2.55 with RoundingIncrement=1.0 pat.format(Roundingnumber1, resultStr); - message= (UnicodeString)"round(" + (double)Roundingnumber1 + UnicodeString(",") + mode + UnicodeString(",false) with RoundingIncrement=1.0==>"); + message = UnicodeString("round(") + Roundingnumber1 + UnicodeString(",") + mode + UnicodeString(",false) with RoundingIncrement=1.0==>"); verify(message, resultStr, result[i++]); message.remove(); resultStr.remove(); @@ -547,18 +547,18 @@ void IntlTestDecimalFormatAPI::testRounding(/*char *par*/) } void IntlTestDecimalFormatAPI::verify(const UnicodeString& message, const UnicodeString& got, double expected){ - logln((UnicodeString)message + got + (UnicodeString)" Expected : " + expected); + logln(UnicodeString(message) + got + UnicodeString(" Expected : ") + expected); UnicodeString expectedStr(""); expectedStr=expectedStr + expected; if(got != expectedStr ) { - errln((UnicodeString)"ERROR: " + message + got + (UnicodeString)" Expected : " + expectedStr); + errln(UnicodeString("ERROR: ") + message + got + UnicodeString(" Expected : ") + expectedStr); } } void IntlTestDecimalFormatAPI::verifyString(const UnicodeString& message, const UnicodeString& got, UnicodeString& expected){ - logln((UnicodeString)message + got + (UnicodeString)" Expected : " + expected); + logln(UnicodeString(message) + got + UnicodeString(" Expected : ") + expected); if(got != expected ) { - errln((UnicodeString)"ERROR: " + message + got + (UnicodeString)" Expected : " + expected); + errln(UnicodeString("ERROR: ") + message + got + UnicodeString(" Expected : ") + expected); } } @@ -574,7 +574,7 @@ void IntlTestDecimalFormatAPI::testRoundingInc(/*char *par*/) // get default rounding increment double roundingInc = pat.getRoundingIncrement(); if (roundingInc != 0.0) { - errln((UnicodeString)"ERROR: Rounding increment not zero"); + errln(UnicodeString("ERROR: Rounding increment not zero")); return; } @@ -584,10 +584,10 @@ void IntlTestDecimalFormatAPI::testRoundingInc(/*char *par*/) // set rounding mode with zero increment. Rounding // increment should not be set by this operation - pat.setRoundingMode((DecimalFormat::ERoundingMode)0); + pat.setRoundingMode(static_cast(0)); roundingInc = pat.getRoundingIncrement(); if (roundingInc != 0.0) { - errln((UnicodeString)"ERROR: Rounding increment not zero after setRoundingMode"); + errln(UnicodeString("ERROR: Rounding increment not zero after setRoundingMode")); return; } } @@ -991,14 +991,14 @@ void IntlTestDecimalFormatAPI::TestBadFastpath() { UnicodeString fmt; fmt.remove(); - assertEquals("Format 1234", "1234", df->format((int32_t)1234, fmt)); + assertEquals("Format 1234", "1234", df->format(static_cast(1234), fmt)); df->setGroupingUsed(false); fmt.remove(); - assertEquals("Format 1234", "1234", df->format((int32_t)1234, fmt)); + assertEquals("Format 1234", "1234", df->format(static_cast(1234), fmt)); df->setGroupingUsed(true); df->setGroupingSize(3); fmt.remove(); - assertEquals("Format 1234 w/ grouping", "1,234", df->format((int32_t)1234, fmt)); + assertEquals("Format 1234 w/ grouping", "1,234", df->format(static_cast(1234), fmt)); } void IntlTestDecimalFormatAPI::TestRequiredDecimalPoint() { @@ -1017,16 +1017,16 @@ void IntlTestDecimalFormatAPI::TestRequiredDecimalPoint() { status = U_ZERO_ERROR; df->applyPattern(pat1, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern() failed"); + errln(UnicodeString("ERROR: applyPattern() failed")); } df->parse(text, result1, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: parse() failed"); + errln(UnicodeString("ERROR: parse() failed")); } df->setDecimalPatternMatchRequired(true); df->parse(text, result1, status); if(U_SUCCESS(status)) { - errln((UnicodeString)"ERROR: unexpected parse()"); + errln(UnicodeString("ERROR: unexpected parse()")); } @@ -1034,16 +1034,16 @@ void IntlTestDecimalFormatAPI::TestRequiredDecimalPoint() { df->applyPattern(pat2, status); df->setDecimalPatternMatchRequired(false); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: applyPattern(2) failed"); + errln(UnicodeString("ERROR: applyPattern(2) failed")); } df->parse(text, result1, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: parse(2) failed - " + u_errorName(status)); + errln(UnicodeString("ERROR: parse(2) failed - ") + u_errorName(status)); } df->setDecimalPatternMatchRequired(true); df->parse(text, result1, status); if(U_SUCCESS(status)) { - errln((UnicodeString)"ERROR: unexpected parse(2)"); + errln(UnicodeString("ERROR: unexpected parse(2)")); } } @@ -1119,11 +1119,11 @@ void IntlTestDecimalFormatAPI::testErrorCode() { assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status); status = U_INTERNAL_PROGRAM_ERROR; - df->format((int32_t)666, dest, nullptr, status); + df->format(static_cast(666), dest, nullptr, status); assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status); status = U_INTERNAL_PROGRAM_ERROR; - df->format((int64_t)666, dest, nullptr, status); + df->format(static_cast(666), dest, nullptr, status); assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status); status = U_INTERNAL_PROGRAM_ERROR; diff --git a/icu4c/source/test/intltest/dtfmapts.cpp b/icu4c/source/test/intltest/dtfmapts.cpp index d95f6a3217ca..99bf8d24a3f2 100644 --- a/icu4c/source/test/intltest/dtfmapts.cpp +++ b/icu4c/source/test/intltest/dtfmapts.cpp @@ -171,13 +171,13 @@ if (fr != nullptr && it != nullptr && de != nullptr) if(U_FAILURE(status)) { errln("ERROR: format() failed (French)"); } - logln( (UnicodeString) "" + d + " formatted to " + res1); + logln(UnicodeString("") + d + " formatted to " + res1); res2 = it->format(d, res2, pos2); - logln( (UnicodeString) "" + d + " formatted to " + res2); + logln(UnicodeString("") + d + " formatted to " + res2); res3 = de->format(d, res3); - logln( (UnicodeString) "" + d + " formatted to " + res3); + logln(UnicodeString("") + d + " formatted to " + res3); } // ======= Test parse() @@ -214,7 +214,7 @@ if (fr != nullptr && it != nullptr && de != nullptr) int32_t count = 0; const Locale *locales = DateFormat::getAvailableLocales(count); - logln((UnicodeString) "Got " + count + " locales" ); + logln(UnicodeString("Got ") + count + " locales"); for(int32_t i = 0; i < count; i++) { UnicodeString name; name = locales[i].getName(); @@ -313,8 +313,8 @@ IntlTestDateFormatAPI::TestNameHiding() { sdf.format(dateObj, str, status); sdf.format(dateObj, str, fpos, status); // DateFormat API - sdf.format((UDate)0, str, fpos); - sdf.format((UDate)0, str); + sdf.format(static_cast(0), str, fpos); + sdf.format(static_cast(0), str); sdf.parse(str, status); sdf.parse(str, ppos); sdf.getNumberFormat(); @@ -348,9 +348,9 @@ IntlTestDateFormatAPI::TestNameHiding() { fmt.format(numObj, str, fpos, status); // NumberFormat API fmt.format(2.71828, str); - fmt.format((int32_t)1234567, str); + fmt.format(static_cast(1234567), str); fmt.format(1.41421, str, fpos); - fmt.format((int32_t)9876543, str, fpos); + fmt.format(static_cast(9876543), str, fpos); fmt.parse(str, obj, ppos); fmt.parse(str, obj, status); } else { @@ -368,9 +368,9 @@ IntlTestDateFormatAPI::TestNameHiding() { fmt.format(numObj, str, fpos, status); // NumberFormat API fmt.format(2.71828, str); - fmt.format((int32_t)1234567, str); + fmt.format(static_cast(1234567), str); fmt.format(1.41421, str, fpos); - fmt.format((int32_t)9876543, str, fpos); + fmt.format(static_cast(9876543), str, fpos); fmt.parse(str, obj, ppos); fmt.parse(str, obj, status); } diff --git a/icu4c/source/test/intltest/dtfmrgts.cpp b/icu4c/source/test/intltest/dtfmrgts.cpp index 6aa601e0855b..2fd10e01d874 100644 --- a/icu4c/source/test/intltest/dtfmrgts.cpp +++ b/icu4c/source/test/intltest/dtfmrgts.cpp @@ -78,7 +78,7 @@ void DateFormatRegressionTest::Test4029195() UErrorCode status = U_ZERO_ERROR; UDate today = Calendar::getNow(); - logln((UnicodeString) "today: " + today); + logln(UnicodeString("today: ") + today); SimpleDateFormat *sdf = dynamic_cast(DateFormat::createDateInstance()); if (failure(status, "SimpleDateFormat::createDateInstance")) { @@ -105,7 +105,7 @@ void DateFormatRegressionTest::Test4029195() //try { today = sdf->parse(todayS, status); failure(status, "sdf->parse"); - logln((UnicodeString)"today date: " + today); + logln(UnicodeString("today date: ") + today); /*} catch(Exception e) { logln("Error reparsing date: " + e.getMessage()); }*/ @@ -148,24 +148,24 @@ void DateFormatRegressionTest::Test4052408() errln(UnicodeString(u"Fail: Test broken; Want 5/3/97, 8:55\u202FAM Got ", -1) + str); UnicodeString expected[] = { - (UnicodeString) "", //"ERA_FIELD", - (UnicodeString) "97", //"YEAR_FIELD", - (UnicodeString) "5", //"MONTH_FIELD", - (UnicodeString) "3", //"DATE_FIELD", - (UnicodeString) "", //"HOUR_OF_DAY1_FIELD", - (UnicodeString) "", //"HOUR_OF_DAY0_FIELD", - (UnicodeString) "55", //"MINUTE_FIELD", - (UnicodeString) "", //"SECOND_FIELD", - (UnicodeString) "", //"MILLISECOND_FIELD", - (UnicodeString) "", //"DAY_OF_WEEK_FIELD", - (UnicodeString) "", //"DAY_OF_YEAR_FIELD", - (UnicodeString) "", //"DAY_OF_WEEK_IN_MONTH_FIELD", - (UnicodeString) "", //"WEEK_OF_YEAR_FIELD", - (UnicodeString) "", //"WEEK_OF_MONTH_FIELD", - (UnicodeString) "AM", //"AM_PM_FIELD", - (UnicodeString) "8", //"HOUR1_FIELD", - (UnicodeString) "", //"HOUR0_FIELD", - (UnicodeString) "" //"TIMEZONE_FIELD" + UnicodeString(""), //"ERA_FIELD", + UnicodeString("97"), //"YEAR_FIELD", + UnicodeString("5"), //"MONTH_FIELD", + UnicodeString("3"), //"DATE_FIELD", + UnicodeString(""), //"HOUR_OF_DAY1_FIELD", + UnicodeString(""), //"HOUR_OF_DAY0_FIELD", + UnicodeString("55"), //"MINUTE_FIELD", + UnicodeString(""), //"SECOND_FIELD", + UnicodeString(""), //"MILLISECOND_FIELD", + UnicodeString(""), //"DAY_OF_WEEK_FIELD", + UnicodeString(""), //"DAY_OF_YEAR_FIELD", + UnicodeString(""), //"DAY_OF_WEEK_IN_MONTH_FIELD", + UnicodeString(""), //"WEEK_OF_YEAR_FIELD", + UnicodeString(""), //"WEEK_OF_MONTH_FIELD", + UnicodeString("AM"), //"AM_PM_FIELD", + UnicodeString("8"), //"HOUR1_FIELD", + UnicodeString(""), //"HOUR0_FIELD", + UnicodeString("") //"TIMEZONE_FIELD" }; //Hashtable expected;// = new Hashtable(); @@ -178,24 +178,24 @@ void DateFormatRegressionTest::Test4052408() //StringBuffer buf = new StringBuffer(); UnicodeString fieldNames[] = { - (UnicodeString) "ERA_FIELD", - (UnicodeString) "YEAR_FIELD", - (UnicodeString) "MONTH_FIELD", - (UnicodeString) "DATE_FIELD", - (UnicodeString) "HOUR_OF_DAY1_FIELD", - (UnicodeString) "HOUR_OF_DAY0_FIELD", - (UnicodeString) "MINUTE_FIELD", - (UnicodeString) "SECOND_FIELD", - (UnicodeString) "MILLISECOND_FIELD", - (UnicodeString) "DAY_OF_WEEK_FIELD", - (UnicodeString) "DAY_OF_YEAR_FIELD", - (UnicodeString) "DAY_OF_WEEK_IN_MONTH_FIELD", - (UnicodeString) "WEEK_OF_YEAR_FIELD", - (UnicodeString) "WEEK_OF_MONTH_FIELD", - (UnicodeString) "AM_PM_FIELD", - (UnicodeString) "HOUR1_FIELD", - (UnicodeString) "HOUR0_FIELD", - (UnicodeString) "TIMEZONE_FIELD" + UnicodeString("ERA_FIELD"), + UnicodeString("YEAR_FIELD"), + UnicodeString("MONTH_FIELD"), + UnicodeString("DATE_FIELD"), + UnicodeString("HOUR_OF_DAY1_FIELD"), + UnicodeString("HOUR_OF_DAY0_FIELD"), + UnicodeString("MINUTE_FIELD"), + UnicodeString("SECOND_FIELD"), + UnicodeString("MILLISECOND_FIELD"), + UnicodeString("DAY_OF_WEEK_FIELD"), + UnicodeString("DAY_OF_YEAR_FIELD"), + UnicodeString("DAY_OF_WEEK_IN_MONTH_FIELD"), + UnicodeString("WEEK_OF_YEAR_FIELD"), + UnicodeString("WEEK_OF_MONTH_FIELD"), + UnicodeString("AM_PM_FIELD"), + UnicodeString("HOUR1_FIELD"), + UnicodeString("HOUR0_FIELD"), + UnicodeString("TIMEZONE_FIELD") }; UBool pass = true; @@ -207,9 +207,9 @@ void DateFormatRegressionTest::Test4052408() UnicodeString dst; buf.extractBetween(pos.getBeginIndex(), pos.getEndIndex(), dst); UnicodeString str(dst); - logln((UnicodeString)"" + i + (UnicodeString)": " + fieldNames[i] + - (UnicodeString)", \"" + str + (UnicodeString)"\", " + - pos.getBeginIndex() + (UnicodeString)", " + + logln(UnicodeString("") + i + UnicodeString(": ") + fieldNames[i] + + UnicodeString(", \"") + str + UnicodeString("\", ") + + pos.getBeginIndex() + UnicodeString(", ") + pos.getEndIndex()); UnicodeString exp = expected[i]; if((exp.length() == 0 && str.length() == 0) || str == exp) @@ -252,11 +252,11 @@ void DateFormatRegressionTest::Test4056591() date(1861-1900, UCAL_DECEMBER, 25), }; - UnicodeString strings [] = { - (UnicodeString) "091225", - (UnicodeString) "091224", - (UnicodeString) "091226", - (UnicodeString) "611225" + UnicodeString strings[] = { + UnicodeString("091225"), + UnicodeString("091224"), + UnicodeString("091226"), + UnicodeString("611225") }; /*Object[] DATA = { @@ -364,8 +364,7 @@ void DateFormatRegressionTest::Test4060212() cal->setTime(myDate, status); failure(status, "cal->setTime"); if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get")) - errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) + - " Want 40"); + errln(UnicodeString("Fail: Got ") + cal->get(UCAL_DAY_OF_YEAR, status) + " Want 40"); // this is an odd usage of "ddd" and it doesn't // work now that date values are range checked per #3579. @@ -379,8 +378,7 @@ void DateFormatRegressionTest::Test4060212() cal->setTime(myDate, status); failure(status, "cal->setTime"); if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get")) - errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) + - " Want 40"); + errln(UnicodeString("Fail: Got ") + cal->get(UCAL_DAY_OF_YEAR, status) + " Want 40"); } /** @@ -573,11 +571,11 @@ void DateFormatRegressionTest::Test4073003() dataerrln("FAIL: SimpleDateFormat constructor - %s", u_errorName(ec)); return; } - UnicodeString tests [] = { - (UnicodeString) "12/25/61", - (UnicodeString) "12/25/1961", - (UnicodeString) "4/3/2010", - (UnicodeString) "4/3/10" + UnicodeString tests[] = { + UnicodeString("12/25/61"), + UnicodeString("12/25/1961"), + UnicodeString("4/3/2010"), + UnicodeString("4/3/10") }; UErrorCode status = U_ZERO_ERROR; for(int i= 0; i < 4; i+=2) { @@ -590,9 +588,9 @@ void DateFormatRegressionTest::Test4073003() UnicodeString ss; ss = fmt.format(dd, ss); if (d != dd) - errln((UnicodeString) "Fail: " + d + " != " + dd); + errln(UnicodeString("Fail: ") + d + " != " + dd); if (s != ss) - errln((UnicodeString)"Fail: " + s + " != " + ss); + errln(UnicodeString("Fail: ") + s + " != " + ss); logln("Ok: " + s + " " + d); } } @@ -604,7 +602,7 @@ void DateFormatRegressionTest::Test4089106() { TimeZone *def = TimeZone::createDefault(); //try { - TimeZone *z = new SimpleTimeZone((int)(1.25 * 3600000), "FAKEZONE"); + TimeZone* z = new SimpleTimeZone(static_cast(1.25 * 3600000), "FAKEZONE"); TimeZone::setDefault(*z); UErrorCode status = U_ZERO_ERROR; SimpleDateFormat *f = new SimpleDateFormat(status); @@ -795,10 +793,10 @@ void DateFormatRegressionTest::Test4104136() sdf->applyPattern(pattern); logln("pattern: \"" + pattern + "\""); - UnicodeString strings [] = { - (UnicodeString)"time 10:30", - (UnicodeString) "time 10:x", - (UnicodeString) "time 10x" + UnicodeString strings[] = { + UnicodeString("time 10:30"), + UnicodeString("time 10:x"), + UnicodeString("time 10x") }; ParsePosition ppos [] = { @@ -828,11 +826,11 @@ void DateFormatRegressionTest::Test4104136() UDate d = sdf->parse(text, pos); logln(" text: \"" + text + "\""); logln(" index: %d", pos.getIndex()); - logln((UnicodeString) " result: " + d); + logln(UnicodeString(" result: ") + d); if(pos.getIndex() != finish.getIndex()) errln(UnicodeString("Fail: Expected pos ") + finish.getIndex()); if (! ((d == 0 && exp == -1) || (d == exp))) - errln((UnicodeString) "Fail: Expected result " + exp); + errln(UnicodeString("Fail: Expected result ") + exp); } delete sdf; @@ -906,11 +904,11 @@ void DateFormatRegressionTest::Test4106807() failure(status, "new SimpleDateFormat"); UnicodeString strings [] = { - (UnicodeString) "19980211140000", - (UnicodeString) "19980211140000", - (UnicodeString) "19980211140000", - (UnicodeString) "19980211140000a", - (UnicodeString) "19980211140000 " + UnicodeString("19980211140000"), + UnicodeString("19980211140000"), + UnicodeString("19980211140000"), + UnicodeString("19980211140000a"), + UnicodeString("19980211140000 ") }; /*Object[] data = { @@ -1113,7 +1111,7 @@ void DateFormatRegressionTest::Test4182066() { "09/12/001", }; int32_t STRINGS_COUNT = UPRV_LENGTHOF(STRINGS); - UDate FAIL_DATE = (UDate) 0; + UDate FAIL_DATE = static_cast(0); UDate DATES[] = { date(2000-1900, UCAL_FEBRUARY, 29), date(2001-1900, UCAL_JANUARY, 23), @@ -1229,19 +1227,18 @@ void DateFormatRegressionTest::Test714() } UnicodeString s; - UnicodeString tests = - (UnicodeString) u"7:25:43\u202FAM" ; + UnicodeString tests = UnicodeString(u"7:25:43\u202FAM"); UErrorCode status = U_ZERO_ERROR; fmt->format (d,s); if(U_FAILURE(status)) { - errln((UnicodeString) "Fail, errmsg " + u_errorName(status)); + errln(UnicodeString("Fail, errmsg ") + u_errorName(status)); return; } if(s != tests) { - errln((UnicodeString) "Fail: " + s + " != " + tests); + errln(UnicodeString("Fail: ") + s + " != " + tests); } else { @@ -1354,7 +1351,7 @@ void DateFormatRegressionTest::Test1684() UDate ms2 = cal->getTime(status); if (ms2 != ms) { - errln((UnicodeString)"\nError: GregorianUCAL_DOM gave " + ms + + errln(UnicodeString("\nError: GregorianUCAL_DOM gave ") + ms + "\n GregorianUCAL_WOM gave " + ms2); error++; } else { @@ -1367,7 +1364,7 @@ void DateFormatRegressionTest::Test1684() } if (ms2!=ms) { - errln((UnicodeString)"\nError: GregorianCalendar gave " + ms + + errln(UnicodeString("\nError: GregorianCalendar gave ") + ms + "\n SimpleDateFormat.parse gave " + ms2); error++; } else { @@ -1388,12 +1385,12 @@ void DateFormatRegressionTest::Test1684() UDate ms3; ms3 = sdf->parse(result, status); if(U_FAILURE(status)) { - errln("parse exception 2: " + (UnicodeString)u_errorName(status)); + errln("parse exception 2: " + UnicodeString(u_errorName(status))); } if (ms3!=ms) { error++; - errln((UnicodeString)"\nError: Re-parse of '" + result + "' gave time of " + + errln(UnicodeString("\nError: Re-parse of '") + result + "' gave time of " + "\n " + ms3 + "\n not " + ms); } else { diff --git a/icu4c/source/test/intltest/dtfmtrtts.cpp b/icu4c/source/test/intltest/dtfmtrtts.cpp index e5d0ff7d08bc..1f24f7cc3de5 100644 --- a/icu4c/source/test/intltest/dtfmtrtts.cpp +++ b/icu4c/source/test/intltest/dtfmtrtts.cpp @@ -225,7 +225,7 @@ void DateFormatRoundTripTest::test(const Locale& loc) // If we have some sparseness, implement it here. Sparseness decreases // test time by eliminating some tests, up to 23. for(i = 0; i < SPARSENESS; ) { - int random = (int)(randFraction() * 24); + int random = static_cast(randFraction() * 24); if (random >= 0 && random < 24 && TEST_TABLE[i]) { TEST_TABLE[i] = false; ++i; @@ -236,10 +236,10 @@ void DateFormatRoundTripTest::test(const Locale& loc) int32_t style = 0; for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) { if(TEST_TABLE[itable++]) { - logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style))); - DateFormat *df = DateFormat::createDateInstance((DateFormat::EStyle)style, loc); + logln("Testing style " + UnicodeString(styleName(static_cast(style)))); + DateFormat* df = DateFormat::createDateInstance(static_cast(style), loc); if(df == nullptr) { - errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp)); + errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName(static_cast(style))) + " Locale: " + loc.getDisplayName(temp)); } else { test(df, loc); delete df; @@ -249,10 +249,10 @@ void DateFormatRoundTripTest::test(const Locale& loc) for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) { if (TEST_TABLE[itable++]) { - logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style))); - DateFormat *df = DateFormat::createTimeInstance((DateFormat::EStyle)style, loc); + logln("Testing style " + UnicodeString(styleName(static_cast(style)))); + DateFormat* df = DateFormat::createTimeInstance(static_cast(style), loc); if(df == nullptr) { - errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp)); + errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName(static_cast(style))) + " Locale: " + loc.getDisplayName(temp)); } else { test(df, loc, true); delete df; @@ -263,10 +263,10 @@ void DateFormatRoundTripTest::test(const Locale& loc) for(int32_t dstyle = DateFormat::FULL; dstyle <= DateFormat::SHORT; ++dstyle) { for(int32_t tstyle = DateFormat::FULL; tstyle <= DateFormat::SHORT; ++tstyle) { if(TEST_TABLE[itable++]) { - logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) ); - DateFormat *df = DateFormat::createDateTimeInstance((DateFormat::EStyle)dstyle, (DateFormat::EStyle)tstyle, loc); + logln("Testing dstyle" + UnicodeString(styleName(static_cast(dstyle))) + ", tstyle" + UnicodeString(styleName(static_cast(tstyle)))); + DateFormat* df = DateFormat::createDateTimeInstance(static_cast(dstyle), static_cast(tstyle), loc); if(df == nullptr) { - dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) + "Locale: " + loc.getDisplayName(temp)); + dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName(static_cast(dstyle))) + ", tstyle" + UnicodeString(styleName(static_cast(tstyle))) + "Locale: " + loc.getDisplayName(temp)); } else { test(df, loc); delete df; @@ -287,12 +287,12 @@ void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UB UBool isGregorian = false; UErrorCode minStatus = U_ZERO_ERROR; if(fmt->getCalendar() == nullptr) { - errln((UnicodeString)"DateFormatRoundTripTest::test, DateFormat getCalendar() returns null for " + origLocale.getName()); + errln(UnicodeString("DateFormatRoundTripTest::test, DateFormat getCalendar() returns null for ") + origLocale.getName()); return; } UDate minDate = CalendarTest::minDateOfCalendar(*fmt->getCalendar(), isGregorian, minStatus); if(U_FAILURE(minStatus)) { - errln((UnicodeString)"Failure getting min date for " + origLocale.getName()); + errln(UnicodeString("Failure getting min date for ") + origLocale.getName()); return; } //logln(UnicodeString("Min date is ") + fullFormat(minDate) + " for " + origLocale.getName()); @@ -518,7 +518,7 @@ void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UB const UnicodeString& DateFormatRoundTripTest::fullFormat(UDate d) { UErrorCode ec = U_ZERO_ERROR; if (dateFormat == nullptr) { - dateFormat = new SimpleDateFormat((UnicodeString)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", ec); + dateFormat = new SimpleDateFormat(UnicodeString("EEE MMM dd HH:mm:ss.SSS zzz yyyy G"), ec); if (U_FAILURE(ec) || dateFormat == nullptr) { fgStr = "[FAIL: SimpleDateFormat constructor]"; delete dateFormat; @@ -539,7 +539,7 @@ int32_t DateFormatRoundTripTest::getField(UDate d, int32_t f) { UErrorCode status = U_ZERO_ERROR; getFieldCal->setTime(d, status); failure(status, "getfieldCal->setTime"); - int32_t ret = getFieldCal->get((UCalendarDateFields)f, status); + int32_t ret = getFieldCal->get(static_cast(f), status); failure(status, "getfieldCal->get"); return ret; } diff --git a/icu4c/source/test/intltest/dtfmtrtts.h b/icu4c/source/test/intltest/dtfmtrtts.h index d1d960ce853d..55447df9440a 100644 --- a/icu4c/source/test/intltest/dtfmtrtts.h +++ b/icu4c/source/test/intltest/dtfmtrtts.h @@ -51,8 +51,8 @@ class DateFormatRoundTripTest : public IntlTest { static uint32_t randLong() { // The portable IntlTest::random() function has sufficient // resolution for a 16-bit value, but not for 32 bits. - return ((uint32_t) (IntlTest::random() * (1<<16))) | - (((uint32_t) (IntlTest::random() * (1<<16))) << 16); + return static_cast(IntlTest::random() * (1 << 16)) | + (static_cast(IntlTest::random() * (1 << 16)) << 16); } /** @@ -60,7 +60,7 @@ static uint32_t randLong() { **/ static double randFraction() { - return (double)randLong() / (double)0xFFFFFFFF; + return static_cast(randLong()) / static_cast(0xFFFFFFFF); } /** diff --git a/icu4c/source/test/intltest/dtfmttst.cpp b/icu4c/source/test/intltest/dtfmttst.cpp index 049b7be09ab7..2e49cf4d49d4 100644 --- a/icu4c/source/test/intltest/dtfmttst.cpp +++ b/icu4c/source/test/intltest/dtfmttst.cpp @@ -266,7 +266,7 @@ void DateFormatTest::TestWallyWedel() * Instantiate a SimpleDateFormat set up to produce a full time zone name. */ - SimpleDateFormat *sdf = new SimpleDateFormat((UnicodeString)"zzzz", status); + SimpleDateFormat* sdf = new SimpleDateFormat(UnicodeString("zzzz"), status); /* * A String array for the time zone ids. */ @@ -308,8 +308,8 @@ void DateFormatTest::TestWallyWedel() hours = offset/3600000; minutes = (offset%3600000)/60000; seconds = (offset%60000)/1000; - UnicodeString dstOffset = (UnicodeString)"" + sign + (hours < 10 ? "0" : "") + - (int32_t)hours + ":" + (minutes < 10 ? "0" : "") + (int32_t)minutes; + UnicodeString dstOffset = UnicodeString("") + sign + (hours < 10 ? "0" : "") + + hours + ":" + (minutes < 10 ? "0" : "") + minutes; if (seconds != 0) { dstOffset = dstOffset + ":" + (seconds < 10 ? "0" : "") + seconds; } @@ -373,7 +373,7 @@ DateFormatTest::TestEquals() return; } - if (!(*fmtA == *fmtB)) errln((UnicodeString)"FAIL"); + if (!(*fmtA == *fmtB)) errln(UnicodeString("FAIL")); delete fmtA; delete fmtB; @@ -390,8 +390,8 @@ void DateFormatTest::TestTwoDigitYearDSTParse() { UErrorCode status = U_ZERO_ERROR; - SimpleDateFormat fullFmt((UnicodeString)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", status); - SimpleDateFormat fmt((UnicodeString)"dd-MMM-yy h:mm:ss 'o''clock' a z", Locale::getEnglish(), status); + SimpleDateFormat fullFmt(UnicodeString("EEE MMM dd HH:mm:ss.SSS zzz yyyy G"), status); + SimpleDateFormat fmt(UnicodeString("dd-MMM-yy h:mm:ss 'o''clock' a z"), Locale::getEnglish(), status); //DateFormat* fmt = DateFormat::createDateTimeInstance(DateFormat::MEDIUM, DateFormat::FULL, Locale::ENGLISH); UnicodeString s(u"03-Apr-04 2:20:47 o'clock AM PST"); LocalPointer defaultTZ(TimeZone::createDefault()); @@ -416,15 +416,15 @@ DateFormatTest::TestTwoDigitYearDSTParse() hour += defaultTZ->inDaylightTime(d, status) ? 1 : 0; hr = hr*60*60; if (hr != hour) - errln((UnicodeString)"FAIL: Should parse to hour " + hour + " but got " + hr); + errln(UnicodeString("FAIL: Should parse to hour ") + hour + " but got " + hr); if (U_FAILURE(status)) - errln((UnicodeString)"FAIL: " + (int32_t)status); + errln(UnicodeString("FAIL: ") + static_cast(status)); } // ------------------------------------- -char16_t toHexString(int32_t i) { return (char16_t)(i + (i < 10 ? 0x30 : (0x41 - 10))); } +char16_t toHexString(int32_t i) { return static_cast(i + (i < 10 ? 0x30 : (0x41 - 10))); } UnicodeString& DateFormatTest::escape(UnicodeString& s) @@ -432,10 +432,10 @@ DateFormatTest::escape(UnicodeString& s) UnicodeString buf; for (int32_t i=0; i(0x7F)) buf += c; else { - buf += (char16_t)0x5c; buf += (char16_t)0x55; + buf += static_cast(0x5c); buf += static_cast(0x55); buf += toHexString((c & 0xF000) >> 12); buf += toHexString((c & 0x0F00) >> 8); buf += toHexString((c & 0x00F0) >> 4); @@ -537,7 +537,7 @@ void DateFormatTest::TestFieldPosition() { dateFormats[1] = DateFormat::createDateTimeInstance(DateFormat::kFull, DateFormat::kFull, Locale::getFrance()); // Make the pattern "G y M d..." buf.remove().append(PATTERN_CHARS); - for (j=buf.length()-1; j>=0; --j) buf.insert(j, (char16_t)32/*' '*/); + for (j=buf.length()-1; j>=0; --j) buf.insert(j, static_cast(32) /*' '*/); dateFormats[2] = new SimpleDateFormat(buf, Locale::getUS(), ec); // Make the pattern "GGGG yyyy MMMM dddd..." for (j=buf.length()-1; j>=0; j-=2) { @@ -609,7 +609,7 @@ void DateFormatTest::TestFieldPosition() { } else { logln(" Pattern = ? (not a SimpleDateFormat)"); } - logln((UnicodeString)" Result = " + df->format(aug13, buf.remove())); + logln(UnicodeString(" Result = ") + df->format(aug13, buf.remove())); int32_t expBase = exp; // save for later for (i = 0; i < UDAT_FIELD_COUNT; ++i, ++exp) { @@ -618,7 +618,7 @@ void DateFormatTest::TestFieldPosition() { df->format(aug13, buf, pos); UnicodeString field; buf.extractBetween(pos.getBeginIndex(), pos.getEndIndex(), field); - assertEquals((UnicodeString)"localeidx #" + j + " field #" + i + " " + + assertEquals(UnicodeString("localeidx #") + j + " field #" + i + " " + DATEFORMAT_FIELD_NAMES[i], ctou(EXPECTED[exp]), field); } @@ -635,7 +635,7 @@ void DateFormatTest::TestFieldPosition() { int32_t i = fp.getField(); UnicodeString field; buf.extractBetween(fp.getBeginIndex(), fp.getEndIndex(), field); - assertEquals((UnicodeString)"localeidx #" + j + " field #" + i + " " + + assertEquals(UnicodeString("localeidx #") + j + " field #" + i + " " + DATEFORMAT_FIELD_NAMES[i], ctou(EXPECTED[expBase + i]), field); } @@ -696,7 +696,7 @@ DateFormatTest::TestPartialParse994() tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10", null); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 ", null); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17", null); - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); delete f; } @@ -713,17 +713,17 @@ DateFormatTest::tryPat994(SimpleDateFormat* format, const char* pat, const char* UDate date = format->parse(str, status); if (U_FAILURE(status) || date == null) { - logln((UnicodeString)"ParseException: " + (int32_t)status); - if (expected != null) errln((UnicodeString)"FAIL: Expected " + dateToString(expected)); + logln(UnicodeString("ParseException: ") + static_cast(status)); + if (expected != null) errln(UnicodeString("FAIL: Expected ") + dateToString(expected)); } else { UnicodeString f; (dynamic_cast(format))->format(date, f); logln(UnicodeString(" parse(") + str + ") -> " + dateToString(date)); - logln((UnicodeString)" format -> " + f); + logln(UnicodeString(" format -> ") + f); if (expected == null || - !(date == expected)) errln((UnicodeString)"FAIL: Expected null");//" + expected); + !(date == expected)) errln(UnicodeString("FAIL: Expected null")); //" + expected); if (!(f == str)) errln(UnicodeString("FAIL: Expected ") + str); } //} @@ -764,9 +764,9 @@ DateFormatTest::TestRunTogetherPattern985() if (date2 == 0) then = UnicodeString("Parse stopped at ") + pos.getIndex(); else (dynamic_cast(formatter))->format(date2, then); logln(then); - if (!(date2 == date1)) errln((UnicodeString)"FAIL"); + if (!(date2 == date1)) errln(UnicodeString("FAIL")); delete formatter; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -781,7 +781,7 @@ DateFormatTest::TestRunTogetherPattern917() UErrorCode status = U_ZERO_ERROR; SimpleDateFormat* fmt; UnicodeString myDate; - fmt = new SimpleDateFormat((UnicodeString)"yyyy/MM/dd", status); + fmt = new SimpleDateFormat(UnicodeString("yyyy/MM/dd"), status); if (U_FAILURE(status)) { dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status)); delete fmt; @@ -790,11 +790,11 @@ DateFormatTest::TestRunTogetherPattern917() myDate = "1997/02/03"; testIt917(fmt, myDate, date(97, 2 - 1, 3)); delete fmt; - fmt = new SimpleDateFormat((UnicodeString)"yyyyMMdd", status); + fmt = new SimpleDateFormat(UnicodeString("yyyyMMdd"), status); myDate = "19970304"; testIt917(fmt, myDate, date(97, 3 - 1, 4)); delete fmt; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -804,7 +804,7 @@ DateFormatTest::testIt917(SimpleDateFormat* fmt, UnicodeString& str, UDate expec { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern; - logln((UnicodeString)"pattern=" + fmt->toPattern(pattern) + " string=" + str); + logln(UnicodeString("pattern=") + fmt->toPattern(pattern) + " string=" + str); Formattable o; //try { dynamic_cast(fmt)->parseObject(str, o, status); @@ -814,13 +814,13 @@ DateFormatTest::testIt917(SimpleDateFormat* fmt, UnicodeString& str, UDate expec // e.printStackTrace(); // return; //} - logln((UnicodeString)"Parsed object: " + dateToString(o.getDate())); - if (!(o.getDate() == expected)) errln((UnicodeString)"FAIL: Expected " + dateToString(expected)); + logln(UnicodeString("Parsed object: ") + dateToString(o.getDate())); + if (!(o.getDate() == expected)) errln(UnicodeString("FAIL: Expected ") + dateToString(expected)); UnicodeString formatted; fmt->format(o, formatted, status); - logln((UnicodeString)"Formatted string: " + formatted); - if (!(formatted == str)) errln((UnicodeString)"FAIL: Expected " + str); - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + logln(UnicodeString("Formatted string: ") + formatted); + if (!(formatted == str)) errln(UnicodeString("FAIL: Expected ") + str); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -840,28 +840,28 @@ DateFormatTest::TestCzechMonths459() } UnicodeString pattern; - logln((UnicodeString)"Pattern " + (dynamic_cast(fmt))->toPattern(pattern)); + logln(UnicodeString("Pattern ") + dynamic_cast(fmt)->toPattern(pattern)); UDate june = date(97, UCAL_JUNE, 15); UDate july = date(97, UCAL_JULY, 15); UnicodeString juneStr; fmt->format(june, juneStr); UnicodeString julyStr; fmt->format(july, julyStr); //try { - logln((UnicodeString)"format(June 15 1997) = " + juneStr); + logln(UnicodeString("format(June 15 1997) = ") + juneStr); UDate d = fmt->parse(juneStr, status); UnicodeString s; fmt->format(d, s); int32_t month,yr,day,hr,min,sec; dateToFields(d,yr,month,day,hr,min,sec); - logln((UnicodeString)" -> parse -> " + s + " (month = " + month + ")"); - if (month != UCAL_JUNE) errln((UnicodeString)"FAIL: Month should be June"); - logln((UnicodeString)"format(July 15 1997) = " + julyStr); + logln(UnicodeString(" -> parse -> ") + s + " (month = " + month + ")"); + if (month != UCAL_JUNE) errln(UnicodeString("FAIL: Month should be June")); + logln(UnicodeString("format(July 15 1997) = ") + julyStr); d = fmt->parse(julyStr, status); fmt->format(d, s); dateToFields(d,yr,month,day,hr,min,sec); - logln((UnicodeString)" -> parse -> " + s + " (month = " + month + ")"); - if (month != UCAL_JULY) errln((UnicodeString)"FAIL: Month should be July"); + logln(UnicodeString(" -> parse -> ") + s + " (month = " + month + ")"); + if (month != UCAL_JULY) errln(UnicodeString("FAIL: Month should be July")); //} //catch(ParseException e) { if (U_FAILURE(status)) - errln((UnicodeString)"Exception: " + (int32_t)status); + errln(UnicodeString("Exception: ") + static_cast(status)); //} delete fmt; } @@ -881,7 +881,7 @@ DateFormatTest::TestLetterDPattern212() UDate expLittleD = date(95, 0, 1, 5, 1, 29); UDate expBigD = expLittleD + 39 * 24 * 3600000.0; expLittleD = expBigD; // Expect the same, with default lenient parsing - logln((UnicodeString)"dateString= " + dateString); + logln(UnicodeString("dateString= ") + dateString); SimpleDateFormat *formatter = new SimpleDateFormat(bigD, status); if (U_FAILURE(status)) { dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status)); @@ -890,17 +890,17 @@ DateFormatTest::TestLetterDPattern212() } ParsePosition pos(0); UDate myDate = formatter->parse(dateString, pos); - logln((UnicodeString)"Using " + bigD + " -> " + myDate); - if (myDate != expBigD) errln((UnicodeString)"FAIL: bigD - Expected " + dateToString(expBigD)); + logln(UnicodeString("Using ") + bigD + " -> " + myDate); + if (myDate != expBigD) errln(UnicodeString("FAIL: bigD - Expected ") + dateToString(expBigD)); delete formatter; formatter = new SimpleDateFormat(littleD, status); ASSERT_OK(status); pos = ParsePosition(0); myDate = formatter->parse(dateString, pos); - logln((UnicodeString)"Using " + littleD + " -> " + dateToString(myDate)); - if (myDate != expLittleD) errln((UnicodeString)"FAIL: littleD - Expected " + dateToString(expLittleD)); + logln(UnicodeString("Using ") + littleD + " -> " + dateToString(myDate)); + if (myDate != expLittleD) errln(UnicodeString("FAIL: littleD - Expected ") + dateToString(expLittleD)); delete formatter; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -915,7 +915,7 @@ DateFormatTest::TestDayOfYearPattern195() UDate today = Calendar::getNow(); int32_t year,month,day,hour,min,sec; dateToFields(today,year,month,day,hour,min,sec); UDate expected = date(year, month, day); - logln((UnicodeString)"Test Date: " + dateToString(today)); + logln(UnicodeString("Test Date: ") + dateToString(today)); SimpleDateFormat* sdf = dynamic_cast(DateFormat::createDateInstance()); if (sdf == nullptr){ dataerrln("Error calling DateFormat::createDateInstance()"); @@ -924,7 +924,7 @@ DateFormatTest::TestDayOfYearPattern195() tryPattern(*sdf, today, nullptr, expected); tryPattern(*sdf, today, "G yyyy DDD", expected); delete sdf; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -935,20 +935,20 @@ DateFormatTest::tryPattern(SimpleDateFormat& sdf, UDate d, const char* pattern, UErrorCode status = U_ZERO_ERROR; if (pattern != nullptr) sdf.applyPattern(pattern); UnicodeString thePat; - logln((UnicodeString)"pattern: " + sdf.toPattern(thePat)); + logln(UnicodeString("pattern: ") + sdf.toPattern(thePat)); UnicodeString formatResult; (*dynamic_cast(&sdf)).format(d, formatResult); - logln((UnicodeString)" format -> " + formatResult); + logln(UnicodeString(" format -> ") + formatResult); // try { UDate d2 = sdf.parse(formatResult, status); - logln((UnicodeString)" parse(" + formatResult + ") -> " + dateToString(d2)); - if (d2 != expected) errln((UnicodeString)"FAIL: Expected " + dateToString(expected)); + logln(UnicodeString(" parse(") + formatResult + ") -> " + dateToString(d2)); + if (d2 != expected) errln(UnicodeString("FAIL: Expected ") + dateToString(expected)); UnicodeString format2; (*dynamic_cast(&sdf)).format(d2, format2); - logln((UnicodeString)" format -> " + format2); - if (!(formatResult == format2)) errln((UnicodeString)"FAIL: Round trip drift"); + logln(UnicodeString(" format -> ") + format2); + if (!(formatResult == format2)) errln(UnicodeString("FAIL: Round trip drift")); //} //catch(Exception e) { if (U_FAILURE(status)) - errln((UnicodeString)"Error: " + (int32_t)status); + errln(UnicodeString("Error: ") + static_cast(status)); //} } @@ -961,7 +961,7 @@ void DateFormatTest::TestQuotePattern161() { UErrorCode status = U_ZERO_ERROR; - SimpleDateFormat* formatter = new SimpleDateFormat((UnicodeString)"MM/dd/yyyy 'at' hh:mm:ss a zzz", status); + SimpleDateFormat* formatter = new SimpleDateFormat(UnicodeString("MM/dd/yyyy 'at' hh:mm:ss a zzz"), status); if (U_FAILURE(status)) { dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status)); delete formatter; @@ -970,10 +970,10 @@ DateFormatTest::TestQuotePattern161() UDate currentTime_1 = date(97, UCAL_AUGUST, 13, 10, 42, 28); UnicodeString dateString; (dynamic_cast(formatter))->format(currentTime_1, dateString); UnicodeString exp("08/13/1997 at 10:42:28 AM "); - logln((UnicodeString)"format(" + dateToString(currentTime_1) + ") = " + dateString); - if (0 != dateString.compareBetween(0, exp.length(), exp, 0, exp.length())) errln((UnicodeString)"FAIL: Expected " + exp); + logln(UnicodeString("format(") + dateToString(currentTime_1) + ") = " + dateString); + if (0 != dateString.compareBetween(0, exp.length(), exp, 0, exp.length())) errln(UnicodeString("FAIL: Expected ") + exp); delete formatter; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -1028,7 +1028,7 @@ DateFormatTest::TestBadInput135() longFmt->format(when, format); logln(prefix + "OK: " + format); if (0!=format.compareBetween(0, expected.length(), expected, 0, expected.length())) - errln((UnicodeString)"FAIL: Parse \"" + text + "\", pattern \"" + pattern + "\", expected " + expected + " got " + format); + errln(UnicodeString("FAIL: Parse \"") + text + "\", pattern \"" + pattern + "\", expected " + expected + " got " + format); } //} //catch(ParseException e) { @@ -1044,7 +1044,7 @@ DateFormatTest::TestBadInput135() } delete longFmt; if (U_FAILURE(status)) - errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } static const char* const parseFormats[] = { @@ -1121,11 +1121,11 @@ DateFormatTest::TestBadInput135a() //try { date = dateParse->parse(s, status); if (U_SUCCESS(status)) - errln((UnicodeString)"FAIL: Expected exception during parse"); + errln(UnicodeString("FAIL: Expected exception during parse")); //} //catch(Exception ex) { else - logln((UnicodeString)"Exception during parse: " + (int32_t)status); + logln(UnicodeString("Exception during parse: ") + static_cast(status)); status = U_ZERO_ERROR; //} for (uint32_t i = 0; i < INPUT_LENGTH; i += (PF_LENGTH + 1)) { @@ -1143,7 +1143,7 @@ DateFormatTest::TestBadInput135a() s.extract(0, parsePosition.getIndex(), s1); s.extract(parsePosition.getIndex(), s.length(), s2); if (date == 0) { - errln((UnicodeString)"ERROR: null result fmt=\"" + + errln(UnicodeString("ERROR: null result fmt=\"") + parseFormats[index] + "\" pos=" + parsePosition.getIndex() + " " + s1 + "|" + s2); @@ -1151,9 +1151,9 @@ DateFormatTest::TestBadInput135a() else { UnicodeString result; (dynamic_cast(dateParse))->format(date, result); - logln((UnicodeString)"Parsed \"" + s + "\" using \"" + dateParse->toPattern(thePat) + "\" to: " + result); + logln(UnicodeString("Parsed \"") + s + "\" using \"" + dateParse->toPattern(thePat) + "\" to: " + result); if (expected == nullptr) - errln((UnicodeString)"FAIL: Expected parse failure, got " + result); + errln(UnicodeString("FAIL: Expected parse failure, got ") + result); else if (!(result == expected)) errln(UnicodeString("FAIL: Parse \"") + s + UnicodeString("\", expected ") + expected + UnicodeString(", got ") + result); } @@ -1165,13 +1165,13 @@ DateFormatTest::TestBadInput135a() //} //catch(Exception ex) { if (U_FAILURE(status)) - errln((UnicodeString)"An exception was thrown during parse: " + (int32_t)status); + errln(UnicodeString("An exception was thrown during parse: ") + static_cast(status)); //} } } delete dateParse; if (U_FAILURE(status)) - errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status); + errln(UnicodeString("FAIL: UErrorCode received during test: ") + static_cast(status)); } // ------------------------------------- @@ -1203,11 +1203,11 @@ DateFormatTest::parse2DigitYear(DateFormat& fmt, const char* str, UDate expected UnicodeString thePat; logln(UnicodeString("Parsing \"") + str + "\" with " + (dynamic_cast(&fmt))->toPattern(thePat) + " => " + dateToString(d)); - if (d != expected) errln((UnicodeString)"FAIL: Expected " + expected); + if (d != expected) errln(UnicodeString("FAIL: Expected ") + expected); //} //catch(ParseException e) { if (U_FAILURE(status)) - errln((UnicodeString)"FAIL: Got exception"); + errln(UnicodeString("FAIL: Got exception")); //} } @@ -1223,8 +1223,8 @@ DateFormatTest::TestDateFormatZone061() UDate date; DateFormat *formatter; date= 859248000000.0; - logln((UnicodeString)"Date 1997/3/25 00:00 GMT: " + date); - formatter = new SimpleDateFormat((UnicodeString)"dd-MMM-yyyyy HH:mm", Locale::getUK(), status); + logln(UnicodeString("Date 1997/3/25 00:00 GMT: ") + date); + formatter = new SimpleDateFormat(UnicodeString("dd-MMM-yyyyy HH:mm"), Locale::getUK(), status); if(U_FAILURE(status)) { dataerrln("Failed creating SimpleDateFormat with %s. Quitting test", u_errorName(status)); delete formatter; @@ -1232,15 +1232,15 @@ DateFormatTest::TestDateFormatZone061() } formatter->adoptTimeZone(TimeZone::createTimeZone("GMT")); UnicodeString temp; formatter->format(date, temp); - logln((UnicodeString)"Formatted in GMT to: " + temp); + logln(UnicodeString("Formatted in GMT to: ") + temp); //try { UDate tempDate = formatter->parse(temp, status); - logln((UnicodeString)"Parsed to: " + dateToString(tempDate)); - if (tempDate != date) errln((UnicodeString)"FAIL: Expected " + dateToString(date)); + logln(UnicodeString("Parsed to: ") + dateToString(tempDate)); + if (tempDate != date) errln(UnicodeString("FAIL: Expected ") + dateToString(date)); //} //catch(Throwable t) { if (U_FAILURE(status)) - errln((UnicodeString)"Date Formatter throws: " + (int32_t)status); + errln(UnicodeString("Date Formatter throws: ") + static_cast(status)); //} delete formatter; } @@ -1338,7 +1338,7 @@ DateFormatTest::TestLocaleDateFormat() // Bug 495 UnicodeString expectedFRENCH ( u"lundi 15 septembre 1997 à 00:00:00 heure d’été du Pacifique nord-américain", -1 ); expectedFRENCH = expectedFRENCH.unescape(); UnicodeString expectedUS ( u"Monday, September 15, 1997 at 12:00:00\u202FAM Pacific Daylight Time", -1 ); - logln((UnicodeString)"Date set to : " + dateToString(testDate)); + logln(UnicodeString("Date set to : ") + dateToString(testDate)); UnicodeString out; if (dfUS == nullptr || dfFrench == nullptr){ dataerrln("Error calling DateFormat::createDateTimeInstance)"); @@ -1348,14 +1348,14 @@ DateFormatTest::TestLocaleDateFormat() // Bug 495 } dfFrench->format(testDate, out); - logln((UnicodeString)"Date Formatted with French Locale " + out); + logln(UnicodeString("Date Formatted with French Locale ") + out); if (!(out == expectedFRENCH)) - errln((UnicodeString)"FAIL: Expected " + expectedFRENCH + ", got " + out); + errln(UnicodeString("FAIL: Expected ") + expectedFRENCH + ", got " + out); out.truncate(0); dfUS->format(testDate, out); - logln((UnicodeString)"Date Formatted with US Locale " + out); + logln(UnicodeString("Date Formatted with US Locale ") + out); if (!(out == expectedUS)) - errln((UnicodeString)"FAIL: Expected " + expectedUS + ", got " + out); + errln(UnicodeString("FAIL: Expected ") + expectedUS + ", got " + out); delete dfUS; delete dfFrench; } @@ -1366,7 +1366,7 @@ DateFormatTest::TestFormattingLocaleTimeSeparator() // This test not as useful as it once was, since timeSeparator // in the Arabic locale is changed back to ":" in CLDR 28. const UDate testDate = 874266720000.; // Sun Sep 14 21:52:00 CET 1997 - logln((UnicodeString)"Date set to : " + dateToString(testDate)); + logln(UnicodeString("Date set to : ") + dateToString(testDate)); const LocalPointer tz(TimeZone::createTimeZone("CET")); @@ -1436,7 +1436,7 @@ void DateFormatTest::TestDateFormatCalendar() { /* Create a calendar */ cal = Calendar::createInstance(Locale::getUS(), ec); if (cal == nullptr || U_FAILURE(ec)) { - errln((UnicodeString)"FAIL: Calendar::createInstance failed with " + + errln(UnicodeString("FAIL: Calendar::createInstance failed with ") + u_errorName(ec)); goto FAIL; } @@ -1447,7 +1447,7 @@ void DateFormatTest::TestDateFormatCalendar() { pos.setIndex(0); date->parse(str, *cal, pos); if (pos.getIndex() != str.length()) { - errln((UnicodeString)"FAIL: DateFormat::parse(4/5/2001) failed at " + + errln(UnicodeString("FAIL: DateFormat::parse(4/5/2001) failed at ") + pos.getIndex()); goto FAIL; } @@ -1457,7 +1457,7 @@ void DateFormatTest::TestDateFormatCalendar() { pos.setIndex(0); time->parse(str, *cal, pos); if (pos.getIndex() != str.length()) { - errln((UnicodeString)"FAIL: DateFormat::parse(17:45) failed at " + + errln(UnicodeString("FAIL: DateFormat::parse(17:45) failed at ") + pos.getIndex()); goto FAIL; } @@ -1465,7 +1465,7 @@ void DateFormatTest::TestDateFormatCalendar() { /* Check result */ when = cal->getTime(ec); if (U_FAILURE(ec)) { - errln((UnicodeString)"FAIL: cal->getTime() failed with " + u_errorName(ec)); + errln(UnicodeString("FAIL: cal->getTime() failed with ") + u_errorName(ec)); goto FAIL; } str.truncate(0); @@ -1578,7 +1578,7 @@ void DateFormatTest::TestInvalidPattern() { } UnicodeString out; FieldPosition pos; - f.format((UDate)0, out, pos); + f.format(static_cast(0), out, pos); logln(out); // The bug is that the call to format() will crash. By not // crashing, the test passes. @@ -1944,7 +1944,7 @@ void DateFormatTest::TestQuarters() */ void DateFormatTest::expectParse(const char** data, int32_t data_length, const Locale& loc) { - const UDate FAIL = (UDate) -1; + const UDate FAIL = static_cast(-1); const UnicodeString FAIL_STR("parse failure"); int32_t i = 0; @@ -1992,10 +1992,10 @@ void DateFormatTest::expectParse(const char** data, int32_t data_length, } if (got == exp) { - logln((UnicodeString)"Ok: " + input + " x " + + logln(UnicodeString("Ok: ") + input + " x " + currentPat + " => " + gotstr); } else { - errln((UnicodeString)"FAIL: " + input + " x " + + errln(UnicodeString("FAIL: ") + input + " x " + currentPat + " => " + gotstr + ", expected " + expstr); } @@ -2057,7 +2057,7 @@ void DateFormatTest::expect(const char** data, int32_t data_length, const char* string = data[i++]; UDate date = ref.parse(ctou(datestr), ec); if (!assertSuccess("parse", ec)) return; - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", ctou(string), fmt.format(date, str.remove())); // 'p' @@ -2065,8 +2065,8 @@ void DateFormatTest::expect(const char** data, int32_t data_length, date = ref.parse(ctou(datestr), ec); if (!assertSuccess("parse", ec)) return; UDate parsedate = fmt.parse(ctou(string), ec); - if (assertSuccess((UnicodeString)"\"" + currentPat + "\".parse(" + string + ")", ec)) { - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", + if (assertSuccess(UnicodeString("\"") + currentPat + "\".parse(" + string + ")", ec)) { + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", univ.format(date, str.remove()), univ.format(parsedate, str2.remove())); } @@ -2079,14 +2079,14 @@ void DateFormatTest::expect(const char** data, int32_t data_length, UDate date = ref.parse(ctou(datestr), ec); if (!assertSuccess("parse", ec)) return; UDate parsedate = fmt.parse(ctou(string), ec); - if (assertSuccess((UnicodeString)"\"" + currentPat + "\".parse(" + string + ")", ec)) { - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", + if (assertSuccess(UnicodeString("\"") + currentPat + "\".parse(" + string + ")", ec)) { + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", univ.format(date, str.remove()), univ.format(parsedate, str2.remove())); } // 'f' string = data[i++]; - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", ctou(string), fmt.format(date, str.remove())); } @@ -2096,20 +2096,20 @@ void DateFormatTest::expect(const char** data, int32_t data_length, const char* string = data[i++]; UDate date = ref.parse(ctou(datestr), ec); if (!assertSuccess("parse", ec)) return; - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", ctou(string), fmt.format(date, str.remove())); UDate parsedate = fmt.parse(string, ec); - if (assertSuccess((UnicodeString)"\"" + currentPat + "\".parse(" + string + ")", ec)) { - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", + if (assertSuccess(UnicodeString("\"") + currentPat + "\".parse(" + string + ")", ec)) { + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".parse(" + string + ")", univ.format(date, str.remove()), univ.format(parsedate, str2.remove())); } } else { - errln((UnicodeString)"FAIL: Invalid control string " + control); + errln(UnicodeString("FAIL: Invalid control string ") + control); return; } } @@ -2158,7 +2158,7 @@ void DateFormatTest::expectFormat(const char** data, int32_t data_length, const char* string = data[i++]; UDate date = ref.parse(ctou(datestr), ec); if (!assertSuccess("parse", ec)) return; - assertEquals((UnicodeString)"loc " + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", + assertEquals(UnicodeString("loc ") + ctou(loc.getName()) + " \"" + currentPat + "\".format(" + datestr + ")", ctou(string), fmt.format(date, str.remove())); } @@ -2277,15 +2277,15 @@ void DateFormatTest::TestGenericTime() { UDate t = formats[k].parse(test, status); if (U_SUCCESS(status)) { if (d != t) { - errln((UnicodeString)"FAIL: format " + k + + errln(UnicodeString("FAIL: format ") + k + " incorrectly parsed output of format " + j + " (" + test + "), returned " + dateToString(t) + " instead of " + dateToString(d)); } else { - logln((UnicodeString)"OK: format " + k + " parsed ok"); + logln(UnicodeString("OK: format ") + k + " parsed ok"); } } else if (status == U_PARSE_ERROR) { - errln((UnicodeString)"FAIL: format " + k + + errln(UnicodeString("FAIL: format ") + k + " could not parse output of format " + j + " (" + test + ")"); } @@ -3602,7 +3602,7 @@ void DateFormatTest::TestRoundtripWithCalendar() { // we should get the same result. formatters[i]->format(*calendars[j], buf, fpos); if (refStr != buf) { - errln((UnicodeString)"FAIL: Different format result with a different calendar for the same time -" + errln(UnicodeString("FAIL: Different format result with a different calendar for the same time -") + "\n Reference calendar type=" + calendars[i]->getType() + "\n Another calendar type=" + calendars[j]->getType() + "\n Expected result=" + refStr @@ -3634,7 +3634,7 @@ void DateFormatTest::TestRoundtripWithCalendar() { if (calendars[i]->getTime(status) != calendars[j]->getTime(status) || calendars[i]->getTimeZone() != calendars[j]->getTimeZone()) { UnicodeString tzid; - errln((UnicodeString)"FAIL: Different parse result with a different calendar for the same string -" + errln(UnicodeString("FAIL: Different parse result with a different calendar for the same string -") + "\n Reference calendar type=" + calendars[i]->getType() + "\n Another calendar type=" + calendars[j]->getType() + "\n Date string=" + refStr @@ -3645,7 +3645,7 @@ void DateFormatTest::TestRoundtripWithCalendar() { } } if (U_FAILURE(status)) { - errln((UnicodeString)"FAIL: " + u_errorName(status)); + errln(UnicodeString("FAIL: ") + u_errorName(status)); break; } } @@ -3701,7 +3701,7 @@ void DateFormatTest::Test6338() logln(str11); if (str1 != str11) { - errln((UnicodeString)"FAIL: Different dates str1:" + str1 + errln(UnicodeString("FAIL: Different dates str1:") + str1 + " str2:" + str11); } @@ -3724,7 +3724,7 @@ void DateFormatTest::Test6338() logln(str22); if (str2 != str22) { - errln((UnicodeString)"FAIL: Different dates str1:" + str2 + errln(UnicodeString("FAIL: Different dates str1:") + str2 + " str2:" + str22); } @@ -3747,7 +3747,7 @@ void DateFormatTest::Test6338() logln(str33); if (str3 != str33) { - errln((UnicodeString)"FAIL: Different dates str1:" + str3 + errln(UnicodeString("FAIL: Different dates str1:") + str3 + " str2:" + str33); } @@ -3770,7 +3770,7 @@ void DateFormatTest::Test6338() logln(str44); if (str4 != str44) { - errln((UnicodeString)"FAIL: Different dates str1:" + str4 + errln(UnicodeString("FAIL: Different dates str1:") + str4 + " str2:" + str44); } @@ -3807,12 +3807,12 @@ void DateFormatTest::Test6726() logln("strm.charAt(10)=%04X wanted 0x20\n", strm.charAt(10)); - if (strm.charAt(10) != char16_t(0x0020)) { - errln((UnicodeString)"FAIL: Improper formatted date: " + strm ); + if (strm.charAt(10) != static_cast(0x0020)) { + errln(UnicodeString("FAIL: Improper formatted date: ") + strm); } logln("strs.charAt(10)=%04X wanted 0x20\n", strs.charAt(8)); - if (strs.charAt(10) != char16_t(0x0020)) { - errln((UnicodeString)"FAIL: Improper formatted date: " + strs); + if (strs.charAt(10) != static_cast(0x0020)) { + errln(UnicodeString("FAIL: Improper formatted date: ") + strs); } delete fmtf; @@ -4011,7 +4011,7 @@ void DateFormatTest::TestISOEra() { // check that roundtrip worked as expected UnicodeString expected = data[i+1]; if (out != expected) { - dataerrln((UnicodeString)"FAIL: " + in + " -> " + out + " expected -> " + expected); + dataerrln(UnicodeString("FAIL: ") + in + " -> " + out + " expected -> " + expected); } } @@ -4037,7 +4037,7 @@ void DateFormatTest::TestFormalChineseDate() { UnicodeString expected = "\\u4e8c\\u3007\\u3007\\u4e5d\\u5e74\\u4e03\\u6708\\u4e8c\\u5341\\u516b\\u65e5"; expected = expected.unescape(); if (result != expected) { - dataerrln((UnicodeString)"FAIL: -> " + result + " expected -> " + expected); + dataerrln(UnicodeString("FAIL: -> ") + result + " expected -> " + expected); } UDate parsedate = sdf.parse(expected,status); @@ -4047,7 +4047,7 @@ void DateFormatTest::TestFormalChineseDate() { UnicodeString parsedres,expres; usf.format(parsedate,parsedres,pos); usf.format(thedate,expres,pos); - dataerrln((UnicodeString)"FAIL: parsed -> " + parsedres + " expected -> " + expres); + dataerrln(UnicodeString("FAIL: parsed -> ") + parsedres + " expected -> " + expres); } } @@ -4064,7 +4064,7 @@ void DateFormatTest::TestStandAloneGMTParse() { ParsePosition pos(0); sdf.parse(inText, pos); if (pos.getIndex() != 3) { - errln((UnicodeString)"FAIL: Incorrect output parse position: actual=" + pos.getIndex() + " expected=3"); + errln(UnicodeString("FAIL: Incorrect output parse position: actual=") + pos.getIndex() + " expected=3"); } } @@ -4202,7 +4202,7 @@ void DateFormatTest::TestMonthPatterns() for (itemPtr = items; itemPtr->locale != nullptr; itemPtr++ ) { Locale locale = Locale::createFromName(itemPtr->locale); DateFormat * dmft = (itemPtr->style >= 0)? - DateFormat::createDateInstance((DateFormat::EStyle)itemPtr->style, locale): + DateFormat::createDateInstance(static_cast(itemPtr->style), locale): new SimpleDateFormat(customPatterns[-itemPtr->style - 1], locale, status); if ( dmft != nullptr ) { if (U_SUCCESS(status)) { @@ -4281,7 +4281,7 @@ void DateFormatTest::TestContext() { "cs", UnicodeString("LLLL y"), UDISPCTX_CAPITALIZATION_FOR_STANDALONE, CharsToUnicodeString("\\u010Dervenec 2008") }, #endif // terminator - { nullptr, UnicodeString(""), (UDisplayContext)0, UnicodeString("") } + { nullptr, UnicodeString(""), static_cast(0), UnicodeString("") } }; UErrorCode status = U_ZERO_ERROR; Calendar* cal = Calendar::createInstance(status); @@ -4303,8 +4303,8 @@ void DateFormatTest::TestContext() sdmft->format(*cal, result, pos); if (result.compare(itemPtr->expectedFormat) != 0) { errln(UnicodeString("FAIL: format for locale ") + UnicodeString(itemPtr->locale) + - ", status " + (int)status + - ", capitalizationContext " + (int)itemPtr->capitalizationContext + + ", status " + static_cast(status) + + ", capitalizationContext " + static_cast(itemPtr->capitalizationContext) + ", expected " + itemPtr->expectedFormat + ", got " + result); } } @@ -4790,10 +4790,10 @@ void DateFormatTest::TestParseLeniencyAPIs() { void DateFormatTest::TestNumberFormatOverride() { UErrorCode status = U_ZERO_ERROR; - UnicodeString fields = (UnicodeString) "M"; + UnicodeString fields = UnicodeString("M"); LocalPointer fmt; - fmt.adoptInsteadAndCheckErrorCode(new SimpleDateFormat((UnicodeString)"MM d", status), status); + fmt.adoptInsteadAndCheckErrorCode(new SimpleDateFormat(UnicodeString("MM d"), status), status); if (!assertSuccess("SimpleDateFormat with pattern MM d", status)) { return; } @@ -4805,7 +4805,7 @@ void DateFormatTest::TestNumberFormatOverride() { fmt->adoptNumberFormat(fields, check_nf, status); assertSuccess("adoptNumberFormat check_nf", status); - const NumberFormat* get_nf = fmt->getNumberFormatForField((char16_t)0x004D /*'M'*/); + const NumberFormat* get_nf = fmt->getNumberFormatForField(static_cast(0x004D) /*'M'*/); if (get_nf != check_nf) errln("FAIL: getter and setter do not work"); } NumberFormat* check_nf = NumberFormat::createInstance(Locale("en_US"), status); @@ -4827,7 +4827,7 @@ void DateFormatTest::TestNumberFormatOverride() { fields = DATA[i][0]; LocalPointer fmt; - fmt.adoptInsteadAndCheckErrorCode(new SimpleDateFormat((UnicodeString)"MM d", status), status); + fmt.adoptInsteadAndCheckErrorCode(new SimpleDateFormat(UnicodeString("MM d"), status), status); assertSuccess("SimpleDateFormat with pattern MM d", status); NumberFormat* overrideNF = NumberFormat::createInstance(Locale::createFromName("zh@numbers=hanidays"),status); assertSuccess("NumberFormat zh@numbers=hanidays", status); @@ -4836,18 +4836,18 @@ void DateFormatTest::TestNumberFormatOverride() { continue; } - if (fields == (UnicodeString) "") { // use the one w/o fields + if (fields == UnicodeString("")) { // use the one w/o fields fmt->adoptNumberFormat(overrideNF); - } else if (fields == (UnicodeString) "mixed") { // set 1 field at first but then full override, both(M & d) should be override + } else if (fields == UnicodeString("mixed")) { // set 1 field at first but then full override, both(M & d) should be override NumberFormat* singleOverrideNF = NumberFormat::createInstance(Locale::createFromName("en@numbers=hebr"),status); assertSuccess("NumberFormat en@numbers=hebr", status); - fields = (UnicodeString) "M"; + fields = UnicodeString("M"); fmt->adoptNumberFormat(fields, singleOverrideNF, status); assertSuccess("adoptNumberFormat singleOverrideNF", status); fmt->adoptNumberFormat(overrideNF); - } else if (fields == (UnicodeString) "Mo"){ // o is invalid field + } else if (fields == UnicodeString("Mo")) { // o is invalid field fmt->adoptNumberFormat(fields, overrideNF, status); if(status == U_INVALID_FORMAT_ERROR) { status = U_ZERO_ERROR; @@ -4862,7 +4862,7 @@ void DateFormatTest::TestNumberFormatOverride() { FieldPosition pos(FieldPosition::DONT_CARE); fmt->format(test_date,result, pos); - UnicodeString expected = ((UnicodeString)DATA[i][1]).unescape(); + UnicodeString expected = (UnicodeString(DATA[i][1])).unescape(); if (result != expected) errln("FAIL: Expected " + expected + " get: " + result); @@ -5712,7 +5712,7 @@ void DateFormatTest::Test20741_ABFields() { FieldPositionIterator fpositer; UnicodeString result; LocalPointer calendar(Calendar::createInstance(TimeZone::createTimeZone(timeZone), status)); - calendar->setTime(UDate(0), status); + calendar->setTime(static_cast(0), status); dateFormat.format(*calendar, result, &fpositer, status); FieldPosition curFieldPosition; diff --git a/icu4c/source/test/intltest/dtifmtts.cpp b/icu4c/source/test/intltest/dtifmtts.cpp index e477f15a4e94..294f1696e4d3 100644 --- a/icu4c/source/test/intltest/dtifmtts.cpp +++ b/icu4c/source/test/intltest/dtifmtts.cpp @@ -1251,7 +1251,7 @@ void DateIntervalFormatTest::expect(const char** data, int32_t data_length) { FieldPosition pos(FieldPosition::DONT_CARE); dtitvfmt->format(&dtitv, str.remove(), pos, ec); if (!assertSuccess("format in expect", ec)) return; - assertEquals((UnicodeString)"\"" + locName + "\\" + oneSkeleton + "\\" + ctou(datestr) + "\\" + ctou(datestr_2) + "\"", ctou(data[i++]), str); + assertEquals(UnicodeString("\"") + locName + "\\" + oneSkeleton + "\\" + ctou(datestr) + "\\" + ctou(datestr_2) + "\"", ctou(data[i++]), str); logln("interval date:" + str + "\"" + locName + "\", " + "\"" + datestr + "\", " @@ -1368,15 +1368,15 @@ void DateIntervalFormatTest::testContext() { fmt->setContext(testItemPtr->context, status); if (U_FAILURE(status)) { errln("setContext failed for locale %s skeleton %s context %04X: %s", - testItemPtr->locale, testItemPtr->skeleton, (unsigned)testItemPtr->context, u_errorName(status)); + testItemPtr->locale, testItemPtr->skeleton, static_cast(testItemPtr->context), u_errorName(status)); } else { UDisplayContext getContext = fmt->getContext(UDISPCTX_TYPE_CAPITALIZATION, status); if (U_FAILURE(status)) { errln("getContext failed for locale %s skeleton %s context %04X: %s", - testItemPtr->locale, testItemPtr->skeleton, (unsigned)testItemPtr->context, u_errorName(status)); + testItemPtr->locale, testItemPtr->skeleton, static_cast(testItemPtr->context), u_errorName(status)); } else if (getContext != testItemPtr->context) { errln("getContext failed for locale %s skeleton %s context %04X: got context %04X", - testItemPtr->locale, testItemPtr->skeleton, (unsigned)testItemPtr->context, (unsigned)getContext); + testItemPtr->locale, testItemPtr->skeleton, static_cast(testItemPtr->context), static_cast(getContext)); } } @@ -1387,7 +1387,7 @@ void DateIntervalFormatTest::testContext() { fmt->format(&interval, getResult, pos, status); if (U_FAILURE(status)) { errln("format failed for locale %s skeleton %s context %04X: %s", - testItemPtr->locale, testItemPtr->skeleton, (unsigned)testItemPtr->context, u_errorName(status)); + testItemPtr->locale, testItemPtr->skeleton, static_cast(testItemPtr->context), u_errorName(status)); continue; } UnicodeString expectResult(true, testItemPtr->expectResult, -1); @@ -1535,7 +1535,7 @@ void DateIntervalFormatTest::expectUserDII(const char** data, FieldPosition pos(FieldPosition::DONT_CARE); dtitvfmt->format(&dtitv, str.remove(), pos, ec); if (!assertSuccess("format in expectUserDII", ec)) return; - assertEquals((UnicodeString)"\"" + locName + "\\" + datestr + "\\" + datestr_2 + "\"", ctou(data[i++]), str); + assertEquals(UnicodeString("\"") + locName + "\\" + datestr + "\\" + datestr_2 + "\"", ctou(data[i++]), str); #ifdef DTIFMTTS_DEBUG char result[1000]; char mesg[1000]; @@ -1755,7 +1755,7 @@ void DateIntervalFormatTest::testTicket11583_2() { if (!assertSuccess("Error create format object", status)) { return; } - DateInterval interval((UDate) 1232364615000.0, (UDate) 1328787015000.0); + DateInterval interval(static_cast(1232364615000.0), static_cast(1328787015000.0)); UnicodeString appendTo; FieldPosition fpos(FieldPosition::DONT_CARE); UnicodeString expected("ene de 2009\\u2009\\u2013\\u2009feb de 2012"); @@ -1857,7 +1857,7 @@ void DateIntervalFormatTest::testTicket12065() { errln("%s:%d DateIntervalFormat and clone are not equal.", __FILE__, __LINE__); return; } - DateInterval interval((UDate) 1232364615000.0, (UDate) 1328787015000.0); + DateInterval interval(static_cast(1232364615000.0), static_cast(1328787015000.0)); UnicodeString appendTo; FieldPosition fpos(FieldPosition::DONT_CARE); formatter->format(&interval, appendTo, fpos, status); @@ -2158,7 +2158,7 @@ void DateIntervalFormatTest::testTicket20707() { FieldPosition fposition; UnicodeString result; LocalPointer calendar(Calendar::createInstance(TimeZone::createTimeZone(timeZone), status)); - calendar->setTime(UDate(1563235200000), status); + calendar->setTime(static_cast(1563235200000), status); dtifmt->format(*calendar, *calendar, result, fposition, status); const char* localeID = locale.getName(); @@ -2408,9 +2408,9 @@ void DateIntervalFormatTest::testTicket20710_FieldIdentity() { IcuTestErrorCode status(*this, "testTicket20710_FieldIdentity"); LocalPointer dtifmt(DateIntervalFormat::createInstance("eeeeMMMddyyhhmma", "de-CH", status)); LocalPointer calendar1(Calendar::createInstance(TimeZone::createTimeZone(u"CET"), status)); - calendar1->setTime(UDate(1563235200000), status); + calendar1->setTime(static_cast(1563235200000), status); LocalPointer calendar2(Calendar::createInstance(TimeZone::createTimeZone(u"CET"), status)); - calendar2->setTime(UDate(1564235200000), status); + calendar2->setTime(static_cast(1564235200000), status); { auto fv = dtifmt->formatToValue(*calendar1, *calendar2, status); @@ -2458,7 +2458,7 @@ void DateIntervalFormatTest::testTicket20710_IntervalIdentity() { const Locale locale = locales[i]; LocalPointer gen(DateTimePatternGenerator::createInstance(locale, status)); LocalPointer calendar(Calendar::createInstance(TimeZone::createTimeZone(timeZone), status)); - calendar->setTime(UDate(1563235200000), status); + calendar->setTime(static_cast(1563235200000), status); for (auto skeleton : skeletons) { LocalPointer dtifmt(DateIntervalFormat::createInstance(skeleton, locale, status)); diff --git a/icu4c/source/test/intltest/dtptngts.cpp b/icu4c/source/test/intltest/dtptngts.cpp index 4ef0fd93446e..bcec7c3f3769 100644 --- a/icu4c/source/test/intltest/dtptngts.cpp +++ b/icu4c/source/test/intltest/dtptngts.cpp @@ -787,7 +787,7 @@ void IntlTestDateTimePatternGeneratorAPI::testAPI(/*char *par*/) UnicodeString randomSkeleton; int32_t len = rand() % 20; for (int32_t j=0; j=(char16_t)0x20) { + while ((newChar = static_cast(rand() % 0x7f)) >= static_cast(0x20)) { randomSkeleton += newChar; } } @@ -1329,7 +1329,13 @@ void IntlTestDateTimePatternGeneratorAPI::testGetFieldDisplayNames() { } } -static const char16_t timeCycleChars[] = { (char16_t)0x0048, (char16_t)0x0068, (char16_t)0x004B, (char16_t)0x006B, (char16_t)0 }; +static const char16_t timeCycleChars[] = { + static_cast(0x0048), + static_cast(0x0068), + static_cast(0x004B), + static_cast(0x006B), + static_cast(0) +}; void IntlTestDateTimePatternGeneratorAPI::testJjMapping() { UErrorCode status = U_ZERO_ERROR; @@ -1395,7 +1401,7 @@ void IntlTestDateTimePatternGeneratorAPI::testJjMapping() { continue; } const char16_t* charPtr = timeCycleChars; - for (; *charPtr != (char16_t)0; charPtr++) { + for (; *charPtr != static_cast(0); charPtr++) { if (jPatSkeleton.indexOf(*charPtr) >= 0) { if (shortPatSkeleton.indexOf(*charPtr) < 0) { char jcBuf[2], spBuf[32], jpBuf[32]; @@ -1717,7 +1723,7 @@ void IntlTestDateTimePatternGeneratorAPI::testDateTimePatterns() { // Test normal getting and setting for (int32_t patStyle = 0; patStyle < kNumDateTimePatterns; patStyle++) { status = U_ZERO_ERROR; - const UnicodeString& dtFormat1 = dtpg->getDateTimeFormat((UDateFormatStyle)patStyle, status); + const UnicodeString& dtFormat1 = dtpg->getDateTimeFormat(static_cast(patStyle), status); if (U_FAILURE(status)) { errln("FAIL: getDateTimeFormat for en before mod, style %d, get %s", patStyle, u_errorName(status)); } else if (dtFormat1 != enDTPatterns[patStyle]) { @@ -1727,11 +1733,11 @@ void IntlTestDateTimePatternGeneratorAPI::testDateTimePatterns() { patStyle, bExpect, bGet); } status = U_ZERO_ERROR; - dtpg->setDateTimeFormat((UDateFormatStyle)patStyle, modDTPatterns[patStyle], status); + dtpg->setDateTimeFormat(static_cast(patStyle), modDTPatterns[patStyle], status); if (U_FAILURE(status)) { errln("FAIL: setDateTimeFormat for en, style %d, get %s", patStyle, u_errorName(status)); } else { - const UnicodeString& dtFormat2 = dtpg->getDateTimeFormat((UDateFormatStyle)patStyle, status); + const UnicodeString& dtFormat2 = dtpg->getDateTimeFormat(static_cast(patStyle), status); if (U_FAILURE(status)) { errln("FAIL: getDateTimeFormat for en after mod, style %d, get %s", patStyle, u_errorName(status)); } else if (dtFormat2 != modDTPatterns[patStyle]) { @@ -1755,7 +1761,7 @@ void IntlTestDateTimePatternGeneratorAPI::testDateTimePatterns() { modDTPatterns[UDAT_SHORT].extract(0, modDTPatterns[UDAT_SHORT].length(), bExpect, 64); for (int32_t patStyle = 0; patStyle < kNumDateTimePatterns; patStyle++) { status = U_ZERO_ERROR; - const UnicodeString& dtFormat4 = dtpg->getDateTimeFormat((UDateFormatStyle)patStyle, status); + const UnicodeString& dtFormat4 = dtpg->getDateTimeFormat(static_cast(patStyle), status); if (U_FAILURE(status)) { errln("FAIL: getDateTimeFormat for en after second mod, style %d, get %s", patStyle, u_errorName(status)); } else if (dtFormat4 != modDTPatterns[UDAT_SHORT]) { diff --git a/icu4c/source/test/intltest/encoll.cpp b/icu4c/source/test/intltest/encoll.cpp index a5af09a93320..d3c791aeac03 100644 --- a/icu4c/source/test/intltest/encoll.cpp +++ b/icu4c/source/test/intltest/encoll.cpp @@ -30,107 +30,107 @@ CollationEnglishTest::~CollationEnglishTest() } static const char16_t testSourceCases[][CollationEnglishTest::MAX_TOKEN_LEN] = { - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x002D /* '-' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0020 /* ' ' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x002D /* '-' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0048 /* 'H' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x006C /* 'l' */, (char16_t)0x006C /* 'l' */, (char16_t)0x006F /* 'o' */, 0}, - {(char16_t)0x0041 /* 'A' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0043 /* 'C' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x002D /* '-' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x002D /* '-' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00EA, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, 0x00E9, 0}, - {0x00C4, (char16_t)0x0042 /* 'B' */, 0x0308, (char16_t)0x0043 /* 'C' */, 0x0308, 0}, - {(char16_t)0x0061 /* 'a' */, 0x0308, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x0072 /* 'r' */, 0}, - {(char16_t)0x0072 /* 'r' */, (char16_t)0x006F /* 'o' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x0073 /* 's' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0041 /* 'A' */, 0}, - {(char16_t)0x0041 /* 'A' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0074 /* 't' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006F /* 'o' */, (char16_t)0x006D /* 'm' */, (char16_t)0x0070 /* 'p' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x0070 /* 'p' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x006E /* 'n' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0023 /* '#' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0023 /* '#' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0041 /* 'A' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00E6, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0048 /* 'H' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, 0x0308, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0074 /* 't' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0069 /* 'i' */, 0x0302, (char16_t)0x0073 /* 's' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00EA, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, 0x00E6, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, 0x00E6, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, 0x00E9, 0} // 49 + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x002D) /* '-' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0020) /* ' ' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x002D) /* '-' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0048) /* 'H' */, static_cast(0x0065) /* 'e' */, static_cast(0x006C) /* 'l' */, static_cast(0x006C) /* 'l' */, static_cast(0x006F) /* 'o' */, 0}, + {static_cast(0x0041) /* 'A' */, static_cast(0x0042) /* 'B' */, static_cast(0x0043) /* 'C' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x002D) /* '-' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x002D) /* '-' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00EA, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, 0x00E9, 0}, + {0x00C4, static_cast(0x0042) /* 'B' */, 0x0308, static_cast(0x0043) /* 'C' */, 0x0308, 0}, + {static_cast(0x0061) /* 'a' */, 0x0308, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, static_cast(0x0072) /* 'r' */, 0}, + {static_cast(0x0072) /* 'r' */, static_cast(0x006F) /* 'o' */, static_cast(0x006C) /* 'l' */, static_cast(0x0065) /* 'e' */, static_cast(0x0073) /* 's' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0041) /* 'A' */, 0}, + {static_cast(0x0041) /* 'A' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0074) /* 't' */, static_cast(0x0063) /* 'c' */, static_cast(0x006F) /* 'o' */, static_cast(0x006D) /* 'm' */, static_cast(0x0070) /* 'p' */, static_cast(0x0061) /* 'a' */, static_cast(0x0072) /* 'r' */, static_cast(0x0065) /* 'e' */, static_cast(0x0070) /* 'p' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0069) /* 'i' */, static_cast(0x006E) /* 'n' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0023) /* '#' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0023) /* '#' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0041) /* 'A' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00E6, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x0048) /* 'H' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, 0x0308, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0074) /* 't' */, static_cast(0x0068) /* 'h' */, static_cast(0x0069) /* 'i' */, 0x0302, static_cast(0x0073) /* 's' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00EA, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, 0x00E6, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, 0x00E6, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, 0x00E9, 0} // 49 }; static const char16_t testTargetCases[][CollationEnglishTest::MAX_TOKEN_LEN] = { - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x002D /* '-' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, 0}, - {(char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x006C /* 'l' */, (char16_t)0x006C /* 'l' */, (char16_t)0x006F /* 'o' */, 0}, - {(char16_t)0x0041 /* 'A' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0043 /* 'C' */, 0}, - {(char16_t)0x0041 /* 'A' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0043 /* 'C' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0073 /* 's' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0073 /* 's' */, 0}, - {(char16_t)0x0062 /* 'b' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x006B /* 'k' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, 0x00E9, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x0072 /* 'r' */, 0}, - {0x00C4, (char16_t)0x0042 /* 'B' */, 0x0308, (char16_t)0x0043 /* 'C' */, 0x0308, 0}, - {(char16_t)0x0041 /* 'A' */, 0x0308, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, 0}, - {(char16_t)0x0072 /* 'r' */, (char16_t)0x006F /* 'o' */, 0x0302, (char16_t)0x006C /* 'l' */, (char16_t)0x0065 /* 'e' */, 0}, - {(char16_t)0x0041 /* 'A' */, 0x00E1, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0041 /* 'A' */, 0x00E1, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0054 /* 'T' */, (char16_t)0x0043 /* 'C' */, (char16_t)0x006F /* 'o' */, (char16_t)0x006D /* 'm' */, (char16_t)0x0070 /* 'p' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0072 /* 'r' */, (char16_t)0x0065 /* 'e' */, (char16_t)0x0050 /* 'P' */, (char16_t)0x006C /* 'l' */, (char16_t)0x0061 /* 'a' */, (char16_t)0x0069 /* 'i' */, (char16_t)0x006E /* 'n' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0023 /* '#' */, (char16_t)0x0042 /* 'B' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0026 /* '&' */, (char16_t)0x0062 /* 'b' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0023 /* '#' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00C4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00C4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {0x00C4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, (char16_t)0x0064 /* 'd' */, (char16_t)0x0061 /* 'a' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0023 /* '#' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x003D /* '=' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0064 /* 'd' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0043 /* 'C' */, (char16_t)0x0048 /* 'H' */, (char16_t)0x0063 /* 'c' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0074 /* 't' */, (char16_t)0x0068 /* 'h' */, 0x00EE, (char16_t)0x0073 /* 's' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00E9, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, 0x00E9, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0043 /* 'C' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0062 /* 'b' */, (char16_t)0x0064 /* 'd' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, 0x00C6, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0064 /* 'd' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, 0x00C6, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0042 /* 'B' */, (char16_t)0x0064 /* 'd' */, 0}, - {0x00E4, (char16_t)0x0062 /* 'b' */, (char16_t)0x0063 /* 'c' */, 0}, - {(char16_t)0x0070 /* 'p' */, 0x00EA, (char16_t)0x0063 /* 'c' */, (char16_t)0x0068 /* 'h' */, (char16_t)0x0065 /* 'e' */, 0} // 49 + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x002D) /* '-' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, 0}, + {static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, static_cast(0x006C) /* 'l' */, static_cast(0x006C) /* 'l' */, static_cast(0x006F) /* 'o' */, 0}, + {static_cast(0x0041) /* 'A' */, static_cast(0x0042) /* 'B' */, static_cast(0x0043) /* 'C' */, 0}, + {static_cast(0x0041) /* 'A' */, static_cast(0x0042) /* 'B' */, static_cast(0x0043) /* 'C' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, static_cast(0x0073) /* 's' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, static_cast(0x0073) /* 's' */, 0}, + {static_cast(0x0062) /* 'b' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0063) /* 'c' */, static_cast(0x006B) /* 'k' */, static_cast(0x0062) /* 'b' */, static_cast(0x0069) /* 'i' */, static_cast(0x0072) /* 'r' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, 0x00E9, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, static_cast(0x0072) /* 'r' */, 0}, + {0x00C4, static_cast(0x0042) /* 'B' */, 0x0308, static_cast(0x0043) /* 'C' */, 0x0308, 0}, + {static_cast(0x0041) /* 'A' */, 0x0308, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, 0}, + {static_cast(0x0072) /* 'r' */, static_cast(0x006F) /* 'o' */, 0x0302, static_cast(0x006C) /* 'l' */, static_cast(0x0065) /* 'e' */, 0}, + {static_cast(0x0041) /* 'A' */, 0x00E1, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0041) /* 'A' */, 0x00E1, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0054) /* 'T' */, static_cast(0x0043) /* 'C' */, static_cast(0x006F) /* 'o' */, static_cast(0x006D) /* 'm' */, static_cast(0x0070) /* 'p' */, static_cast(0x0061) /* 'a' */, static_cast(0x0072) /* 'r' */, static_cast(0x0065) /* 'e' */, static_cast(0x0050) /* 'P' */, static_cast(0x006C) /* 'l' */, static_cast(0x0061) /* 'a' */, static_cast(0x0069) /* 'i' */, static_cast(0x006E) /* 'n' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0042) /* 'B' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0023) /* '#' */, static_cast(0x0042) /* 'B' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0026) /* '&' */, static_cast(0x0062) /* 'b' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0023) /* '#' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00C4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00C4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {0x00C4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, static_cast(0x0064) /* 'd' */, static_cast(0x0061) /* 'a' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0023) /* '#' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x003D) /* '=' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0064) /* 'd' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0043) /* 'C' */, static_cast(0x0048) /* 'H' */, static_cast(0x0063) /* 'c' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0074) /* 't' */, static_cast(0x0068) /* 'h' */, 0x00EE, static_cast(0x0073) /* 's' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00E9, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, 0x00E9, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0042) /* 'B' */, static_cast(0x0043) /* 'C' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0062) /* 'b' */, static_cast(0x0064) /* 'd' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, 0x00C6, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0042) /* 'B' */, static_cast(0x0064) /* 'd' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, 0x00C6, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0042) /* 'B' */, static_cast(0x0064) /* 'd' */, 0}, + {0x00E4, static_cast(0x0062) /* 'b' */, static_cast(0x0063) /* 'c' */, 0}, + {static_cast(0x0070) /* 'p' */, 0x00EA, static_cast(0x0063) /* 'c' */, static_cast(0x0068) /* 'h' */, static_cast(0x0065) /* 'e' */, 0} // 49 }; static const Collator::EComparisonResult results[] = { @@ -233,14 +233,14 @@ static const char16_t testAcute[][CollationEnglishTest::MAX_TOKEN_LEN] = { }; static const char16_t testMore[][CollationEnglishTest::MAX_TOKEN_LEN] = { - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0065 /* 'e' */, 0}, - { 0x00E6, 0}, - { 0x00C6, 0}, - {(char16_t)0x0061 /* 'a' */, (char16_t)0x0066 /* 'f' */, 0}, - {(char16_t)0x006F /* 'o' */, (char16_t)0x0065 /* 'e' */, 0}, - { 0x0153, 0}, - { 0x0152, 0}, - {(char16_t)0x006F /* 'o' */, (char16_t)0x0066 /* 'f' */, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0065) /* 'e' */, 0}, + {0x00E6, 0}, + {0x00C6, 0}, + {static_cast(0x0061) /* 'a' */, static_cast(0x0066) /* 'f' */, 0}, + {static_cast(0x006F) /* 'o' */, static_cast(0x0065) /* 'e' */, 0}, + {0x0153, 0}, + {0x0152, 0}, + {static_cast(0x006F) /* 'o' */, static_cast(0x0066) /* 'f' */, 0}, }; void CollationEnglishTest::TestTertiary(/* char* par */) diff --git a/icu4c/source/test/intltest/fldset.cpp b/icu4c/source/test/intltest/fldset.cpp index 4162d9bb4af1..d68a79c095eb 100644 --- a/icu4c/source/test/intltest/fldset.cpp +++ b/icu4c/source/test/intltest/fldset.cpp @@ -19,7 +19,7 @@ FieldsSet::FieldsSet() { } FieldsSet::FieldsSet(int32_t fieldCount) { - construct((UDebugEnumType)-1, fieldCount); + construct(static_cast(-1), fieldCount); } FieldsSet::FieldsSet(UDebugEnumType field) { @@ -50,7 +50,7 @@ UnicodeString FieldsSet::diffFrom(const FieldsSet& other, UErrorCode& status) co return {"U_ILLEGAL_ARGUMENT_ERROR: FieldsSet of a different type!"}; } for (int i=0; i(i))) { int32_t myVal = get(i); int32_t theirVal = other.get(i); @@ -210,13 +210,13 @@ void FieldsSet::parseValueDefault(const FieldsSet* inheritFrom, int32_t field, c int32_t value = -1; if(substr.length()==0) { // inherit requested // inherit - if((inheritFrom == nullptr) || !inheritFrom->isSet((UCalendarDateFields)field)) { + if ((inheritFrom == nullptr) || !inheritFrom->isSet(static_cast(field))) { // couldn't inherit from field it_errln(UnicodeString("Parse Failed: Couldn't inherit field ") + field + UnicodeString(" [") + UnicodeString(udbg_enumName(fEnum, field)) + UnicodeString("]")); status = U_ILLEGAL_ARGUMENT_ERROR; return; } - value = inheritFrom->get((UCalendarDateFields)field); + value = inheritFrom->get(static_cast(field)); } else { value = udbg_stoi(substr); } @@ -262,9 +262,9 @@ void CalendarFieldsSet::handleParseValue(const FieldsSet* inheritFrom, int32_t f */ void CalendarFieldsSet::setOnCalendar(Calendar *cal, UErrorCode& /*status*/) const { for (int i=0; iset((UCalendarDateFields)i, value); + if (isSet(static_cast(i))) { + int32_t value = get(static_cast(i)); + cal->set(static_cast(i), value); } } } @@ -279,13 +279,13 @@ UBool CalendarFieldsSet::matches(Calendar *cal, CalendarFieldsSet &diffSet, return false; } for (int i=0; iget((UCalendarDateFields)i, status); + if (isSet(static_cast(i))) { + int32_t calVal = cal->get(static_cast(i), status); if (U_FAILURE(status)) return false; - if (calVal != get((UCalendarDateFields)i)) { + if (calVal != get(static_cast(i))) { match = false; - diffSet.set((UCalendarDateFields)i, calVal); + diffSet.set(static_cast(i), calVal); //fprintf(stderr, "match failed: %s#%d=%d != %d\n",udbg_enumName(UDBG_UCalendarDateFields,i),i,cal->get((UCalendarDateFields)i,status), get((UCalendarDateFields)i));; } } @@ -318,7 +318,7 @@ UDateFormatStyle DateTimeStyleSet::getDateStyle() const { if(!isSet(DTS_DATE)) { return UDAT_NONE; } else { - return (UDateFormatStyle)get(DTS_DATE); + return static_cast(get(DTS_DATE)); } } @@ -327,7 +327,7 @@ UDateFormatStyle DateTimeStyleSet::getTimeStyle() const { if(!isSet(DTS_TIME)) { return UDAT_NONE; } else { - return (UDateFormatStyle)get(DTS_TIME); + return static_cast(get(DTS_TIME)); } } diff --git a/icu4c/source/test/intltest/formatted_string_builder_test.cpp b/icu4c/source/test/intltest/formatted_string_builder_test.cpp index 88088b749785..9dcafdff487d 100644 --- a/icu4c/source/test/intltest/formatted_string_builder_test.cpp +++ b/icu4c/source/test/intltest/formatted_string_builder_test.cpp @@ -165,7 +165,7 @@ void FormattedStringBuilderTest::testInsertAppendCodePoint() { assertEquals("Code point count of sb3", 1, sb3.codePointCount()); assertEquals( "First code unit in sb3", - !U_IS_SUPPLEMENTARY(cas) ? (char16_t) cas : U16_LEAD(cas), + !U_IS_SUPPLEMENTARY(cas) ? static_cast(cas) : U16_LEAD(cas), sb3.charAt(0)); UnicodeString sb4; diff --git a/icu4c/source/test/intltest/formattedvaluetest.cpp b/icu4c/source/test/intltest/formattedvaluetest.cpp index d2befe2714d8..8f5284db6f30 100644 --- a/icu4c/source/test/intltest/formattedvaluetest.cpp +++ b/icu4c/source/test/intltest/formattedvaluetest.cpp @@ -157,11 +157,11 @@ void FormattedValueTest::assertAllPartsEqual( context, cfpos.getInt64IterationContext()); assertEquals(messagePrefix + u": integer field", - (UBool) ((matching & 1) != 0), cfpos.matchesField(UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD)); + static_cast((matching & 1) != 0), cfpos.matchesField(UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD)); assertEquals(messagePrefix + u": compact field", - (UBool) ((matching & 2) != 0), cfpos.matchesField(UFIELD_CATEGORY_NUMBER, UNUM_COMPACT_FIELD)); + static_cast((matching & 2) != 0), cfpos.matchesField(UFIELD_CATEGORY_NUMBER, UNUM_COMPACT_FIELD)); assertEquals(messagePrefix + u": date field", - (UBool) ((matching & 4) != 0), cfpos.matchesField(UFIELD_CATEGORY_DATE, UDAT_AM_PM_FIELD)); + static_cast((matching & 4) != 0), cfpos.matchesField(UFIELD_CATEGORY_DATE, UDAT_AM_PM_FIELD)); } diff --git a/icu4c/source/test/intltest/icusvtst.cpp b/icu4c/source/test/intltest/icusvtst.cpp index e8363966b372..f9d981e8c45b 100644 --- a/icu4c/source/test/intltest/icusvtst.cpp +++ b/icu4c/source/test/intltest/icusvtst.cpp @@ -168,7 +168,7 @@ UnicodeString append(UnicodeString& result, const UObject* obj) } else if ((loc = dynamic_cast(obj)) != nullptr) { result.append(loc->getName()); } else if ((i = dynamic_cast(obj)) != nullptr) { - snprintf(buffer, sizeof(buffer), "%d", (int)i->_val); + snprintf(buffer, sizeof(buffer), "%d", static_cast(i->_val)); result.append(buffer); } else { snprintf(buffer, sizeof(buffer), "%p", (const void*)obj); @@ -1048,7 +1048,7 @@ void ICUServiceTest::testLocale() { service.registerInstance(root, "", status); service.registerInstance(german, "de", status); service.registerInstance(germany, Locale::getGermany(), status); - service.registerInstance(japanese, (UnicodeString)"ja", true, status); + service.registerInstance(japanese, UnicodeString("ja"), true, status); service.registerInstance(japan, Locale::getJapan(), status); { diff --git a/icu4c/source/test/intltest/idnaconf.cpp b/icu4c/source/test/intltest/idnaconf.cpp index 8fa1306c9c89..c545f7404d2a 100644 --- a/icu4c/source/test/intltest/idnaconf.cpp +++ b/icu4c/source/test/intltest/idnaconf.cpp @@ -116,7 +116,7 @@ UBool IdnaConfTest::ReadOneLine(UnicodeString& buf){ * and, of course, will shift tail elements. */ void IdnaConfTest::ExplainCodePointTag(UnicodeString& buf){ - buf.append((char16_t)0); // add a terminal NUL + buf.append(static_cast(0)); // add a terminal NUL char16_t* bufBase = buf.getBuffer(buf.length()); char16_t* p = bufBase; while (*p != 0){ @@ -238,7 +238,7 @@ void IdnaConfTest::Test(){ Call(); } else { // explain key:value - int p = s.indexOf((char16_t)0x3A); // : + int p = s.indexOf(static_cast(0x3A)); // : key.setTo(s,0,p).trim(); value.setTo(s,p+1).trim(); if (key.compare(C_TYPE, -1) == 0){ @@ -259,7 +259,7 @@ void IdnaConfTest::Test(){ } else { option = 0; } - id.setTo(value, 0, value.indexOf((char16_t)0x20)); // space + id.setTo(value, 0, value.indexOf(static_cast(0x20))); // space } else if (key.compare(C_NAMEZONE, -1) == 0){ ExplainCodePointTag(value); namezone.setTo(value); diff --git a/icu4c/source/test/intltest/idnaref.cpp b/icu4c/source/test/intltest/idnaref.cpp index 061705cb3e82..92091efeda41 100644 --- a/icu4c/source/test/intltest/idnaref.cpp +++ b/icu4c/source/test/intltest/idnaref.cpp @@ -89,7 +89,7 @@ compareCaseInsensitiveASCII(const char16_t* s1, int32_t s1Len, /* Case-insensitive comparison */ if(c1!=c2) { - rc=(int32_t)toASCIILower(c1)-(int32_t)toASCIILower(c2); + rc = static_cast(toASCIILower(c1)) - static_cast(toASCIILower(c2)); if(rc!=0) { return rc; } @@ -123,7 +123,7 @@ static inline int32_t convertASCIIToUChars(const char* src,char16_t* dest, int32 static inline int32_t convertUCharsToASCII(const char16_t* src,char* dest, int32_t length){ int i; for(i=0;i(src[i]); } return i; } @@ -140,11 +140,11 @@ static int32_t convertToPuny(const char16_t* src, int32_t srcLength, punycode_status error; unsigned char* caseFlags = nullptr; - u_strToUTF32((UChar32*)b1,b1Capacity,&b1Len,src,srcLength,&status); + u_strToUTF32(reinterpret_cast(b1), b1Capacity, &b1Len, src, srcLength, &status); if(status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ - b1 = (uint32_t*) uprv_malloc(b1Len * sizeof(uint32_t)); + b1 = static_cast(uprv_malloc(b1Len * sizeof(uint32_t))); if(b1==nullptr){ status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -152,7 +152,7 @@ static int32_t convertToPuny(const char16_t* src, int32_t srcLength, status = U_ZERO_ERROR; // reset error - u_strToUTF32((UChar32*)b1,b1Len,&b1Len,src,srcLength,&status); + u_strToUTF32(reinterpret_cast(b1), b1Len, &b1Len, src, srcLength, &status); } if(U_FAILURE(status)){ goto CLEANUP; @@ -160,12 +160,12 @@ static int32_t convertToPuny(const char16_t* src, int32_t srcLength, //caseFlags = (unsigned char*) uprv_malloc(b1Len *sizeof(unsigned char)); - error = punycode_encode(b1Len,b1,caseFlags, (uint32_t*)&b2Len, b2); + error = punycode_encode(b1Len, b1, caseFlags, reinterpret_cast(&b2Len), b2); status = getError(error); if(status == U_BUFFER_OVERFLOW_ERROR){ /* we do not have enough room so grow the buffer*/ - b2 = (char*) uprv_malloc( b2Len * sizeof(char)); + b2 = static_cast(uprv_malloc(b2Len * sizeof(char))); if(b2==nullptr){ status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; @@ -173,7 +173,7 @@ static int32_t convertToPuny(const char16_t* src, int32_t srcLength, status = U_ZERO_ERROR; // reset error - punycode_status error = punycode_encode(b1Len,b1,caseFlags, (uint32_t*)&b2Len, b2); + punycode_status error = punycode_encode(b1Len, b1, caseFlags, reinterpret_cast(&b2Len), b2); status = getError(error); } if(U_FAILURE(status)){ @@ -222,15 +222,15 @@ static int32_t convertFromPuny( const char16_t* src, int32_t srcLength, uint32_t* b2 = b2Stack; int32_t b2Len =MAX_LABEL_BUFFER_SIZE; unsigned char* caseFlags = nullptr; //(unsigned char*) uprv_malloc(srcLength * sizeof(unsigned char*)); - punycode_status error = punycode_decode(srcLength,b1,(uint32_t*)&b2Len,b2,caseFlags); + punycode_status error = punycode_decode(srcLength, b1, reinterpret_cast(&b2Len), b2, caseFlags); status = getError(error); if(status == U_BUFFER_OVERFLOW_ERROR){ - b2 = (uint32_t*) uprv_malloc(b2Len * sizeof(uint32_t)); + b2 = static_cast(uprv_malloc(b2Len * sizeof(uint32_t))); if(b2 == nullptr){ status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; } - error = punycode_decode(srcLength,b1,(uint32_t*)&b2Len,b2,caseFlags); + error = punycode_decode(srcLength, b1, reinterpret_cast(&b2Len), b2, caseFlags); status = getError(error); } @@ -238,7 +238,7 @@ static int32_t convertFromPuny( const char16_t* src, int32_t srcLength, goto CLEANUP; } - u_strFromUTF32(dest,destCapacity,&destLen,(UChar32*)b2,b2Len,&status); + u_strFromUTF32(dest, destCapacity, &destLen, reinterpret_cast(b2), b2Len, &status); CLEANUP: if(b1Stack != b1){ diff --git a/icu4c/source/test/intltest/incaltst.cpp b/icu4c/source/test/intltest/incaltst.cpp index 6f786c59b5a4..d7d052bde24f 100644 --- a/icu4c/source/test/intltest/incaltst.cpp +++ b/icu4c/source/test/intltest/incaltst.cpp @@ -190,7 +190,7 @@ void IntlCalendarTest::quasiGregorianTest(Calendar& cal, const Locale& gcl, cons int32_t tz1 = cal.get(UCAL_ZONE_OFFSET,status); int32_t tz2 = grego -> get (UCAL_ZONE_OFFSET, status); if(tz1 != tz2) { - errln((UnicodeString)"cal's tz " + tz1 + " != grego's tz " + tz2); + errln(UnicodeString("cal's tz ") + tz1 + " != grego's tz " + tz2); } for (int32_t i=0; data[i]!=-1; ) { @@ -209,8 +209,8 @@ void IntlCalendarTest::quasiGregorianTest(Calendar& cal, const Locale& gcl, cons cal.set(year, month, dayOfMonth); UDate d = cal.getTime(status); #ifdef U_DEBUG_DUMPCALS - logln((UnicodeString)"cal : " + CalendarTest::calToStr(cal)); - logln((UnicodeString)"grego: " + CalendarTest::calToStr(*grego)); + logln(UnicodeString("cal : ") + CalendarTest::calToStr(cal)); + logln(UnicodeString("grego: ") + CalendarTest::calToStr(*grego)); #endif if (d == D) { logln(UnicodeString("OK: ") + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth + @@ -226,15 +226,15 @@ void IntlCalendarTest::quasiGregorianTest(Calendar& cal, const Locale& gcl, cons int e = cal.get(UCAL_ERA, status); int y = cal.get(UCAL_YEAR, status); #ifdef U_DEBUG_DUMPCALS - logln((UnicodeString)"cal : " + CalendarTest::calToStr(cal)); - logln((UnicodeString)"grego: " + CalendarTest::calToStr(*grego)); + logln(UnicodeString("cal : ") + CalendarTest::calToStr(cal)); + logln(UnicodeString("grego: ") + CalendarTest::calToStr(*grego)); #endif if (y == year && e == era) { - logln((UnicodeString)"OK: " + D + " => " + cal.get(UCAL_ERA, status) + ":" + + logln(UnicodeString("OK: ") + D + " => " + cal.get(UCAL_ERA, status) + ":" + cal.get(UCAL_YEAR, status) + "/" + - (cal.get(UCAL_MONTH, status)+1) + "/" + cal.get(UCAL_DATE, status) + " (" + UnicodeString(cal.getType()) + ")"); + (cal.get(UCAL_MONTH, status) + 1) + "/" + cal.get(UCAL_DATE, status) + " (" + UnicodeString(cal.getType()) + ")"); } else { - errln((UnicodeString)"Fail: (millis to fields)" + D + " => " + cal.get(UCAL_ERA, status) + ":" + + errln(UnicodeString("Fail: (millis to fields)") + D + " => " + cal.get(UCAL_ERA, status) + ":" + cal.get(UCAL_YEAR, status) + "/" + (cal.get(UCAL_MONTH, status)+1) + "/" + cal.get(UCAL_DATE, status) + ", expected " + era + ":" + year + "/" + (month+1) + "/" + @@ -267,7 +267,7 @@ void IntlCalendarTest::TestGregorian() { UDate timeCal = cal->getTime(status); if(!(timeA <= timeCal) || !(timeCal <= timeB)) { - errln((UnicodeString)"Error: Calendar time " + timeCal + + errln(UnicodeString("Error: Calendar time ") + timeCal + " is not within sampled times [" + timeA + " to " + timeB + "]!"); } // end sanity check @@ -320,7 +320,7 @@ void IntlCalendarTest::TestBuddhist() { UDate timeCal = cal->getTime(status); if(!(timeA <= timeCal) || !(timeCal <= timeB)) { - errln((UnicodeString)"Error: Calendar time " + timeCal + + errln(UnicodeString("Error: Calendar time ") + timeCal + " is not within sampled times [" + timeA + " to " + timeB + "]!"); } // end sanity check @@ -371,7 +371,7 @@ void IntlCalendarTest::TestTaiwan() { UDate timeCal = cal->getTime(status); if(!(timeA <= timeCal) || !(timeCal <= timeB)) { - errln((UnicodeString)"Error: Calendar time " + timeCal + + errln(UnicodeString("Error: Calendar time ") + timeCal + " is not within sampled times [" + timeA + " to " + timeB + "]!"); } // end sanity check @@ -424,7 +424,7 @@ void IntlCalendarTest::TestJapanese() { UDate timeCal = cal->getTime(status); if(!(timeA <= timeCal) || !(timeCal <= timeB)) { - errln((UnicodeString)"Error: Calendar time " + timeCal + + errln(UnicodeString("Error: Calendar time ") + timeCal + " is not within sampled times [" + timeA + " to " + timeB + "]!"); } // end sanity check @@ -790,7 +790,7 @@ void IntlCalendarTest::TestPersian() { UDate timeCal = cal->getTime(status); if(!(timeA <= timeCal) || !(timeCal <= timeB)) { - errln((UnicodeString)"Error: Calendar time " + timeCal + + errln(UnicodeString("Error: Calendar time ") + timeCal + " is not within sampled times [" + timeA + " to " + timeB + "]!"); } // end sanity check @@ -1047,9 +1047,9 @@ void IntlCalendarTest::checkConsistency(const char* locale) { g->get(UCAL_DATE, status) == 4) { lastDay = 5; } else { - errln((UnicodeString) + errln(UnicodeString( "Day is not one less from previous date for " - "Gregorian(e=" + g->get(UCAL_ERA, status) + " " + + "Gregorian(e=") + g->get(UCAL_ERA, status) + " " + g->get(UCAL_YEAR, status) + "/" + (g->get(UCAL_MONTH, status) + 1) + "/" + g->get(UCAL_DATE, status) + ") " + locale + "(" + @@ -1066,8 +1066,8 @@ void IntlCalendarTest::checkConsistency(const char* locale) { // Second, we verify the month is in reasonale range. int32_t cmonth = base->get(UCAL_MONTH, status); if (cmonth < 0 || cmonth > 13) { - errln((UnicodeString) - "Month is out of range Gregorian(e=" + + errln(UnicodeString( + "Month is out of range Gregorian(e=") + g->get(UCAL_ERA, status) + " " + g->get(UCAL_YEAR, status) + "/" + (g->get(UCAL_MONTH, status) + 1) + "/" + @@ -1082,7 +1082,7 @@ void IntlCalendarTest::checkConsistency(const char* locale) { // Third, we verify the set function can round trip the time back. r->clear(); for (int32_t f = 0; f < UCAL_FIELD_COUNT; f++) { - UCalendarDateFields ut = (UCalendarDateFields)f; + UCalendarDateFields ut = static_cast(f); r->set(ut, base->get(ut, status)); } UDate result = r->getTime(status); @@ -1100,8 +1100,8 @@ void IntlCalendarTest::checkConsistency(const char* locale) { int32_t month = base->get(UCAL_MONTH, status) + 1; int32_t date = base->get(UCAL_DATE, status); - errln((UnicodeString)"Round trip conversion produces different " - "time from " + test + " to " + result + " delta: " + + errln(UnicodeString("Round trip conversion produces different " + "time from ") + test + " to " + result + " delta: " + (result - test) + " Gregorian(e=" + g->get(UCAL_ERA, status) + " " + g->get(UCAL_YEAR, status) + "/" + @@ -1146,7 +1146,7 @@ void IntlCalendarTest::simpleTest(const Locale& loc, const UnicodeString& expect UDate d; DateFormat *fmt0 = DateFormat::createDateTimeInstance(DateFormat::kFull, DateFormat::kFull); - logln("Try format/parse of " + (UnicodeString)loc.getName()); + logln("Try format/parse of " + UnicodeString(loc.getName())); DateFormat *fmt2 = DateFormat::createDateInstance(DateFormat::kFull, loc); if(fmt2) { fmt2->format(expectDate, tmp); @@ -1159,12 +1159,12 @@ void IntlCalendarTest::simpleTest(const Locale& loc, const UnicodeString& expect CHECK(status, "Error occurred parsing " + UnicodeString(loc.getName())); if(d != expectDate) { fmt2->format(d,tmp); - errln(UnicodeString("Failed to parse " ) + escape(expect) + ", " + loc.getName() + " expect " + (double)expectDate + " got " + (double)d + " " + escape(tmp)); + errln(UnicodeString("Failed to parse ") + escape(expect) + ", " + loc.getName() + " expect " + static_cast(expectDate) + " got " + static_cast(d) + " " + escape(tmp)); logln( "wanted " + escape(fmt0->format(expectDate,tmp.remove())) + " but got " + escape(fmt0->format(d,tmp.remove()))); } delete fmt2; } else { - errln((UnicodeString)"Can't create " + loc.getName() + " date instance"); + errln(UnicodeString("Can't create ") + loc.getName() + " date instance"); } delete fmt0; } @@ -1213,7 +1213,7 @@ void IntlCalendarTest::TestBug21044Hebrew() { return; } if (y > 0 || m < 0 || m > 12 || d < 0 || d > 32) { - errln((UnicodeString)"Out of rage!\nYear " + y + " should be " + + errln(UnicodeString("Out of rage!\nYear ") + y + " should be " + "negative number before 1AD.\nMonth " + m + " should " + "be between 0 and 12 in Hebrew calendar.\nDate " + d + " should be between 0 and 32 in Islamic calendar."); @@ -1254,7 +1254,7 @@ void IntlCalendarTest::TestBug21046IslamicUmalqura() { int32_t m = cal->get(UCAL_MONTH, status); int32_t d = cal->get(UCAL_DATE, status); if (y > 0 || m < 0 || m > 11 || d < 0 || d > 32) { - errln((UnicodeString)"Out of rage!\nYear " + y + " should be " + + errln(UnicodeString("Out of rage!\nYear ") + y + " should be " + "negative number before 1AD.\nMonth " + m + " should " + "be between 0 and 11 in Islamic calendar.\nDate " + d + " should be between 0 and 32 in Islamic calendar."); diff --git a/icu4c/source/test/intltest/intltest.cpp b/icu4c/source/test/intltest/intltest.cpp index 04c46e238807..868dcbbd52d5 100644 --- a/icu4c/source/test/intltest/intltest.cpp +++ b/icu4c/source/test/intltest/intltest.cpp @@ -105,7 +105,7 @@ Int64ToUnicodeString(int64_t num) #if defined(_MSC_VER) snprintf(buffer, sizeof(buffer), "%I64d", num); #else - snprintf(buffer, sizeof(buffer), "%lld", (long long)num); + snprintf(buffer, sizeof(buffer), "%lld", static_cast(num)); #endif assert(danger == 'p'); @@ -210,7 +210,7 @@ UnicodeString _toString(const Formattable& f) { break; } default: - s = UnicodeString("Unknown Formattable type=") + (int32_t)f.getType(); + s = UnicodeString("Unknown Formattable type=") + static_cast(f.getType()); break; } return s; @@ -221,9 +221,9 @@ UnicodeString _toString(const Formattable& f) { * + char* ambiguous. - liu */ UnicodeString toString(const Formattable& f) { - UnicodeString s((char16_t)91/*[*/); + UnicodeString s(static_cast(91)/*[*/); s.append(_toString(f)); - s.append((char16_t)0x5d/*]*/); + s.append(static_cast(0x5d)/*]*/); return s; } @@ -231,7 +231,7 @@ UnicodeString toString(const Formattable& f) { // useful when operator+ won't cooperate UnicodeString toString(int32_t n) { - return UnicodeString() + (long)n; + return UnicodeString() + static_cast(n); } @@ -248,19 +248,19 @@ UnicodeString toString(const UnicodeSet& uniset, UErrorCode& status) { // stephen - cleaned up 05/05/99 UnicodeString operator+(const UnicodeString& left, char num) -{ return left + (long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, short num) -{ return left + (long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, int num) -{ return left + (long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, unsigned char num) -{ return left + (unsigned long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, unsigned short num) -{ return left + (unsigned long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, unsigned int num) -{ return left + (unsigned long)num; } +{ return left + static_cast(num); } UnicodeString operator+(const UnicodeString& left, float num) -{ return left + (double)num; } +{ return left + static_cast(num); } //------------------ @@ -384,7 +384,7 @@ IntlTest::prettify(const UnicodeString &source, UBool parseBackslash) // Delete a backslash. int32_t backslashCount = 0; for (int32_t j=target.length()-1; j>=0; --j) { - if (target.charAt(j) == (char16_t)92) { + if (target.charAt(j) == static_cast(92)) { ++backslashCount; } else { break; @@ -696,7 +696,7 @@ UBool IntlTest::runTest( char* name, char* par, char *baseName ) char* baseNameBuffer = nullptr; if(baseName == nullptr) { - baseNameBuffer = (char*)malloc(1024); + baseNameBuffer = static_cast(malloc(1024)); baseName=baseNameBuffer; strcpy(baseName, "/"); } @@ -776,7 +776,7 @@ UBool IntlTest::runTestLoop( char* testname, char* par, char *baseName ) if (!testname) { run_this_test = true; }else{ - run_this_test = (UBool) (strcmp( name, testname ) == 0); + run_this_test = static_cast(strcmp(name, testname) == 0); } } if (run_this_test) { @@ -816,7 +816,7 @@ UBool IntlTest::runTestLoop( char* testname, char* par, char *baseName ) if(!no_time) str_timeDelta(msg+strlen(msg),timeStop-timeStart); lastTestFailed = false; }else{ - snprintf(msg, sizeof(msg), " } ERRORS (%li) in %s", (long)(errorCount-lastErrorCount), name); + snprintf(msg, sizeof(msg), " } ERRORS (%li) in %s", static_cast(errorCount - lastErrorCount), name); if(!no_time) str_timeDelta(msg+strlen(msg),timeStop-timeStart); for(int i=0;i 0) { - fwrite(buffer, sizeof(*buffer), length, (FILE *)testoutfp); + fwrite(buffer, sizeof(*buffer), length, static_cast(testoutfp)); } // replace each LineFeed by the indentation string - message.findAndReplace(UnicodeString((char16_t)'\n'), indent); + message.findAndReplace(UnicodeString(static_cast('\n')), indent); // stream out the message length = message.extract(0, message.length(), buffer, sizeof(buffer)); if (length > 0) { length = length > 30000 ? 30000 : length; - fwrite(buffer, sizeof(*buffer), length, (FILE *)testoutfp); + fwrite(buffer, sizeof(*buffer), length, static_cast(testoutfp)); } if (newline) { char newLine = '\n'; - fwrite(&newLine, sizeof(newLine), 1, (FILE *)testoutfp); + fwrite(&newLine, sizeof(newLine), 1, static_cast(testoutfp)); } // A newline usually flushes the buffer, but // flush the message just in case of a core dump. - fflush((FILE *)testoutfp); + fflush(static_cast(testoutfp)); } /** @@ -1369,7 +1369,7 @@ main(int argc, char* argv[]) { const char *charsetFamily = "Unknown"; - int32_t voidSize = (int32_t)sizeof(void*); + int32_t voidSize = static_cast(sizeof(void*)); int32_t bits = voidSize * 8; if(U_CHARSET_FAMILY==U_ASCII_FAMILY) { charsetFamily="ASCII"; @@ -1558,7 +1558,7 @@ main(int argc, char* argv[]) fprintf(stdout, "\t*WARNING* some data-loading errors were ignored by the -w option.\n"); } }else{ - fprintf(stdout, "Errors in total: %ld.\n", (long)major.getErrors()); + fprintf(stdout, "Errors in total: %ld.\n", static_cast(major.getErrors())); major.printErrors(); if(summary_file != nullptr) { @@ -1566,7 +1566,7 @@ main(int argc, char* argv[]) if( summf != nullptr) { char buf[10000]; int32_t length = errorList.extract(0, errorList.length(), buf, sizeof(buf)); - fwrite(buf, sizeof(*buf), length, (FILE*)summf); + fwrite(buf, sizeof(*buf), length, summf); fclose(summf); } } @@ -1593,12 +1593,12 @@ main(int argc, char* argv[]) } if(!no_time) { endTime = uprv_getRawUTCtime(); - diffTime = (int32_t)(endTime - startTime); + diffTime = static_cast(endTime - startTime); printf("Elapsed Time: %02d:%02d:%02d.%03d\n", - (int)((diffTime%U_MILLIS_PER_DAY)/U_MILLIS_PER_HOUR), - (int)((diffTime%U_MILLIS_PER_HOUR)/U_MILLIS_PER_MINUTE), - (int)((diffTime%U_MILLIS_PER_MINUTE)/U_MILLIS_PER_SECOND), - (int)(diffTime%U_MILLIS_PER_SECOND)); + (diffTime % U_MILLIS_PER_DAY) / U_MILLIS_PER_HOUR, + (diffTime % U_MILLIS_PER_HOUR) / U_MILLIS_PER_MINUTE, + (diffTime % U_MILLIS_PER_MINUTE) / U_MILLIS_PER_SECOND, + diffTime % U_MILLIS_PER_SECOND); } if(ctest_xml_fini()) @@ -1622,11 +1622,11 @@ const char* IntlTest::loadTestData(UErrorCode& err){ directory = pathToDataDirectory(); #endif - tdpath = (char*) malloc(sizeof(char) *(( strlen(directory) * strlen(tdrelativepath)) + 100)); + tdpath = static_cast(malloc(sizeof(char) * ((strlen(directory) * strlen(tdrelativepath)) + 100))); if (tdpath == nullptr) { err = U_MEMORY_ALLOCATION_ERROR; - it_dataerrln((UnicodeString) "Could not allocate memory for _testDataPath " + u_errorName(err)); + it_dataerrln(UnicodeString("Could not allocate memory for _testDataPath ") + u_errorName(err)); return ""; } @@ -1641,7 +1641,7 @@ const char* IntlTest::loadTestData(UErrorCode& err){ if (U_FAILURE(err)) { err = U_FILE_ACCESS_ERROR; - it_dataerrln((UnicodeString)"Could not load testtypes.res in testdata bundle with path " + tdpath + (UnicodeString)" - " + u_errorName(err)); + it_dataerrln(UnicodeString("Could not load testtypes.res in testdata bundle with path ") + tdpath + UnicodeString(" - ") + u_errorName(err)); return ""; } ures_close(test); @@ -1831,12 +1831,12 @@ float IntlTest::random(int32_t* seedp) { *seedp=(RAND_IA*(*seedp)+RAND_IC) % RAND_M; iy=(*seedp); } - j=(int32_t)(1 + 97.0*iy/RAND_M); + j = static_cast(1 + 97.0 * iy / RAND_M); U_ASSERT(j>=1 && j<=97); iy=ir[j]; *seedp=(RAND_IA*(*seedp)+RAND_IC) % RAND_M; ir[j]=(*seedp); - return (float) iy/RAND_M; + return static_cast(iy) / RAND_M; } /** @@ -1869,28 +1869,28 @@ void IntlTest::icu_rand::seed(uint32_t seed) { } uint32_t IntlTest::icu_rand::operator() () { - fLast = ((uint64_t)fLast * 48271UL) % 2147483647UL; + fLast = (static_cast(fLast) * 48271UL) % 2147483647UL; return fLast; } uint32_t IntlTest::icu_rand::getSeed() { - return (uint32_t) fLast; + return fLast; } static inline char16_t toHex(int32_t i) { - return (char16_t)(i + (i < 10 ? 0x30 : (0x41 - 10))); + return static_cast(i + (i < 10 ? 0x30 : (0x41 - 10))); } static UnicodeString& escape(const UnicodeString& s, UnicodeString& result) { for (int32_t i=0; i(0x7F)) { result += c; } else { - result += (char16_t)0x5c; - result += (char16_t)0x75; + result += static_cast(0x5c); + result += static_cast(0x75); result += toHex((c >> 12) & 0xF); result += toHex((c >> 8) & 0xF); result += toHex((c >> 4) & 0xF); @@ -1964,11 +1964,11 @@ UBool IntlTest::assertEquals(const char* message, UBool possibleDataError) { if (expected != actual) { if (possibleDataError) { - dataerrln((UnicodeString)"FAIL: " + message + "; got " + + dataerrln(UnicodeString("FAIL: ") + message + "; got " + prettify(actual) + "; expected " + prettify(expected)); } else { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + prettify(actual) + "; expected " + prettify(expected)); } @@ -1976,7 +1976,7 @@ UBool IntlTest::assertEquals(const char* message, } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + prettify(actual)); + logln(UnicodeString("Ok: ") + message + "; got " + prettify(actual)); } #endif return true; @@ -1988,14 +1988,14 @@ UBool IntlTest::assertEquals(const char* message, U_ASSERT(expected != nullptr); U_ASSERT(actual != nullptr); if (uprv_strcmp(expected, actual) != 0) { - errln((UnicodeString)"FAIL: " + message + "; got \"" + + errln(UnicodeString("FAIL: ") + message + "; got \"" + actual + "\"; expected \"" + expected + "\""); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got \"" + actual + "\""); + logln(UnicodeString("Ok: ") + message + "; got \"" + actual + "\""); } #endif return true; @@ -2005,14 +2005,14 @@ UBool IntlTest::assertEquals(const char* message, int32_t expected, int32_t actual) { if (expected != actual) { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + actual + "=0x" + toHex(actual) + "; expected " + expected + "=0x" + toHex(expected)); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + actual + "=0x" + toHex(actual)); + logln(UnicodeString("Ok: ") + message + "; got " + actual + "=0x" + toHex(actual)); } #endif return true; @@ -2022,14 +2022,14 @@ UBool IntlTest::assertEquals(const char* message, int64_t expected, int64_t actual) { if (expected != actual) { - errln((UnicodeString)"FAIL: " + message + "; got int64 " + + errln(UnicodeString("FAIL: ") + message + "; got int64 " + Int64ToUnicodeString(actual) + "; expected " + Int64ToUnicodeString(expected) ); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got int64 " + Int64ToUnicodeString(actual)); + logln(UnicodeString("Ok: ") + message + "; got int64 " + Int64ToUnicodeString(actual)); } #endif return true; @@ -2040,14 +2040,14 @@ UBool IntlTest::assertEquals(const char* message, double actual) { bool bothNaN = std::isnan(expected) && std::isnan(actual); if (expected != actual && !bothNaN) { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + actual + "; expected " + expected); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + actual); + logln(UnicodeString("Ok: ") + message + "; got " + actual); } #endif return true; @@ -2057,14 +2057,14 @@ UBool IntlTest::assertEquals(const char* message, UBool expected, UBool actual) { if (expected != actual) { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + toString(actual) + "; expected " + toString(expected)); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + toString(actual)); + logln(UnicodeString("Ok: ") + message + "; got " + toString(actual)); } #endif return true; @@ -2075,14 +2075,14 @@ UBool IntlTest::assertEquals(const char* message, UErrorCode expected, UErrorCode actual) { if (expected != actual) { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + u_errorName(actual) + "; expected " + u_errorName(expected)); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + u_errorName(actual)); + logln(UnicodeString("Ok: ") + message + "; got " + u_errorName(actual)); } #endif return true; @@ -2093,14 +2093,14 @@ UBool IntlTest::assertEquals(const char* message, const UnicodeSet& actual) { IcuTestErrorCode status(*this, "assertEqualsUniSet"); if (expected != actual) { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + toString(actual, status) + "; expected " + toString(expected, status)); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + toString(actual, status)); + logln(UnicodeString("Ok: ") + message + "; got " + toString(actual, status)); } #endif return true; @@ -2114,11 +2114,11 @@ UBool IntlTest::assertEquals(const char* message, UBool possibleDataError) { if (expected != actual) { if (possibleDataError) { - dataerrln((UnicodeString)"FAIL: " + message + "; got " + + dataerrln(UnicodeString("FAIL: ") + message + "; got " + toString(actual) + "; expected " + toString(expected)); } else { - errln((UnicodeString)"FAIL: " + message + "; got " + + errln(UnicodeString("FAIL: ") + message + "; got " + toString(actual) + "; expected " + toString(expected)); } @@ -2126,7 +2126,7 @@ UBool IntlTest::assertEquals(const char* message, } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + toString(actual)); + logln(UnicodeString("Ok: ") + message + "; got " + toString(actual)); } #endif return true; @@ -2156,14 +2156,14 @@ UBool IntlTest::assertEquals(const char* message, if (expected != actual) { std::string expectedAsString = vectorToString(expected); std::string actualAsString = vectorToString(actual); - errln((UnicodeString)"FAIL: " + message + + errln(UnicodeString("FAIL: ") + message + "; got " + actualAsString.c_str() + "; expected " + expectedAsString.c_str()); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)"Ok: " + message + "; got " + vectorToString(actual).c_str()); + logln(UnicodeString("Ok: ") + message + "; got " + vectorToString(actual).c_str()); } #endif return true; @@ -2173,13 +2173,13 @@ UBool IntlTest::assertNotEquals(const char* message, int32_t expectedNot, int32_t actual) { if (expectedNot == actual) { - errln((UnicodeString)("FAIL: ") + message + "; got " + actual + "=0x" + toHex(actual) + + errln(UnicodeString("FAIL: ") + message + "; got " + actual + "=0x" + toHex(actual) + "; expected != " + expectedNot); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)("Ok: ") + message + "; got " + actual + "=0x" + toHex(actual) + + logln(UnicodeString("Ok: ") + message + "; got " + actual + "=0x" + toHex(actual) + " != " + expectedNot); } #endif @@ -2198,19 +2198,19 @@ UBool IntlTest::assertEqualsNear(const char* message, return true; } if (std::isnan(delta) || std::isinf(delta)) { - errln((UnicodeString)("FAIL: ") + message + "; nonsensical delta " + delta + + errln(UnicodeString("FAIL: ") + message + "; nonsensical delta " + delta + " - delta may not be NaN or Inf. (Got " + actual + "; expected " + expected + ".)"); return false; } double difference = std::abs(expected - actual); if (expected != actual && (difference > delta || std::isnan(difference))) { - errln((UnicodeString)("FAIL: ") + message + "; got " + actual + "; expected " + expected + + errln(UnicodeString("FAIL: ") + message + "; got " + actual + "; expected " + expected + "; acceptable delta " + delta); return false; } #ifdef VERBOSE_ASSERTIONS else { - logln((UnicodeString)("Ok: ") + message + "; got " + actual); + logln(UnicodeString("Ok: ") + message + "; got " + actual); } #endif return true; @@ -2316,7 +2316,7 @@ const char* IntlTest::getProperty(const char* prop) { const char* val = nullptr; for (int32_t i = 0; i < numProps; i++) { int32_t plen = static_cast(uprv_strlen(prop)); - if ((int32_t)uprv_strlen(proplines[i]) > plen + 1 + if (static_cast(uprv_strlen(proplines[i])) > plen + 1 && proplines[i][plen] == '=' && uprv_strncmp(proplines[i], prop, plen) == 0) { val = &(proplines[i][plen+1]); diff --git a/icu4c/source/test/intltest/intltest.h b/icu4c/source/test/intltest/intltest.h index 32f468e3fa7f..146b7421bb5b 100644 --- a/icu4c/source/test/intltest/intltest.h +++ b/icu4c/source/test/intltest/intltest.h @@ -407,7 +407,7 @@ class IntlTest : public TestLog { static UnicodeString &appendHex(uint32_t number, int32_t digits, UnicodeString &target); static UnicodeString toHex(uint32_t number, int32_t digits=-1); static inline UnicodeString toHex(int32_t number, int32_t digits=-1) { - return toHex((uint32_t)number, digits); + return toHex(static_cast(number), digits); } public: diff --git a/icu4c/source/test/intltest/itercoll.cpp b/icu4c/source/test/intltest/itercoll.cpp index 310614b669fa..25b361af1f73 100644 --- a/icu4c/source/test/intltest/itercoll.cpp +++ b/icu4c/source/test/intltest/itercoll.cpp @@ -94,7 +94,7 @@ void CollationIteratorTest::TestPrevious(/* char* par */) UnicodeString source; RuleBasedCollator *c1 = nullptr; c1 = new RuleBasedCollator( - (UnicodeString)"&a,A < b,B < c,C, d,D < z,Z < ch,cH,Ch,CH", status); + UnicodeString("&a,A < b,B < c,C, d,D < z,Z < ch,cH,Ch,CH"), status); if (c1 == nullptr || U_FAILURE(status)) { @@ -111,7 +111,7 @@ void CollationIteratorTest::TestPrevious(/* char* par */) // Test with an expanding character sequence RuleBasedCollator *c2 = nullptr; - c2 = new RuleBasedCollator((UnicodeString)"&a < b < c/abd < d", status); + c2 = new RuleBasedCollator(UnicodeString("&a < b < c/abd < d"), status); if (c2 == nullptr || U_FAILURE(status)) { @@ -128,7 +128,7 @@ void CollationIteratorTest::TestPrevious(/* char* par */) // Now try both RuleBasedCollator *c3 = nullptr; - c3 = new RuleBasedCollator((UnicodeString)"&a < b < c/aba < d < z < ch", status); + c3 = new RuleBasedCollator(UnicodeString("&a < b < c/aba < d < z < ch"), status); if (c3 == nullptr || U_FAILURE(status)) { @@ -329,13 +329,13 @@ void CollationIteratorTest::TestSetText(/* char* par */) UnicodeString empty(""); iter1->setText(empty, status); if (U_FAILURE(status) - || iter1->next(status) != (int32_t)CollationElementIterator::NULLORDER) { + || iter1->next(status) != static_cast(CollationElementIterator::NULLORDER)) { errln("Empty string should have no CEs."); } (dynamic_cast(chariter))->setText(empty); iter1->setText(*chariter, status); if (U_FAILURE(status) - || iter1->next(status) != (int32_t)CollationElementIterator::NULLORDER) { + || iter1->next(status) != static_cast(CollationElementIterator::NULLORDER)) { errln("Empty string should have no CEs."); } delete chariter; @@ -369,7 +369,7 @@ void CollationIteratorTest::TestMaxExpansion(/* char* par */) order = iter->previous(status); while (U_SUCCESS(status) - && iter->previous(status) != (int32_t)CollationElementIterator::NULLORDER) + && iter->previous(status) != static_cast(CollationElementIterator::NULLORDER)) { count ++; } @@ -390,7 +390,7 @@ void CollationIteratorTest::TestMaxExpansion(/* char* par */) void CollationIteratorTest::TestClearBuffers(/* char* par */) { UErrorCode status = U_ZERO_ERROR; - RuleBasedCollator *c = new RuleBasedCollator((UnicodeString)"&a < b < c & ab = d", status); + RuleBasedCollator* c = new RuleBasedCollator(UnicodeString("&a < b < c & ab = d"), status); if (c == nullptr || U_FAILURE(status)) { @@ -580,10 +580,10 @@ void CollationIteratorTest::TestConstructors() || *iter2 != *iter1) { errln("CollationElementIterators constructed with the same string data should be the same at the start"); } - if (iter1->next(status) != (int32_t)CollationElementIterator::NULLORDER) { + if (iter1->next(status) != static_cast(CollationElementIterator::NULLORDER)) { errln("Empty string should have no CEs."); } - if (iter2->next(status) != (int32_t)CollationElementIterator::NULLORDER) { + if (iter2->next(status) != static_cast(CollationElementIterator::NULLORDER)) { errln("Empty string should have no CEs."); } delete iter1; diff --git a/icu4c/source/test/intltest/itformat.cpp b/icu4c/source/test/intltest/itformat.cpp index aacd19aee2bb..074cb993b118 100644 --- a/icu4c/source/test/intltest/itformat.cpp +++ b/icu4c/source/test/intltest/itformat.cpp @@ -154,7 +154,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "TimeUnitTest"; if (exec) { logln("TimeUnitTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createTimeUnitTest()); callTest(*test, par); } @@ -169,7 +169,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "GenderInfoTest"; if (exec) { logln("GenderInfoTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createGenderInfoTest()); callTest(*test, par); } @@ -178,7 +178,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "CompactDecimalFormatTest"; if (exec) { logln("CompactDecimalFormatTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createCompactDecimalFormatTest()); callTest(*test, par); } @@ -189,7 +189,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "RelativeDateTimeFormatterTest"; if (exec) { logln("RelativeDateTimeFormatterTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createRelativeDateTimeFormatterTest()); callTest(*test, par); } @@ -199,7 +199,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "MeasureFormatTest"; if (exec) { logln("MeasureFormatTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createMeasureFormatTest()); callTest(*test, par); } @@ -208,7 +208,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "NumberFormatSpecificationTest"; if (exec) { logln("NumberFormatSpecificationTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createNumberFormatSpecificationTest()); callTest(*test, par); } @@ -217,7 +217,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "ScientificNumberFormatterTest"; if (exec) { logln("ScientificNumberFormatterTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createScientificNumberFormatterTest()); callTest(*test, par); } @@ -229,7 +229,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "FormattedValueTest"; if (exec) { logln("FormattedValueTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createFormattedValueTest()); callTest(*test, par); } @@ -238,7 +238,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "FormattedStringBuilderTest"; if (exec) { logln("FormattedStringBuilderTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createFormattedStringBuilderTest()); callTest(*test, par); } @@ -247,7 +247,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "StringSegmentTest"; if (exec) { logln("StringSegmentTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createStringSegmentTest()); callTest(*test, par); } @@ -256,7 +256,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "UnitsTest"; if (exec) { logln("UnitsTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createUnitsTest()); callTest(*test, par); } @@ -265,7 +265,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "UnitsDataTest"; if (exec) { logln("UnitsDataTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createUnitsDataTest()); callTest(*test, par); } @@ -274,7 +274,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "UnitsRouterTest"; if (exec) { logln("UnitsRouterTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createUnitsRouterTest()); callTest(*test, par); } @@ -283,7 +283,7 @@ void IntlTestFormat::runIndexedTest( int32_t index, UBool exec, const char* &nam name = "DisplayOptionsTest"; if (exec) { logln("DisplayOptionsTest test---"); - logln((UnicodeString)""); + logln(UnicodeString("")); LocalPointer test(createDisplayOptionsTest()); callTest(*test, par); } diff --git a/icu4c/source/test/intltest/itrbnf.cpp b/icu4c/source/test/intltest/itrbnf.cpp index b764730b66e6..fd2451856e56 100644 --- a/icu4c/source/test/intltest/itrbnf.cpp +++ b/icu4c/source/test/intltest/itrbnf.cpp @@ -126,7 +126,7 @@ void IntlTestRBNF::TestHebrewFraction() { UnicodeString expected(text1); formatter->format(123.45, result); if (result != expected) { - errln((UnicodeString)"expected '" + TestUtility::hex(expected) + "'\nbut got: '" + TestUtility::hex(result) + "'"); + errln(UnicodeString("expected '") + TestUtility::hex(expected) + "'\nbut got: '" + TestUtility::hex(result) + "'"); } else { // formatter->parse(result, parseResult, pp); // if (parseResult.getDouble() != 123.45) { @@ -139,7 +139,7 @@ void IntlTestRBNF::TestHebrewFraction() { result.remove(); formatter->format(123.0045, result); if (result != expected) { - errln((UnicodeString)"expected '" + TestUtility::hex(expected) + "'\nbut got: '" + TestUtility::hex(result) + "'"); + errln(UnicodeString("expected '") + TestUtility::hex(expected) + "'\nbut got: '" + TestUtility::hex(result) + "'"); } else { pp.setIndex(0); // formatter->parse(result, parseResult, pp); @@ -220,7 +220,7 @@ IntlTestRBNF::TestAPI() { } // Jitterbug 4452, for coverage - RuleBasedNumberFormat nf(spelloutRules, (UnicodeString)"", Locale::getUS(), perror, status); + RuleBasedNumberFormat nf(spelloutRules, UnicodeString(""), Locale::getUS(), perror, status); if(!(nf == *formatter)) { errln("Formatter constructed from the original rules should be semantically equivalent to the original!"); } @@ -324,7 +324,7 @@ IntlTestRBNF::TestAPI() { } result.remove(); expected = "four"; - formatter->format((int32_t)4,result); + formatter->format(static_cast(4), result); if(result != expected) { errln("Formatted 4, expected " + expected + " got " + result); } else { @@ -333,7 +333,7 @@ IntlTestRBNF::TestAPI() { result.remove(); FieldPosition pos; - formatter->format((int64_t)4, result, pos, status = U_ZERO_ERROR); + formatter->format(static_cast(4), result, pos, status = U_ZERO_ERROR); if(result != expected) { errln("Formatted 4 int64_t, expected " + expected + " got " + result); } else { @@ -343,7 +343,7 @@ IntlTestRBNF::TestAPI() { //Jitterbug 4452, for coverage result.remove(); FieldPosition pos2; - formatter->format((int64_t)4, formatter->getRuleSetName(0), result, pos2, status = U_ZERO_ERROR); + formatter->format(static_cast(4), formatter->getRuleSetName(0), result, pos2, status = U_ZERO_ERROR); if(result != expected) { errln("Formatted 4 int64_t, expected " + expected + " got " + result); } else { @@ -465,7 +465,7 @@ void IntlTestRBNF::TestFractionalRuleSet() change = 1; // change, but once we hit a non-space char, don't change } else if (ch == ' ') { if (change != 0) { - fracRules.setCharAt(i, (char16_t)0x200e); + fracRules.setCharAt(i, static_cast(0x200e)); } } else { if (change == 1) { @@ -2021,7 +2021,7 @@ IntlTestRBNF::TestAllLocales() for (int j = 0; j < 2; ++j) { UErrorCode status = U_ZERO_ERROR; - RuleBasedNumberFormat* f = new RuleBasedNumberFormat((URBNFRuleSetTag)j, *loc, status); + RuleBasedNumberFormat* f = new RuleBasedNumberFormat(static_cast(j), *loc, status); if (U_FAILURE(status)) { errln(UnicodeString(loc->getName()) + names[j] @@ -2066,7 +2066,7 @@ IntlTestRBNF::TestAllLocales() + UnicodeString("ERROR could not roundtrip ") + n + UnicodeString(" -> ") + str + UnicodeString(" -> ") + num.getLong()); } - else if (num.getType() == Formattable::kDouble && (int64_t)(num.getDouble() * 1000) != (int64_t)(n*1000)) { + else if (num.getType() == Formattable::kDouble && static_cast(num.getDouble() * 1000) != static_cast(n * 1000)) { // The epsilon difference is too high. errln(UnicodeString(loc->getName()) + names[j] + UnicodeString("ERROR could not roundtrip ") + n @@ -2088,7 +2088,7 @@ IntlTestRBNF::TestAllLocales() + UnicodeString("ERROR could not roundtrip ") + n + UnicodeString(" -> ") + str + UnicodeString(" -> ") + num.getLong()); } - else if (num.getType() == Formattable::kDouble && (int64_t)(num.getDouble() * 1000) != (int64_t)(n*1000)) { + else if (num.getType() == Formattable::kDouble && static_cast(num.getDouble() * 1000) != static_cast(n * 1000)) { // The epsilon difference is too high. errln(UnicodeString(loc->getName()) + names[j] + UnicodeString("ERROR could not roundtrip ") + n @@ -2263,7 +2263,7 @@ void IntlTestRBNF::TestPluralRules() { // Make sure there are no divide by 0 errors. UnicodeString result; - RuleBasedNumberFormat(ruRules, Locale("ru"), parseError, status).format((int32_t)21000, result); + RuleBasedNumberFormat(ruRules, Locale("ru"), parseError, status).format(static_cast(21000), result); if (result.compare(UNICODE_STRING_SIMPLE("twenty-one thousand")) != 0) { errln("Got " + result + " for 21000"); } diff --git a/icu4c/source/test/intltest/itrbnfp.cpp b/icu4c/source/test/intltest/itrbnfp.cpp index 4e224488e216..93cf7d4331f7 100644 --- a/icu4c/source/test/intltest/itrbnfp.cpp +++ b/icu4c/source/test/intltest/itrbnfp.cpp @@ -147,10 +147,10 @@ IntlTestRBNFParse::TestParse() { void IntlTestRBNFParse::testfmt(RuleBasedNumberFormat* formatter, double val, UErrorCode& status) { UnicodeString us; - formatter->format((const Formattable)val, us, status); + formatter->format(static_cast(val), us, status); if (U_SUCCESS(status)) { - us.insert(0, (char16_t)'"'); - us.append((char16_t)'"'); + us.insert(0, static_cast('"')); + us.append(static_cast('"')); logln(us); } else { logln("error: could not format %g, returned status: %d", val, status); @@ -160,10 +160,10 @@ IntlTestRBNFParse::testfmt(RuleBasedNumberFormat* formatter, double val, UErrorC void IntlTestRBNFParse::testfmt(RuleBasedNumberFormat* formatter, int val, UErrorCode& status) { UnicodeString us; - formatter->format((const Formattable)(int32_t)val, us, status); + formatter->format(static_cast(static_cast(val)), us, status); if (U_SUCCESS(status)) { - us.insert(0, (char16_t)'"'); - us.append((char16_t)'"'); + us.insert(0, static_cast('"')); + us.append(static_cast('"')); logln(us); } else { logln("error: could not format %d, returned status: %d", val, status); diff --git a/icu4c/source/test/intltest/itrbnfrt.cpp b/icu4c/source/test/intltest/itrbnfrt.cpp index 3087ae08423e..650b2fc4a377 100644 --- a/icu4c/source/test/intltest/itrbnfrt.cpp +++ b/icu4c/source/test/intltest/itrbnfrt.cpp @@ -306,7 +306,7 @@ RbnfRoundTripTest::doTest(const RuleBasedNumberFormat* formatter, } else { double rt = (parseResult.getType() == Formattable::kDouble) ? parseResult.getDouble() : - (double)parseResult.getLong(); + static_cast(parseResult.getLong()); if (rt != i) { snprintf(buf, sizeof(buf), "Round-trip failed: %.12g -> %.12g", i, rt); @@ -333,7 +333,7 @@ RbnfRoundTripTest::doTest(const RuleBasedNumberFormat* formatter, } else { double rt = (parseResult.getType() == Formattable::kDouble) ? parseResult.getDouble() : - (double)parseResult.getLong(); + static_cast(parseResult.getLong()); if (rt != d) { UnicodeString msg; diff --git a/icu4c/source/test/intltest/itspoof.cpp b/icu4c/source/test/intltest/itspoof.cpp index 728b7e715f59..b1f560a53b7f 100644 --- a/icu4c/source/test/intltest/itspoof.cpp +++ b/icu4c/source/test/intltest/itspoof.cpp @@ -392,10 +392,10 @@ static void appendHexUChar(UnicodeString &dest, UChar32 c) { int hexDigit = (c>>bitNum) & 0x0f; if (hexDigit != 0 || doZeroes) { doZeroes = true; - dest.append((char16_t)(hexDigit<=9? hexDigit + 0x30: hexDigit -10 + 0x41)); + dest.append(static_cast(hexDigit <= 9 ? hexDigit + 0x30 : hexDigit - 10 + 0x41)); } } - dest.append((char16_t)0x20); + dest.append(static_cast(0x20)); } U_DEFINE_LOCAL_OPEN_POINTER(LocalStdioFilePointer, FILE, fclose); @@ -517,7 +517,7 @@ void IntlTestSpoof::testScriptSet() { s1.reset(USCRIPT_ARABIC, status); TEST_ASSERT(s1 == s2); - static constexpr UScriptCode LAST_SCRIPT_CODE = (UScriptCode)(USCRIPT_CODE_LIMIT - 1); + static constexpr UScriptCode LAST_SCRIPT_CODE = static_cast(USCRIPT_CODE_LIMIT - 1); status = U_ZERO_ERROR; s1.setAll(); TEST_ASSERT(s1.test(USCRIPT_COMMON, status)); diff --git a/icu4c/source/test/intltest/itutil.cpp b/icu4c/source/test/intltest/itutil.cpp index a89c83f0243b..e31b470b8cf0 100644 --- a/icu4c/source/test/intltest/itutil.cpp +++ b/icu4c/source/test/intltest/itutil.cpp @@ -93,8 +93,8 @@ void ErrorCodeTest::runIndexedTest(int32_t index, UBool exec, const char* &name, } } -static void RefPlusOne(UErrorCode &code) { code=(UErrorCode)(code+1); } -static void PtrPlusTwo(UErrorCode *code) { *code=(UErrorCode)(*code+2); } +static void RefPlusOne(UErrorCode &code) { code = static_cast(code + 1); } +static void PtrPlusTwo(UErrorCode *code) { *code = static_cast(*code + 2); } void ErrorCodeTest::TestErrorCode() { ErrorCode errorCode; @@ -351,7 +351,7 @@ void LocalPointerTest::runIndexedTest(int32_t index, UBool exec, const char *&na // Exercise almost every LocalPointer and LocalPointerBase method. void LocalPointerTest::TestLocalPointer() { // constructor - LocalPointer s(new UnicodeString((UChar32)0x50005)); + LocalPointer s(new UnicodeString(static_cast(0x50005))); // isNULL(), isValid(), operator==(), operator!=() if(s.isNull() || !s.isValid() || s==nullptr || !(s!=nullptr)) { errln("LocalPointer constructor or nullptr test failure"); @@ -362,7 +362,7 @@ void LocalPointerTest::TestLocalPointer() { errln("LocalPointer access failure"); } // adoptInstead(), orphan() - s.adoptInstead(new UnicodeString((char16_t)0xfffc)); + s.adoptInstead(new UnicodeString(static_cast(0xfffc))); if(s->length()!=1) { errln("LocalPointer adoptInstead(U+FFFC) failure"); } @@ -423,8 +423,8 @@ void moveFrom(T &dest, T &src) { } void LocalPointerTest::TestLocalPointerMoveSwap() { - UnicodeString *p1 = new UnicodeString((char16_t)0x61); - UnicodeString *p2 = new UnicodeString((char16_t)0x62); + UnicodeString* p1 = new UnicodeString(static_cast(0x61)); + UnicodeString* p2 = new UnicodeString(static_cast(0x62)); LocalPointer s1(p1); LocalPointer s2(p2); s1.swap(s2); @@ -458,7 +458,7 @@ void LocalPointerTest::TestLocalPointerMoveSwap() { } void LocalPointerTest::TestLocalPointerStdUniquePtr() { - auto* ptr = new UnicodeString((UChar32)0x50005); + auto* ptr = new UnicodeString(static_cast(0x50005)); // Implicit conversion operator std::unique_ptr s = LocalPointer(ptr); // Explicit move constructor @@ -475,14 +475,14 @@ void LocalPointerTest::TestLocalArray() { // constructor LocalArray a(new UnicodeString[2]); // operator[]() - a[0].append((char16_t)0x61); - a[1].append((UChar32)0x60006); + a[0].append(static_cast(0x61)); + a[1].append(static_cast(0x60006)); if(a[0].length()!=1 || a[1].length()!=2) { errln("LocalArray access failure"); } // adoptInstead() a.adoptInstead(new UnicodeString[4]); - a[3].append((char16_t)0x62).append((char16_t)0x63).reverse(); + a[3].append(static_cast(0x62)).append(static_cast(0x63)).reverse(); if(a[3].length()!=2 || a[3][1]!=0x62) { errln("LocalArray adoptInstead() failure"); } diff --git a/icu4c/source/test/intltest/jamotest.cpp b/icu4c/source/test/intltest/jamotest.cpp index 949b92c756ed..509fb6fff0b9 100644 --- a/icu4c/source/test/intltest/jamotest.cpp +++ b/icu4c/source/test/intltest/jamotest.cpp @@ -154,7 +154,7 @@ JamoTest::TestJamo() { * latin and back. */ void JamoTest::TestPiecemeal() { - UnicodeString hangul; hangul.append((char16_t)0xBC0F); + UnicodeString hangul; hangul.append(static_cast(0xBC0F)); UnicodeString jamo = nameToJamo("(Mi)(I)(Cf)"); UnicodeString latin("mic"); UnicodeString latin2("mich"); @@ -417,7 +417,7 @@ JamoTest::TestRealText() { buf.remove(0); buf.append("FAIL: "); if (hangul2 != hangulX) { - buf.append((UnicodeString)"(Weird: " + hangulX + " != " + hangul2 + ")"); + buf.append(UnicodeString("(Weird: ") + hangulX + " != " + hangul2 + ")"); } // The Hangul-Jamo conversion is not usually the // bug here, so we hide it from display. @@ -431,9 +431,9 @@ JamoTest::TestRealText() { } } if (errors != 0) { - errln((UnicodeString)"Test word failures: " + errors + " out of " + total); + errln(UnicodeString("Test word failures: ") + errors + " out of " + total); } else { - logln((UnicodeString)"All " + total + " test words passed"); + logln(UnicodeString("All ") + total + " test words passed"); } delete latinJamo; diff --git a/icu4c/source/test/intltest/listformattertest.cpp b/icu4c/source/test/intltest/listformattertest.cpp index 1564e54c19e6..592137e39dd9 100644 --- a/icu4c/source/test/intltest/listformattertest.cpp +++ b/icu4c/source/test/intltest/listformattertest.cpp @@ -95,14 +95,14 @@ void ListFormatterTest::ExpectPositions( break; } } - assertTrue((UnicodeString)"found [" + attrString(id) + "," + start + "," + limit + "]", ok); + assertTrue(UnicodeString("found [") + attrString(id) + "," + start + "," + limit + "]", ok); } // check that all were found UBool ok = true; for (int i = 0; i < tupleCount; ++i) { if (!found[i]) { ok = false; - assertTrue((UnicodeString) "missing [" + attrString(values[i*3]) + "," + values[i*3+1] + + assertTrue(UnicodeString("missing [") + attrString(values[i * 3]) + "," + values[i * 3 + 1] + "," + values[i*3+2] + "]", found[i]); } } diff --git a/icu4c/source/test/intltest/localematchertest.cpp b/icu4c/source/test/intltest/localematchertest.cpp index c9ce207059ee..2996f8aa706d 100644 --- a/icu4c/source/test/intltest/localematchertest.cpp +++ b/icu4c/source/test/intltest/localematchertest.cpp @@ -578,7 +578,7 @@ UBool LocaleMatcherTest::dataDriven(const TestCase &test, IcuTestErrorCode &erro } if (!test.threshold.isEmpty()) { infoln("skipping test case on line %d with non-default threshold: not exposed via API", - (int)test.lineNr); + static_cast(test.lineNr)); return true; // int32_t threshold = Integer.valueOf(test.threshold); // builder.internalSetThresholdDistance(threshold); @@ -660,20 +660,20 @@ void LocaleMatcherTest::testDataDriven() { line.setTo(false, p, lineLength); if (!readTestCase(line, test, errorCode)) { if (errorCode.errIfFailureAndReset( - "test data syntax error on line %d", (int)test.lineNr)) { + "test data syntax error on line %d", static_cast(test.lineNr))) { infoln(line); } continue; } UBool ok = dataDriven(test, errorCode); - if (errorCode.errIfFailureAndReset("test error on line %d", (int)test.lineNr)) { + if (errorCode.errIfFailureAndReset("test error on line %d", static_cast(test.lineNr))) { infoln(line); } else if (!ok) { - infoln("test failure on line %d", (int)test.lineNr); + infoln("test failure on line %d", static_cast(test.lineNr)); infoln(line); } else { ++numPassed; } } - infoln("number of passing test cases: %d", (int)numPassed); + infoln("number of passing test cases: %d", static_cast(numPassed)); } diff --git a/icu4c/source/test/intltest/locnmtst.cpp b/icu4c/source/test/intltest/locnmtst.cpp index 846017c9b24b..864b57ef5185 100644 --- a/icu4c/source/test/intltest/locnmtst.cpp +++ b/icu4c/source/test/intltest/locnmtst.cpp @@ -363,7 +363,7 @@ static const LocNameDispContextItem ctxtItems[] = { { "es", UDISPCTX_DIALECT_NAMES, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, UDISPCTX_LENGTH_FULL, en_GB, esFor_en_GB_DT }, { "ru", UDISPCTX_STANDARD_NAMES, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, UDISPCTX_LENGTH_FULL, uz_Latn, ruFor_uz_Latn_T }, #endif /* #if !UCONFIG_NO_BREAK_ITERATION */ - { nullptr, (UDisplayContext)0, (UDisplayContext)0, (UDisplayContext)0, nullptr, nullptr } + { nullptr, static_cast(0), static_cast(0), static_cast(0), nullptr, nullptr } }; void LocaleDisplayNamesTest::TestUldnDisplayContext() { @@ -382,7 +382,7 @@ void LocaleDisplayNamesTest::TestUldnDisplayContext() { UDisplayContext capitalization = uldn_getContext(uldn, UDISPCTX_TYPE_CAPITALIZATION, &status); UDisplayContext displayLength = uldn_getContext(uldn, UDISPCTX_TYPE_DISPLAY_LENGTH, &status); if (U_FAILURE(status)) { - errln(UnicodeString("FAIL: uldn_getContext status ") + (int)status); + errln(UnicodeString("FAIL: uldn_getContext status ") + static_cast(status)); } else if (dialectHandling != ctxtItemPtr->dialectHandling || capitalization != ctxtItemPtr->capitalization || displayLength != ctxtItemPtr->displayLength) { diff --git a/icu4c/source/test/intltest/loctest.cpp b/icu4c/source/test/intltest/loctest.cpp index 3180645ad1ae..1eb1574561f0 100644 --- a/icu4c/source/test/intltest/loctest.cpp +++ b/icu4c/source/test/intltest/loctest.cpp @@ -310,7 +310,7 @@ void LocaleTest::TestBasicGetters() { else { testLocale = Locale(rawData[LANG][i], rawData[CTRY][i], rawData[VAR][i]); } - logln("Testing " + (UnicodeString)testLocale.getName() + "..."); + logln("Testing " + UnicodeString(testLocale.getName()) + "..."); if ( (temp=testLocale.getLanguage()) != (dataTable[LANG][i])) errln(" Language code mismatch: " + temp + " versus " @@ -557,14 +557,14 @@ void LocaleTest::TestSimpleResourceInfo() { errln(" ISO-3 country code mismatch: " + temp + " versus " + dataTable[CTRY3][i]); - snprintf(temp2, sizeof(temp2), "%x", (int)testLocale.getLCID()); + snprintf(temp2, sizeof(temp2), "%x", static_cast(testLocale.getLCID())); if (UnicodeString(temp2) != dataTable[LCID][i]) - errln((UnicodeString)" LCID mismatch: " + temp2 + " versus " + errln(UnicodeString(" LCID mismatch: ") + temp2 + " versus " + dataTable[LCID][i]); if(U_FAILURE(err)) { - errln((UnicodeString)"Some error on number " + i + u_errorName(err)); + errln(UnicodeString("Some error on number ") + i + u_errorName(err)); } err = U_ZERO_ERROR; } @@ -1003,7 +1003,7 @@ LocaleTest::TestGetLangsAndCountries() if (uprv_strcmp(test[j],spotCheck1[i])== 0) break; if (j == testCount || (uprv_strcmp(test[j],spotCheck1[i])!=0)) - errln("Couldn't find " + (UnicodeString)spotCheck1[i] + " in language list."); + errln("Couldn't find " + UnicodeString(spotCheck1[i]) + " in language list."); } } for (i = 0; i < testCount; i++) { @@ -1354,7 +1354,7 @@ LocaleTest::TestEuroSupport() delete nf; } - UnicodeString dollarStr("USD", ""), euroStr("EUR", ""), genericStr((char16_t)0x00a4), resultStr; + UnicodeString dollarStr("USD", ""), euroStr("EUR", ""), genericStr(static_cast(0x00a4)), resultStr; char16_t tmp[4]; status = U_ZERO_ERROR; @@ -1714,7 +1714,7 @@ LocaleTest::Test4105828() } UnicodeString result; FieldPosition pos(FieldPosition::DONT_CARE); - fmt->format((int32_t)1, result, pos); + fmt->format(static_cast(1), result, pos); UnicodeString temp; if(result != "100%") { errln(UnicodeString("Percent for ") + LOC[i].getDisplayName(temp) + " should be 100%, got " + result); @@ -4649,8 +4649,8 @@ LocaleTest::TestGetBaseName() { * prefix + '_' + x, then return 1. Otherwise return a value < 0. */ static UBool _loccmp(const char* string, const char* prefix) { - int32_t slen = (int32_t)strlen(string), - plen = (int32_t)strlen(prefix); + int32_t slen = static_cast(strlen(string)), + plen = static_cast(strlen(prefix)); int32_t c = uprv_strncmp(string, prefix, plen); /* 'root' is "less than" everything */ if (prefix[0] == '\0') { @@ -5383,7 +5383,7 @@ void LocaleTest::TestCurrencyByDate() UnicodeString tempStr, resultStr; // Cycle through historical currencies - date = (UDate)-630720000000.0; // pre 1961 - no currency defined + date = static_cast(-630720000000.0); // pre 1961 - no currency defined index = ucurr_countCurrencies("eo_AM", date, &status); if (index != 0) { @@ -5395,7 +5395,7 @@ void LocaleTest::TestCurrencyByDate() } status = U_ZERO_ERROR; - date = (UDate)0.0; // 1970 - one currency defined + date = static_cast(0.0); // 1970 - one currency defined index = ucurr_countCurrencies("eo_AM", date, &status); if (index != 1) { @@ -5408,7 +5408,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return SUR for eo_AM - %s", u_errorName(status)); } - date = (UDate)693792000000.0; // 1992 - one currency defined + date = static_cast(693792000000.0); // 1992 - one currency defined index = ucurr_countCurrencies("eo_AM", date, &status); if (index != 1) { @@ -5421,7 +5421,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return RUR for eo_AM - %s", u_errorName(status)); } - date = (UDate)977616000000.0; // post 1993 - one currency defined + date = static_cast(977616000000.0); // post 1993 - one currency defined index = ucurr_countCurrencies("eo_AM", date, &status); if (index != 1) { @@ -5435,7 +5435,7 @@ void LocaleTest::TestCurrencyByDate() } // Locale AD has multiple currencies at once - date = (UDate)977616000000.0; // year 2001 + date = static_cast(977616000000.0); // year 2001 index = ucurr_countCurrencies("eo_AD", date, &status); if (index != 4) { @@ -5466,7 +5466,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status)); } - date = (UDate)0.0; // year 1970 + date = static_cast(0.0); // year 1970 index = ucurr_countCurrencies("eo_AD", date, &status); if (index != 3) { @@ -5491,7 +5491,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status)); } - date = (UDate)-630720000000.0; // year 1950 + date = static_cast(-630720000000.0); // year 1950 index = ucurr_countCurrencies("eo_AD", date, &status); if (index != 2) { @@ -5510,7 +5510,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status)); } - date = (UDate)-2207520000000.0; // year 1900 + date = static_cast(-2207520000000.0); // year 1900 index = ucurr_countCurrencies("eo_AD", date, &status); if (index != 1) { @@ -5524,7 +5524,7 @@ void LocaleTest::TestCurrencyByDate() } // Locale UA has gap between years 1994 - 1996 - date = (UDate)788400000000.0; + date = static_cast(788400000000.0); index = ucurr_countCurrencies("eo_UA", date, &status); if (index != 0) { @@ -5568,7 +5568,7 @@ void LocaleTest::TestCurrencyByDate() status = U_ZERO_ERROR; // Cycle through histrocial currencies - date = (UDate)977616000000.0; // 2001 - one currency + date = static_cast(977616000000.0); // 2001 - one currency index = ucurr_countCurrencies("eo_AO", date, &status); if (index != 1) { @@ -5581,7 +5581,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return AOA for eo_AO - %s", u_errorName(status)); } - date = (UDate)819936000000.0; // 1996 - 2 currencies + date = static_cast(819936000000.0); // 1996 - 2 currencies index = ucurr_countCurrencies("eo_AO", date, &status); if (index != 2) { @@ -5600,7 +5600,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return AON for eo_AO - %s", u_errorName(status)); } - date = (UDate)662256000000.0; // 1991 - 2 currencies + date = static_cast(662256000000.0); // 1991 - 2 currencies index = ucurr_countCurrencies("eo_AO", date, &status); if (index != 2) { @@ -5619,7 +5619,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return AOK for eo_AO - %s", u_errorName(status)); } - date = (UDate)315360000000.0; // 1980 - one currency + date = static_cast(315360000000.0); // 1980 - one currency index = ucurr_countCurrencies("eo_AO", date, &status); if (index != 1) { @@ -5632,7 +5632,7 @@ void LocaleTest::TestCurrencyByDate() errcheckln(status, "FAIL: didn't return AOK for eo_AO - %s", u_errorName(status)); } - date = (UDate)0.0; // 1970 - no currencies + date = static_cast(0.0); // 1970 - no currencies index = ucurr_countCurrencies("eo_AO", date, &status); if (index != 0) { @@ -5645,7 +5645,7 @@ void LocaleTest::TestCurrencyByDate() status = U_ZERO_ERROR; // Test with currency keyword override - date = (UDate)977616000000.0; // 2001 - two currencies + date = static_cast(977616000000.0); // 2001 - two currencies index = ucurr_countCurrencies("eo_DE@currency=DEM", date, &status); if (index != 2) { @@ -5829,7 +5829,7 @@ void LocaleTest::TestLocaleCanonicalizationFromFile() } // Format: // ; - while (fgets(line, (int)sizeof(line), testFile.getAlias())!=nullptr) { + while (fgets(line, static_cast(sizeof(line)), testFile.getAlias()) != nullptr) { if (line[0] == '#') { // ignore any lines start with # continue; @@ -5841,9 +5841,9 @@ void LocaleTest::TestLocaleCanonicalizationFromFile() } *semi = '\0'; // null terminiate on the spot of semi const char* from = u_skipWhitespace((const char*)line); - u_rtrim((char*)from); + u_rtrim(const_cast(from)); const char* to = u_skipWhitespace((const char*)semi + 1); - u_rtrim((char*)to); + u_rtrim(const_cast(to)); std::string expect(to); // Change the _ to - std::transform(expect.begin(), expect.end(), expect.begin(), @@ -5894,7 +5894,7 @@ testLikelySubtagsLineFn(void *context, return; } (void)fieldCount; - LocaleTest* THIS = (LocaleTest*)context; + LocaleTest* THIS = static_cast(context); std::string source(trim(std::string(fields[0][0], fields[0][1]-fields[0][0]))); std::string addLikely(trim(std::string(fields[1][0], fields[1][1]-fields[1][0]))); std::string removeFavorScript(trim(std::string(fields[2][0], fields[2][1]-fields[2][0]))); diff --git a/icu4c/source/test/intltest/measfmttest.cpp b/icu4c/source/test/intltest/measfmttest.cpp index 847aacb96fa5..fbe71bdf8873 100644 --- a/icu4c/source/test/intltest/measfmttest.cpp +++ b/icu4c/source/test/intltest/measfmttest.cpp @@ -4340,17 +4340,17 @@ void MeasureFormatTest::TestExamplesInDocs() { if (!assertSuccess("Error creating formatters", status)) { return; } - Measure measureC((double)23, MeasureUnit::createCelsius(status), status); - Measure measureF((double)70, MeasureUnit::createFahrenheit(status), status); + Measure measureC(static_cast(23), MeasureUnit::createCelsius(status), status); + Measure measureF(static_cast(70), MeasureUnit::createFahrenheit(status), status); Measure feetAndInches[] = { - Measure((double)70, MeasureUnit::createFoot(status), status), - Measure((double)5.3, MeasureUnit::createInch(status), status)}; + Measure(static_cast(70), MeasureUnit::createFoot(status), status), + Measure(5.3, MeasureUnit::createInch(status), status)}; Measure footAndInch[] = { - Measure((double)1, MeasureUnit::createFoot(status), status), - Measure((double)1, MeasureUnit::createInch(status), status)}; + Measure(static_cast(1), MeasureUnit::createFoot(status), status), + Measure(static_cast(1), MeasureUnit::createInch(status), status)}; Measure inchAndFeet[] = { - Measure((double)1, MeasureUnit::createInch(status), status), - Measure((double)2, MeasureUnit::createFoot(status), status)}; + Measure(static_cast(1), MeasureUnit::createInch(status), status), + Measure(static_cast(2), MeasureUnit::createFoot(status), status)}; if (!assertSuccess("Error creating measurements.", status)) { return; } @@ -4408,32 +4408,32 @@ void MeasureFormatTest::TestExamplesInDocs() { void MeasureFormatTest::TestFormatPeriodEn() { UErrorCode status = U_ZERO_ERROR; - Measure t_1y[] = {Measure((double)1, MeasureUnit::createYear(status), status)}; - Measure t_5M[] = {Measure((double)5, MeasureUnit::createMonth(status), status)}; - Measure t_4d[] = {Measure((double)4, MeasureUnit::createDay(status), status)}; - Measure t_2h[] = {Measure((double)2, MeasureUnit::createHour(status), status)}; - Measure t_19m[] = {Measure((double)19, MeasureUnit::createMinute(status), status)}; + Measure t_1y[] = {Measure(static_cast(1), MeasureUnit::createYear(status), status)}; + Measure t_5M[] = {Measure(static_cast(5), MeasureUnit::createMonth(status), status)}; + Measure t_4d[] = {Measure(static_cast(4), MeasureUnit::createDay(status), status)}; + Measure t_2h[] = {Measure(static_cast(2), MeasureUnit::createHour(status), status)}; + Measure t_19m[] = {Measure(static_cast(19), MeasureUnit::createMinute(status), status)}; Measure t_1h_23_5s[] = { - Measure((double)1.0, MeasureUnit::createHour(status), status), - Measure((double)23.5, MeasureUnit::createSecond(status), status) + Measure(1.0, MeasureUnit::createHour(status), status), + Measure(23.5, MeasureUnit::createSecond(status), status) }; Measure t_1h_23_5m[] = { - Measure((double)1.0, MeasureUnit::createHour(status), status), - Measure((double)23.5, MeasureUnit::createMinute(status), status) + Measure(1.0, MeasureUnit::createHour(status), status), + Measure(23.5, MeasureUnit::createMinute(status), status) }; Measure t_1h_0m_23s[] = { Measure( - (double)1.0, + 1.0, TimeUnit::createInstance( TimeUnit::UTIMEUNIT_HOUR, status), status), Measure( - (double)0.0, + 0.0, TimeUnit::createInstance( TimeUnit::UTIMEUNIT_MINUTE, status), status), Measure( - (double)23.0, + 23.0, TimeUnit::createInstance( TimeUnit::UTIMEUNIT_SECOND, status), status) @@ -5110,14 +5110,14 @@ void MeasureFormatTest::helperTestManyLocaleDurations( const char *localeID, UErrorCode status = U_ZERO_ERROR; MeasureFormat fmt(Locale(localeID), width, status); if (U_FAILURE(status)) { - errln("Could not create MeasureFormat for locale %s, width %d, status: %s", localeID, (int)width, u_errorName(status)); + errln("Could not create MeasureFormat for locale %s, width %d, status: %s", localeID, static_cast(width), u_errorName(status)); return; } UnicodeString buffer; FieldPosition pos(FieldPosition::DONT_CARE); fmt.formatMeasures(measures, measureCount, buffer, pos, status); if (U_FAILURE(status)) { - errln("MeasureFormat::formatMeasures failed for locale %s, width %d, status: %s", localeID, (int)width, u_errorName(status)); + errln("MeasureFormat::formatMeasures failed for locale %s, width %d, status: %s", localeID, static_cast(width), u_errorName(status)); return; } UnicodeString expStr(UnicodeString(expected).unescape()); @@ -5132,8 +5132,8 @@ void MeasureFormatTest::TestGram() { if (!assertSuccess("Error creating format object", status)) { return; } - Measure gram((double)1, MeasureUnit::createGram(status), status); - Measure gforce((double)1, MeasureUnit::createGForce(status), status); + Measure gram(static_cast(1), MeasureUnit::createGram(status), status); + Measure gforce(static_cast(1), MeasureUnit::createGForce(status), status); if (!assertSuccess("Error creating measures", status)) { return; } @@ -5222,21 +5222,21 @@ void MeasureFormatTest::helperTestDisplayName(const MeasureUnit *unit, MeasureFormat fmt(Locale(localeID), width, status); if (U_FAILURE(status)) { errln("Could not create MeasureFormat for locale %s, width %d, status: %s", - localeID, (int)width, u_errorName(status)); + localeID, static_cast(width), u_errorName(status)); return; } UnicodeString dnam = fmt.getUnitDisplayName(*unit, status); if (U_FAILURE(status)) { errln("MeasureFormat::getUnitDisplayName failed for unit %s-%s, locale %s, width %d, status: %s", - unit->getType(), unit->getSubtype(), localeID, (int)width, u_errorName(status)); + unit->getType(), unit->getSubtype(), localeID, static_cast(width), u_errorName(status)); return; } UnicodeString expStr(UnicodeString(expected).unescape()); if (dnam != expStr) { errln("MeasureFormat::getUnitDisplayName for unit %s-%s, locale %s, width %d: expected \"%s\", got \"%s\"", - unit->getType(), unit->getSubtype(), localeID, (int)width, CStr(expStr)(), CStr(dnam)()); + unit->getType(), unit->getSubtype(), localeID, static_cast(width), CStr(expStr)(), CStr(dnam)()); } // Delete the measure unit @@ -5285,16 +5285,16 @@ void MeasureFormatTest::TestFieldPositionMultiple() { return; } Measure first[] = { - Measure((double)354, MeasureUnit::createMeter(status), status), - Measure((double)23, MeasureUnit::createCentimeter(status), status)}; + Measure(static_cast(354), MeasureUnit::createMeter(status), status), + Measure(static_cast(23), MeasureUnit::createCentimeter(status), status)}; Measure second[] = { - Measure((double)354, MeasureUnit::createMeter(status), status), - Measure((double)23, MeasureUnit::createCentimeter(status), status), - Measure((double)5.4, MeasureUnit::createMillimeter(status), status)}; + Measure(static_cast(354), MeasureUnit::createMeter(status), status), + Measure(static_cast(23), MeasureUnit::createCentimeter(status), status), + Measure(5.4, MeasureUnit::createMillimeter(status), status)}; Measure third[] = { - Measure((double)3, MeasureUnit::createMeter(status), status), - Measure((double)23, MeasureUnit::createCentimeter(status), status), - Measure((double)5, MeasureUnit::createMillimeter(status), status)}; + Measure(static_cast(3), MeasureUnit::createMeter(status), status), + Measure(static_cast(23), MeasureUnit::createCentimeter(status), status), + Measure(static_cast(5), MeasureUnit::createMillimeter(status), status)}; if (!assertSuccess("Error creating measure objects", status)) { return; } @@ -5377,8 +5377,8 @@ void MeasureFormatTest::TestGroupingSeparator() { return; } Measure ms[] = { - Measure((int32_t)INT32_MAX, MeasureUnit::createYear(status), status), - Measure((int32_t)INT32_MIN, MeasureUnit::createMonth(status), status), + Measure(static_cast(INT32_MAX), MeasureUnit::createYear(status), status), + Measure(static_cast(INT32_MIN), MeasureUnit::createMonth(status), status), Measure(-987.0, MeasureUnit::createDay(status), status), Measure(1362.0, MeasureUnit::createHour(status), status), Measure(987.0, MeasureUnit::createMinute(status), status)}; @@ -5726,7 +5726,7 @@ void MeasureFormatTest::TestIdentifierDetails() { static_assert(UMEASURE_PREFIX_INTERNAL_MAX_SI < 99, "Tests assume there is no prefix 99."); static_assert(UMEASURE_PREFIX_INTERNAL_MAX_BIN < 99, "Tests assume there is no prefix 99."); - MeasureUnit unit = joule.withPrefix((UMeasurePrefix)99, status); + MeasureUnit unit = joule.withPrefix(static_cast(99), status); if (!status.expectErrorAndReset(U_UNSUPPORTED_ERROR)) { errln("Invalid prefix should result in an error."); } diff --git a/icu4c/source/test/intltest/messageformat2test.cpp b/icu4c/source/test/intltest/messageformat2test.cpp index a7137d8493a0..524ee4ab79d9 100644 --- a/icu4c/source/test/intltest/messageformat2test.cpp +++ b/icu4c/source/test/intltest/messageformat2test.cpp @@ -103,7 +103,7 @@ void TestMessageFormat2::testAPISimple() { assertEquals("testAPI", "Today is Sunday, October 28, 2136.", result); argsBuilder.clear(); - argsBuilder["photoCount"] = message2::Formattable((int64_t) 12); + argsBuilder["photoCount"] = message2::Formattable(static_cast(12)); argsBuilder["userGender"] = message2::Formattable("feminine"); argsBuilder["userName"] = message2::Formattable("Maria"); args = MessageArguments(argsBuilder, errorCode); diff --git a/icu4c/source/test/intltest/messageformat2test_custom.cpp b/icu4c/source/test/intltest/messageformat2test_custom.cpp index 2d7d89ee24c2..b498be791ca9 100644 --- a/icu4c/source/test/intltest/messageformat2test_custom.cpp +++ b/icu4c/source/test/intltest/messageformat2test_custom.cpp @@ -139,7 +139,7 @@ void TestMessageFormat2::testCustomFunctionsComplexMessage(IcuTestErrorCode& err TestCase test = testBuilder.setArgument(host, jane.getAlias()) .setArgument(hostGender, "female") .setArgument(guest, john.getAlias()) - .setArgument(guestCount, (int64_t) 3) + .setArgument(guestCount, static_cast(3)) .setExpected("Ms. Jane Doe invites 3 people, including Mr. John Doe, to her party.") .setExpectSuccess() .build(); @@ -148,7 +148,7 @@ void TestMessageFormat2::testCustomFunctionsComplexMessage(IcuTestErrorCode& err test = testBuilder.setArgument(host, jane.getAlias()) .setArgument(hostGender, "female") .setArgument(guest, john.getAlias()) - .setArgument(guestCount, (int64_t) 2) + .setArgument(guestCount, static_cast(2)) .setExpected("Ms. Jane Doe invites Mr. John Doe and one other person to her party.") .setExpectSuccess() .build(); @@ -157,7 +157,7 @@ void TestMessageFormat2::testCustomFunctionsComplexMessage(IcuTestErrorCode& err test = testBuilder.setArgument(host, jane.getAlias()) .setArgument(hostGender, "female") .setArgument(guest, john.getAlias()) - .setArgument(guestCount, (int64_t) 1) + .setArgument(guestCount, static_cast(1)) .setExpected("Ms. Jane Doe invites Mr. John Doe to her party.") .setExpectSuccess() .build(); @@ -166,7 +166,7 @@ void TestMessageFormat2::testCustomFunctionsComplexMessage(IcuTestErrorCode& err test = testBuilder.setArgument(host, john.getAlias()) .setArgument(hostGender, "male") .setArgument(guest, jane.getAlias()) - .setArgument(guestCount, (int64_t) 3) + .setArgument(guestCount, static_cast(3)) .setExpected("Mr. John Doe invites 3 people, including Ms. Jane Doe, to his party.") .setExpectSuccess() .build(); @@ -175,7 +175,7 @@ void TestMessageFormat2::testCustomFunctionsComplexMessage(IcuTestErrorCode& err test = testBuilder.setArgument(host, anonymous.getAlias()) .setArgument(hostGender, "unknown") .setArgument(guest, jane.getAlias()) - .setArgument(guestCount, (int64_t) 2) + .setArgument(guestCount, static_cast(2)) .setExpected("Mx. Anonymous Doe invites Ms. Jane Doe and one other person to their party.") .setExpectSuccess() .build(); @@ -673,7 +673,7 @@ void TestMessageFormat2::testMessageRefFormatter(IcuTestErrorCode& errorCode) { TestCase::Builder testBuilder; testBuilder.setLocale(Locale("ro")); testBuilder.setFunctionRegistry(®); - testBuilder.setPattern(*((UnicodeString*) properties->get("firefox"))); + testBuilder.setPattern(*static_cast(properties->get("firefox"))); testBuilder.setName("message-ref"); TestCase test = testBuilder.setArgument("gcase", "whatever") @@ -685,7 +685,7 @@ void TestMessageFormat2::testMessageRefFormatter(IcuTestErrorCode& errorCode) { .build(); TestUtils::runTestCase(*this, test, errorCode); - testBuilder.setPattern(*((UnicodeString*) properties->get("chrome"))); + testBuilder.setPattern(*static_cast(properties->get("chrome"))); test = testBuilder.setArgument("gcase", "whatever") .setExpected("Chrome") diff --git a/icu4c/source/test/intltest/miscdtfm.cpp b/icu4c/source/test/intltest/miscdtfm.cpp index 535db88c7781..cae3b801ad85 100644 --- a/icu4c/source/test/intltest/miscdtfm.cpp +++ b/icu4c/source/test/intltest/miscdtfm.cpp @@ -114,7 +114,7 @@ DateFormatMiscTests::test4097450() UErrorCode status = U_ZERO_ERROR; LocalPointer formatter; - SimpleDateFormat resultFormatter((UnicodeString)u"yyyy", status); + SimpleDateFormat resultFormatter(UnicodeString(u"yyyy"), status); if (U_FAILURE(status)) { dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status)); return; diff --git a/icu4c/source/test/intltest/mnkytst.cpp b/icu4c/source/test/intltest/mnkytst.cpp index 3bb695011270..f9200f895c56 100644 --- a/icu4c/source/test/intltest/mnkytst.cpp +++ b/icu4c/source/test/intltest/mnkytst.cpp @@ -54,7 +54,7 @@ CollationMonkeyTest::report(UnicodeString& s, UnicodeString& t, int32_t result, msg += " and "; msg += t; msg += " round trip comparison failed"; - msg += (UnicodeString) " (result " + result + ", reverse Result " + revResult + ")"; + msg += UnicodeString(" (result ") + result + ", reverse Result " + revResult + ")"; errln(msg); } @@ -78,7 +78,7 @@ void CollationMonkeyTest::TestCollationKey(/* char* par */) return; } - srand( (unsigned)time( nullptr ) ); + srand(static_cast(time(nullptr))); int32_t s = checkValue(rand() % source.length()); int32_t t = checkValue(rand() % source.length()); int32_t slen = checkValue((rand() - source.length()) % source.length()); @@ -114,7 +114,7 @@ void CollationMonkeyTest::TestCollationKey(/* char* par */) UnicodeString msg; UnicodeString addOne(subs); - addOne += (UChar32)0xE000; + addOne += static_cast(0xE000); myCollator->getCollationKey(subs, collationKey1, status1); myCollator->getCollationKey(addOne, collationKey2, status2); @@ -153,7 +153,7 @@ CollationMonkeyTest::TestCompare(/* char* par */) /* Seed the random-number generator with current time so that * the numbers will be different every time we run. */ - srand( (unsigned)time( nullptr ) ); + srand(static_cast(time(nullptr))); int32_t s = checkValue(rand() % source.length()); int32_t t = checkValue(rand() % source.length()); int32_t slen = checkValue((rand() - source.length()) % source.length()); @@ -180,7 +180,7 @@ CollationMonkeyTest::TestCompare(/* char* par */) UnicodeString msg; UnicodeString addOne(subs); - addOne += (UChar32)0xE000; + addOne += static_cast(0xE000); result = myCollator->compare(subs, addOne); if (result != -1) @@ -222,7 +222,7 @@ void CollationMonkeyTest::TestRules(/* char* par */){ Collator *col = Collator::createInstance("en_US", status); const UnicodeString baseRules = (dynamic_cast(col))->getRules(); UnicodeString newRules(" & z < "); - newRules.append((char16_t)0x00e4); + newRules.append(static_cast(0x00e4)); newRules.insert(0, baseRules); RuleBasedCollator *myCollation = new RuleBasedCollator(newRules, status); if (U_FAILURE(status)) { @@ -237,7 +237,7 @@ void CollationMonkeyTest::TestRules(/* char* par */){ logln("Demo Test 2 : Create a new table collation with rules \"& z < a 0x0308\""); newRules.remove(); newRules.append(" & z < a"); - newRules.append((char16_t)0x0308); + newRules.append(static_cast(0x0308)); newRules.insert(0, baseRules); myCollation = new RuleBasedCollator(newRules, status); if (U_FAILURE(status)) { diff --git a/icu4c/source/test/intltest/msfmrgts.cpp b/icu4c/source/test/intltest/msfmrgts.cpp index ec031b1d6c1e..156fdcbc7560 100644 --- a/icu4c/source/test/intltest/msfmrgts.cpp +++ b/icu4c/source/test/intltest/msfmrgts.cpp @@ -195,7 +195,7 @@ void MessageFormatRegressionTest::Test4031438() failure(status, "messageFormat->applyPattern"); //Object[] params = {new Integer(7)}; Formattable params []= { - Formattable((int32_t)7) + Formattable(static_cast(7)) }; UnicodeString tempBuffer; FieldPosition pos(FieldPosition::DONT_CARE); @@ -402,7 +402,7 @@ void MessageFormatRegressionTest::Test4106660() FieldPosition pos(FieldPosition::DONT_CARE); str = cf->format(d, str, pos); if (str != "Two") - errln( (UnicodeString) "format(" + d + ") = " + str); + errln(UnicodeString("format(") + d + ") = " + str); delete cf; } @@ -477,9 +477,9 @@ void MessageFormatRegressionTest::Test4114743() void MessageFormatRegressionTest::Test4116444() { UnicodeString patterns [] = { - (UnicodeString)"", - (UnicodeString)"one", - (UnicodeString) "{0,date,short}" + UnicodeString(""), + UnicodeString("one"), + UnicodeString("{0,date,short}") }; UErrorCode status = U_ZERO_ERROR; @@ -607,7 +607,7 @@ void MessageFormatRegressionTest::Test4106661() logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); - logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status)); + logln("Format with 0 : " + fmt->format(Formattable(static_cast(0)), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status)); @@ -619,7 +619,7 @@ void MessageFormatRegressionTest::Test4106661() logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status)); failure(status, "fmt->format"); str.remove(); - logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status)); + logln("Format with 2 : " + fmt->format(Formattable(static_cast(2)), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status)); @@ -641,17 +641,17 @@ void MessageFormatRegressionTest::Test4094906() { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern("-"); - pattern += (char16_t) 0x221E; + pattern += static_cast(0x221E); pattern += "(0x221E); pattern += "toPattern(pat) != pattern) { - errln( (UnicodeString) "Formatter Pattern : " + pat); - errln( (UnicodeString) "Expected Pattern : " + pattern); + errln(UnicodeString("Formatter Pattern : ") + pat); + errln(UnicodeString("Expected Pattern : ") + pattern); } FieldPosition bogus(FieldPosition::DONT_CARE); UnicodeString str; @@ -666,7 +666,7 @@ void MessageFormatRegressionTest::Test4094906() logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); - logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status)); + logln("Format with 0 : " + fmt->format(Formattable(static_cast(0)), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status)); @@ -678,7 +678,7 @@ void MessageFormatRegressionTest::Test4094906() logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status)); failure(status, "fmt->format"); str.remove(); - logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status)); + logln("Format with 2 : " + fmt->format(Formattable(static_cast(2)), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status)); @@ -723,9 +723,9 @@ void MessageFormatRegressionTest::Test4118592() else { UnicodeString temp; if(objs[0].getType() == Formattable::kString) - logln((UnicodeString)" " + objs[0].getString(temp)); + logln(UnicodeString(" ") + objs[0].getString(temp)); else - logln((UnicodeString)" " + (objs[0].getType() == Formattable::kLong ? objs[0].getLong() : objs[0].getDouble())); + logln(UnicodeString(" ") + (objs[0].getType() == Formattable::kLong ? objs[0].getLong() : objs[0].getDouble())); delete[] objs; } @@ -798,17 +798,17 @@ void MessageFormatRegressionTest::Test4105380() failure(status, "new MessageFormat"); double filelimits [] = {0,1,2}; UnicodeString filepart [] = { - (UnicodeString)"no files", - (UnicodeString)"one file", - (UnicodeString)"{0,number} files" + UnicodeString("no files"), + UnicodeString("one file"), + UnicodeString("{0,number} files") }; ChoiceFormat *fileform = new ChoiceFormat(filelimits, filepart, 3); form1->setFormat(1, *fileform); form2->setFormat(0, *fileform); //Object[] testArgs = {new Long(12373), "MyDisk"}; Formattable testArgs [] = { - Formattable((int32_t)12373), - Formattable((UnicodeString)"MyDisk") + Formattable(static_cast(12373)), + Formattable(UnicodeString("MyDisk")) }; FieldPosition bogus(FieldPosition::DONT_CARE); @@ -833,9 +833,9 @@ void MessageFormatRegressionTest::Test4120552() MessageFormat *mf = new MessageFormat("pattern", status); failure(status, "new MessageFormat"); UnicodeString texts[] = { - (UnicodeString)"pattern", - (UnicodeString)"pat", - (UnicodeString)"1234" + UnicodeString("pattern"), + UnicodeString("pat"), + UnicodeString("1234") }; UnicodeString pat; logln("pattern: \"" + mf->toPattern(pat) + "\""); @@ -887,19 +887,19 @@ void MessageFormatRegressionTest::Test4142938() UnicodeString out; //out = mf->format(new Object[]{new Integer(i)}); Formattable objs [] = { - Formattable((int32_t)i) + Formattable(static_cast(i)) }; FieldPosition pos(FieldPosition::DONT_CARE); out = mf->format(objs, 1, out, pos, status); if (!failure(status, "mf->format", true)) { if (SUFFIX[i] == "") { if (out != PREFIX[i]) - errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\""); + errln(UnicodeString("") + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\""); } else { if (!out.startsWith(PREFIX[i]) || !out.endsWith(SUFFIX[i])) - errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"...\"" + + errln(UnicodeString("") + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"...\"" + SUFFIX[i] + "\""); } } @@ -942,7 +942,7 @@ void MessageFormatRegressionTest::TestChoicePatternQuote() for (int j=0; j<=1; ++j) { UnicodeString out; FieldPosition pos(FieldPosition::DONT_CARE); - out = cf->format((double)j, out, pos); + out = cf->format(static_cast(j), out, pos); if (out != DATA[i+1+j]) errln("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " + out + "; want \"" + DATA[i+1+j] + "\""); @@ -1043,7 +1043,7 @@ void MessageFormatRegressionTest::TestAPI() { failure(status, "adoptFormat"); // Test getFormat - format->setFormat((int32_t)0,*fmt); + format->setFormat(static_cast(0), *fmt); format->getFormat("some_other_name",status); // Must at least pass a valid identifier. failure(status, "getFormat"); delete format; diff --git a/icu4c/source/test/intltest/nmfmapts.cpp b/icu4c/source/test/intltest/nmfmapts.cpp index 77e56ffd37e9..5be1a23684c9 100644 --- a/icu4c/source/test/intltest/nmfmapts.cpp +++ b/icu4c/source/test/intltest/nmfmapts.cpp @@ -125,30 +125,30 @@ if (cur_fr != nullptr) FieldPosition pos1(FieldPosition::DONT_CARE), pos2(FieldPosition::DONT_CARE), pos3(FieldPosition::DONT_CARE), pos4(FieldPosition::DONT_CARE); res1 = cur_fr->format(d, res1); - logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res1); + logln(UnicodeString("") + static_cast(d) + " formatted to " + res1); res2 = cur_fr->format(l, res2); - logln((UnicodeString) "" + (int32_t) l + " formatted to " + res2); + logln(UnicodeString("") + l + " formatted to " + res2); res3 = cur_fr->format(d, res3, pos1); - logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res3); + logln(UnicodeString("") + static_cast(d) + " formatted to " + res3); res4 = cur_fr->format(l, res4, pos2); - logln((UnicodeString) "" + (int32_t) l + " formatted to " + res4); + logln(UnicodeString("") + l + " formatted to " + res4); status = U_ZERO_ERROR; res5 = cur_fr->format(fD, res5, pos3, status); if(U_FAILURE(status)) { errln("ERROR: format(Formattable [double]) failed"); } - logln((UnicodeString) "" + (int32_t) fD.getDouble() + " formatted to " + res5); + logln(UnicodeString("") + static_cast(fD.getDouble()) + " formatted to " + res5); status = U_ZERO_ERROR; res6 = cur_fr->format(fL, res6, pos4, status); if(U_FAILURE(status)) { errln("ERROR: format(Formattable [long]) failed"); } - logln((UnicodeString) "" + fL.getLong() + " formatted to " + res6); + logln(UnicodeString("") + fL.getLong() + " formatted to " + res6); } // ======= Test parse() @@ -164,13 +164,13 @@ if (fr != nullptr) if(result1.getType() != Formattable::kDouble && result1.getDouble() != d) { errln("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + (int32_t) result1.getDouble()); + logln(text + " parsed into " + static_cast(result1.getDouble())); fr->parse(text, result2, pos01); if(result2.getType() != Formattable::kDouble && result2.getDouble() != d) { errln("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + (int32_t) result2.getDouble()); + logln(text + " parsed into " + static_cast(result2.getDouble())); status = U_ZERO_ERROR; fr->parse(text, result3, status); @@ -180,7 +180,7 @@ if (fr != nullptr) if(result3.getType() != Formattable::kDouble && result3.getDouble() != d) { errln("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + (int32_t) result3.getDouble()); + logln(text + " parsed into " + static_cast(result3.getDouble())); } // ======= Test getters and setters @@ -190,7 +190,7 @@ if (fr != nullptr && def != nullptr) int32_t count = 0; const Locale *locales = NumberFormat::getAvailableLocales(count); - logln((UnicodeString) "Got " + count + " locales" ); + logln(UnicodeString("Got ") + count + " locales"); for(int32_t i = 0; i < count; i++) { UnicodeString name(locales[i].getName(),""); logln(name); @@ -345,12 +345,12 @@ IntlTestNumberFormatAPI::testRegistration() unum_formatDouble(uf4.getAlias(), n, ures4, 50, nullptr, &status); unum_formatDouble(uf5.getAlias(), n, ures5, 50, nullptr, &status); - logln((UnicodeString)"f0 swap int: " + res0); - logln((UnicodeString)"f1 src int: " + res1); - logln((UnicodeString)"f2 src cur: " + res2); - logln((UnicodeString)"f3 reg cur: " + res3); - logln((UnicodeString)"f4 reg int: " + res4); - logln((UnicodeString)"f5 unreg cur: " + res5); + logln(UnicodeString("f0 swap int: ") + res0); + logln(UnicodeString("f1 src int: ") + res1); + logln(UnicodeString("f2 src cur: ") + res2); + logln(UnicodeString("f3 reg cur: ") + res3); + logln(UnicodeString("f4 reg int: ") + res4); + logln(UnicodeString("f5 unreg cur: ") + res5); log("uf3 reg cur: "); logln(ures3); log("uf4 reg int: "); diff --git a/icu4c/source/test/intltest/nmfmtrt.cpp b/icu4c/source/test/intltest/nmfmtrt.cpp index 6111ad25e258..b8c7d3196b42 100644 --- a/icu4c/source/test/intltest/nmfmtrt.cpp +++ b/icu4c/source/test/intltest/nmfmtrt.cpp @@ -67,10 +67,10 @@ NumberFormatRoundTripTest::randLong() // that the system rand() function is very poor, which it always is. uint32_t d; uint32_t i; - char* poke = (char*)&d; + char* poke = reinterpret_cast(&d); for (i=0; i < sizeof(uint32_t); ++i) { - poke[i] = (char)(rand() & 0xFF); + poke[i] = static_cast(rand() & 0xFF); } return d; } @@ -155,9 +155,9 @@ NumberFormatRoundTripTest::test(NumberFormat *fmt) test(fmt, -uprv_getInfinity()); #endif - test(fmt, (int32_t)500); - test(fmt, (int32_t)0); - test(fmt, (int32_t)-0); + test(fmt, static_cast(500)); + test(fmt, static_cast(0)); + test(fmt, static_cast(-0)); test(fmt, 0.0); double negZero = 0.0; negZero /= -1.0; test(fmt, negZero); @@ -297,7 +297,7 @@ NumberFormatRoundTripTest::test(NumberFormat *fmt, const Formattable& value) if (show) { errln(/*value.getString(temp) +*/ typeOf(value, temp) + " F> " + - escape(s) + " P> " + (n.getType() == Formattable::kDouble ? n.getDouble() : (double)n.getLong()) + escape(s) + " P> " + (n.getType() == Formattable::kDouble ? n.getDouble() : static_cast(n.getLong())) /*n.getString(temp) */ + typeOf(n, temp) + " F> " + escape(s2)); } diff --git a/icu4c/source/test/intltest/nmfmtrt.h b/icu4c/source/test/intltest/nmfmtrt.h index 0f7e17f059b2..add908a21936 100644 --- a/icu4c/source/test/intltest/nmfmtrt.h +++ b/icu4c/source/test/intltest/nmfmtrt.h @@ -65,7 +65,7 @@ class NumberFormatRoundTripTest : public IntlTest { **/ static double randFraction() { - return (double)randLong() / (double)0xFFFFFFFF; + return static_cast(randLong()) / static_cast(0xFFFFFFFF); } protected: diff --git a/icu4c/source/test/intltest/normconf.cpp b/icu4c/source/test/intltest/normconf.cpp index 8de551480bf5..cdb917c77787 100644 --- a/icu4c/source/test/intltest/normconf.cpp +++ b/icu4c/source/test/intltest/normconf.cpp @@ -60,7 +60,7 @@ static const char *moreCases[]={ void NormalizerConformanceTest::compare(const UnicodeString& s1, const UnicodeString& s2){ UErrorCode status=U_ZERO_ERROR; // TODO: Re-enable this tests after UTC fixes UAX 21 - if(s1.indexOf((UChar32)0x0345)>=0)return; + if (s1.indexOf(static_cast(0x0345)) >= 0) return; if(Normalizer::compare(s1,s2,U_FOLD_CASE_DEFAULT,status)!=0){ errln("Normalizer::compare() failed for s1: " + prettify(s1) + " s2: " +prettify(s2)); } @@ -178,7 +178,7 @@ void NormalizerConformanceTest::TestConformance(FileStream *input, int32_t optio int32_t count, countMoreCases = UPRV_LENGTHOF(moreCases); for (count = 1;;++count) { if (!T_FileStream_eof(input)) { - T_FileStream_readLine(input, lineBuf, (int32_t)sizeof(lineBuf)); + T_FileStream_readLine(input, lineBuf, static_cast(sizeof(lineBuf))); } else { // once NormalizationTest.txt is finished, use moreCases[] if(count > countMoreCases) { @@ -205,7 +205,7 @@ void NormalizerConformanceTest::TestConformance(FileStream *input, int32_t optio // Parse out the fields if (!hexsplit(lineBuf, ';', fields, FIELD_COUNT)) { - errln((UnicodeString)"Unable to parse line " + count); + errln(UnicodeString("Unable to parse line ") + count); break; // Syntax error } @@ -256,7 +256,7 @@ void NormalizerConformanceTest::TestConformance(FileStream *input, int32_t optio } fields[0]=fields[1]=fields[2]=fields[3]=fields[4].setTo(c); - snprintf(lineBuf, sizeof(lineBuf), "not mentioned code point U+%04lx", (long)c); + snprintf(lineBuf, sizeof(lineBuf), "not mentioned code point U+%04lx", static_cast(c)); if (checkConformance(fields, lineBuf, options, status)) { ++passCount; @@ -273,10 +273,10 @@ void NormalizerConformanceTest::TestConformance(FileStream *input, int32_t optio } if (failCount != 0) { - dataerrln((UnicodeString)"Total: " + failCount + " lines/code points failed, " + + dataerrln(UnicodeString("Total: ") + failCount + " lines/code points failed, " + passCount + " lines/code points passed"); } else { - logln((UnicodeString)"Total: " + passCount + " lines/code points passed"); + logln(UnicodeString("Total: ") + passCount + " lines/code points passed"); } } @@ -511,9 +511,9 @@ UBool NormalizerConformanceTest::checkNorm(UNormalizationMode mode, int32_t opti // Do the Edits cover the entire input & output? UBool pass = true; - pass &= assertEquals("edits.hasChanges()", (UBool)(s8 != out8), edits.hasChanges()); + pass &= assertEquals("edits.hasChanges()", static_cast(s8 != out8), edits.hasChanges()); pass &= assertEquals("edits.lengthDelta()", - (int32_t)(out8.length() - s8.length()), edits.lengthDelta()); + static_cast(out8.length() - s8.length()), edits.lengthDelta()); Edits::Iterator iter = edits.getCoarseIterator(); while (iter.next(errorCode)) {} pass &= assertEquals("edits source length", static_cast(s8.length()), iter.sourceIndex()); @@ -610,10 +610,10 @@ UBool NormalizerConformanceTest::hexsplit(const char *s, char delimiter, // read a sequence of code points output[i].remove(); for(;;) { - c = (UChar32)uprv_strtoul(t, &end, 16); + c = static_cast(uprv_strtoul(t, &end, 16)); - if( (char *)t == end || - (uint32_t)c > 0x10ffff || + if (const_cast(t) == end || + static_cast(c) > 0x10ffff || (*end != ' ' && *end != '\t' && *end != delimiter) ) { errln(UnicodeString("Bad field ", "") + (i + 1) + " in " + UnicodeString(s, "")); @@ -657,7 +657,7 @@ void NormalizerConformanceTest::_testOneLine(const char *line) { UErrorCode status = U_ZERO_ERROR; UnicodeString fields[FIELD_COUNT]; if (!hexsplit(line, ';', fields, FIELD_COUNT)) { - errln((UnicodeString)"Unable to parse line " + line); + errln(UnicodeString("Unable to parse line ") + line); } else { checkConformance(fields, line, 0, status); } diff --git a/icu4c/source/test/intltest/nptrans.cpp b/icu4c/source/test/intltest/nptrans.cpp index 0e9e4ceac0cd..aebf18104924 100644 --- a/icu4c/source/test/intltest/nptrans.cpp +++ b/icu4c/source/test/intltest/nptrans.cpp @@ -122,7 +122,7 @@ NamePrepTransform::NamePrepTransform(UParseError& parseError, UErrorCode& status UBool NamePrepTransform::isProhibited(UChar32 ch){ - return (UBool)(ch != ASCII_SPACE); + return static_cast(ch != ASCII_SPACE); } NamePrepTransform::~NamePrepTransform(){ diff --git a/icu4c/source/test/intltest/numberformattesttuple.cpp b/icu4c/source/test/intltest/numberformattesttuple.cpp index 4cacedcb3c8e..ec960741f5f5 100644 --- a/icu4c/source/test/intltest/numberformattesttuple.cpp +++ b/icu4c/source/test/intltest/numberformattesttuple.cpp @@ -156,7 +156,7 @@ static void strToInt( status = U_ILLEGAL_ARGUMENT_ERROR; return; } - value = value * 10 - 0x30 + (int32_t) ch; + value = value * 10 - 0x30 + static_cast(ch); } int32_t signedValue = neg ? static_cast(-value) : static_cast(value); *static_cast(intPtr) = signedValue; @@ -169,7 +169,7 @@ static void intToStr( int64_t xSigned = *static_cast(intPtr); uint32_t x; if (xSigned < 0) { - appendTo.append((char16_t)0x2D); + appendTo.append(static_cast(0x2D)); x = static_cast(-xSigned); } else { x = static_cast(xSigned); @@ -203,7 +203,7 @@ static void strToERounding( const UnicodeString &str, void *roundPtr, UErrorCode &status) { int32_t val = toEnum( gRoundingEnum, UPRV_LENGTHOF(gRoundingEnum), str, status); - *static_cast(roundPtr) = (DecimalFormat::ERoundingMode) val; + *static_cast(roundPtr) = static_cast(val); } static void eRoundingToStr( @@ -221,7 +221,7 @@ static void strToCurrencyUsage( const UnicodeString &str, void *currencyUsagePtr, UErrorCode &status) { int32_t val = toEnum( gCurrencyUsageEnum, UPRV_LENGTHOF(gCurrencyUsageEnum), str, status); - *static_cast(currencyUsagePtr) = (UCurrencyUsage) val; + *static_cast(currencyUsagePtr) = static_cast(val); } static void currencyUsageToStr( @@ -240,7 +240,7 @@ static void strToEPadPosition( int32_t val = toEnum( gPadPositionEnum, UPRV_LENGTHOF(gPadPositionEnum), str, status); *static_cast(padPositionPtr) = - (DecimalFormat::EPadPosition) val; + static_cast(val); } static void ePadPositionToStr( @@ -258,7 +258,7 @@ static void strToFormatStyle( const UnicodeString &str, void *formatStylePtr, UErrorCode &status) { int32_t val = toEnum( gFormatStyleEnum, UPRV_LENGTHOF(gFormatStyleEnum), str, status); - *static_cast(formatStylePtr) = (UNumberFormatStyle) val; + *static_cast(formatStylePtr) = static_cast(val); } static void formatStyleToStr( @@ -426,7 +426,7 @@ NumberFormatTestTuple::getFieldByName( if (result == -1) { return kNumberFormatTestTupleFieldCount; } - return (ENumberFormatTestTupleField) result; + return static_cast(result); } const void * diff --git a/icu4c/source/test/intltest/numbertest_decimalquantity.cpp b/icu4c/source/test/intltest/numbertest_decimalquantity.cpp index 6d389ada8ee8..8eeef7b11365 100644 --- a/icu4c/source/test/intltest/numbertest_decimalquantity.cpp +++ b/icu4c/source/test/intltest/numbertest_decimalquantity.cpp @@ -431,7 +431,7 @@ void DecimalQuantityTest::testMaxDigits() { assertEquals("Should trim, toPlainString", "76.54", dq.toPlainString()); assertEquals("Should trim, toScientificString", "7.654E+1", dq.toScientificString()); assertEquals("Should trim, toLong", 76LL, dq.toLong(true)); - assertEquals("Should trim, toFractionLong", (int64_t) 54, (int64_t) dq.toFractionLong(false)); + assertEquals("Should trim, toFractionLong", static_cast(54), static_cast(dq.toFractionLong(false))); assertEquals("Should trim, toDouble", 76.54, dq.toDouble()); // To test DecNum output, check the round-trip. DecNum dn; diff --git a/icu4c/source/test/intltest/numfmtst.cpp b/icu4c/source/test/intltest/numfmtst.cpp index 109d36e5dd60..6ca31b8db658 100644 --- a/icu4c/source/test/intltest/numfmtst.cpp +++ b/icu4c/source/test/intltest/numfmtst.cpp @@ -315,7 +315,7 @@ class StubNumberFormat :public NumberFormat{ return appendTo; } virtual UnicodeString& format(int32_t ,UnicodeString& appendTo,FieldPosition& ) const override { - return appendTo.append((char16_t)0x0033); + return appendTo.append(static_cast(0x0033)); } virtual UnicodeString& format(int64_t number,UnicodeString& appendTo,FieldPosition& pos) const override { return NumberFormat::format(number, appendTo, pos); @@ -415,18 +415,18 @@ NumberFormatTest::TestPatterns() { status = U_ZERO_ERROR; DecimalFormat fmt(pat[i], sym, status); - if (U_FAILURE(status)) { errln((UnicodeString)"FAIL: DecimalFormat constructor failed for " + pat[i]); continue; } + if (U_FAILURE(status)) { errln(UnicodeString("FAIL: DecimalFormat constructor failed for ") + pat[i]); continue; } UnicodeString newp; fmt.toPattern(newp); if (!(newp == newpat[i])) - errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + + errln(UnicodeString("FAIL: Pattern ") + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); - UnicodeString s; (*dynamic_cast(&fmt)).format((int32_t)0, s); + UnicodeString s; dynamic_cast(&fmt)->format(static_cast(0), s); if (!(s == num[i])) { - errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + + errln(UnicodeString("FAIL: Pattern ") + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); - logln((UnicodeString)"Min integer digits = " + fmt.getMinimumIntegerDigits()); + logln(UnicodeString("Min integer digits = ") + fmt.getMinimumIntegerDigits()); } } } @@ -571,15 +571,15 @@ NumberFormatTest::TestExponential() DecimalFormat fmt(pat[p], sym, status); if (U_FAILURE(status)) { errln("FAIL: Bad status returned by DecimalFormat ct"); continue; } UnicodeString pattern; - logln((UnicodeString)"Pattern \"" + pat[p] + "\" -toPattern-> \"" + + logln(UnicodeString("Pattern \"") + pat[p] + "\" -toPattern-> \"" + fmt.toPattern(pattern) + "\""); int32_t v; for (v=0; v(&fmt)).format(val[v], s); - logln((UnicodeString)" " + val[v] + " -format-> " + s); + logln(UnicodeString(" ") + val[v] + " -format-> " + s); if (s != valFormat[v+ival]) - errln((UnicodeString)"FAIL: Expected " + valFormat[v+ival]); + errln(UnicodeString("FAIL: Expected ") + valFormat[v + ival]); ParsePosition pos(0); Formattable af; @@ -607,28 +607,28 @@ NumberFormatTest::TestExponential() } if (pos.getIndex() == s.length()) { - logln((UnicodeString)" -parse-> " + a); + logln(UnicodeString(" -parse-> ") + a); // Use epsilon comparison as necessary if ((useEpsilon && (uprv_fabs(a - valParse[v+ival]) / a > (2*DBL_EPSILON))) || (!useEpsilon && a != valParse[v+ival])) { - errln((UnicodeString)"FAIL: Expected " + valParse[v+ival] + " but got " + a + errln(UnicodeString("FAIL: Expected ") + valParse[v + ival] + " but got " + a + " on input " + s); } } else { - errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); - errln((UnicodeString)" should be (" + s.length() + " chars) -> " + valParse[v+ival]); + errln(UnicodeString("FAIL: Partial parse (") + pos.getIndex() + " chars) -> " + a); + errln(UnicodeString(" should be (") + s.length() + " chars) -> " + valParse[v + ival]); } } for (v=0; v(&fmt)).format(lval[v], s); - logln((UnicodeString)" " + lval[v] + "L -format-> " + s); + logln(UnicodeString(" ") + lval[v] + "L -format-> " + s); if (s != lvalFormat[v+ilval]) - errln((UnicodeString)"ERROR: Expected " + lvalFormat[v+ilval] + " Got: " + s); + errln(UnicodeString("ERROR: Expected ") + lvalFormat[v + ilval] + " Got: " + s); ParsePosition pos(0); Formattable af; @@ -639,15 +639,15 @@ NumberFormatTest::TestExponential() int32_t a = af.getLong(status); if (pos.getIndex() == s.length()) { - logln((UnicodeString)" -parse-> " + a); + logln(UnicodeString(" -parse-> ") + a); if (a != lvalParse[v+ilval]) - errln((UnicodeString)"FAIL: Expected " + lvalParse[v+ilval] + " but got " + a); + errln(UnicodeString("FAIL: Expected ") + lvalParse[v + ilval] + " but got " + a); } else - errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); + errln(UnicodeString("FAIL: Partial parse (") + pos.getIndex() + " chars) -> " + a); } else - errln((UnicodeString)"FAIL: Non-long Formattable returned for " + s + errln(UnicodeString("FAIL: Non-long Formattable returned for ") + s + " Double: " + af.getDouble() + ", Long: " + af.getLong()); } @@ -718,13 +718,13 @@ NumberFormatTest::TestInt64() { } fmt.setMaximumFractionDigits(20); if (U_SUCCESS(status)) { - expect(fmt, (Formattable)(int64_t)0, "0E0"); - expect(fmt, (Formattable)(int64_t)-1, "-1E0"); - expect(fmt, (Formattable)(int64_t)1, "1E0"); - expect(fmt, (Formattable)(int64_t)2147483647, "2.147483647E9"); - expect(fmt, (Formattable)((int64_t)-2147483647-1), "-2.147483648E9"); - expect(fmt, (Formattable)(int64_t)U_INT64_MAX, "9.223372036854775807E18"); - expect(fmt, (Formattable)(int64_t)U_INT64_MIN, "-9.223372036854775808E18"); + expect(fmt, Formattable(static_cast(0)), "0E0"); + expect(fmt, Formattable(static_cast(-1)), "-1E0"); + expect(fmt, Formattable(static_cast(1)), "1E0"); + expect(fmt, Formattable(static_cast(2147483647)), "2.147483647E9"); + expect(fmt, Formattable(static_cast(-2147483647) - 1), "-2.147483648E9"); + expect(fmt, Formattable(U_INT64_MAX), "9.223372036854775807E18"); + expect(fmt, Formattable(U_INT64_MIN), "-9.223372036854775808E18"); } // also test digitlist @@ -809,11 +809,11 @@ NumberFormatTest::TestQuotes() pat = new UnicodeString("a'fo''o'b#"); DecimalFormat *fmt = new DecimalFormat(*pat, *sym, status); UnicodeString s; - (dynamic_cast(fmt))->format((int32_t)123, s); - logln((UnicodeString)"Pattern \"" + *pat + "\""); - logln((UnicodeString)" Format 123 -> " + escape(s)); + dynamic_cast(fmt)->format(static_cast(123), s); + logln(UnicodeString("Pattern \"") + *pat + "\""); + logln(UnicodeString(" Format 123 -> ") + escape(s)); if (!(s=="afo'ob123")) - errln((UnicodeString)"FAIL: Expected afo'ob123"); + errln(UnicodeString("FAIL: Expected afo'ob123")); s.truncate(0); delete fmt; @@ -821,11 +821,11 @@ NumberFormatTest::TestQuotes() pat = new UnicodeString("a''b#"); fmt = new DecimalFormat(*pat, *sym, status); - (dynamic_cast(fmt))->format((int32_t)123, s); - logln((UnicodeString)"Pattern \"" + *pat + "\""); - logln((UnicodeString)" Format 123 -> " + escape(s)); + dynamic_cast(fmt)->format(static_cast(123), s); + logln(UnicodeString("Pattern \"") + *pat + "\""); + logln(UnicodeString(" Format 123 -> ") + escape(s)); if (!(s=="a'b123")) - errln((UnicodeString)"FAIL: Expected a'b123"); + errln(UnicodeString("FAIL: Expected a'b123")); delete fmt; delete pat; delete sym; @@ -852,13 +852,13 @@ NumberFormatTest::TestCurrencySign() DecimalFormat *fmt = new DecimalFormat(pat, *sym, status); UnicodeString s; (dynamic_cast(fmt))->format(1234.56, s); pat.truncate(0); - logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); - logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); - if (s != "$1,234.56") dataerrln((UnicodeString)"FAIL: Expected $1,234.56"); + logln(UnicodeString("Pattern \"") + fmt->toPattern(pat) + "\""); + logln(UnicodeString(" Format ") + 1234.56 + " -> " + escape(s)); + if (s != "$1,234.56") dataerrln(UnicodeString("FAIL: Expected $1,234.56")); s.truncate(0); (dynamic_cast(fmt))->format(- 1234.56, s); - logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); - if (s != "-$1,234.56") dataerrln((UnicodeString)"FAIL: Expected -$1,234.56"); + logln(UnicodeString(" Format ") + (-1234.56) + " -> " + escape(s)); + if (s != "-$1,234.56") dataerrln(UnicodeString("FAIL: Expected -$1,234.56")); delete fmt; pat.truncate(0); // "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00" @@ -869,21 +869,21 @@ NumberFormatTest::TestCurrencySign() fmt = new DecimalFormat(pat, *sym, status); s.truncate(0); (dynamic_cast(fmt))->format(1234.56, s); - logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); - logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); - if (s != "USD 1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD 1,234.56"); + logln(UnicodeString("Pattern \"") + fmt->toPattern(pat) + "\""); + logln(UnicodeString(" Format ") + 1234.56 + " -> " + escape(s)); + if (s != "USD 1,234.56") dataerrln(UnicodeString("FAIL: Expected USD 1,234.56")); s.truncate(0); (dynamic_cast(fmt))->format(-1234.56, s); - logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); - if (s != "USD -1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD -1,234.56"); + logln(UnicodeString(" Format ") + (-1234.56) + " -> " + escape(s)); + if (s != "USD -1,234.56") dataerrln(UnicodeString("FAIL: Expected USD -1,234.56")); delete fmt; delete sym; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + u_errorName(status)); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: Status ") + u_errorName(status)); } // ------------------------------------- -static char16_t toHexString(int32_t i) { return (char16_t)(i + (i < 10 ? 0x30 : (0x41 - 10))); } +static char16_t toHexString(int32_t i) { return static_cast(i + (i < 10 ? 0x30 : (0x41 - 10))); } UnicodeString& NumberFormatTest::escape(UnicodeString& s) @@ -891,10 +891,10 @@ NumberFormatTest::escape(UnicodeString& s) UnicodeString buf; for (int32_t i=0; i(0x7F)) buf += c; else { - buf += (char16_t)0x5c; buf += (char16_t)0x55; + buf += static_cast(0x5c); buf += static_cast(0x55); buf += toHexString((c & 0xF000) >> 12); buf += toHexString((c & 0x0F00) >> 8); buf += toHexString((c & 0x00F0) >> 4); @@ -935,9 +935,9 @@ NumberFormatTest::TestCurrency() } UnicodeString s; currencyFmt->format(1.50, s); - logln((UnicodeString)"Un pauvre ici a..........." + s); + logln(UnicodeString("Un pauvre ici a...........") + s); if (!(s==CharsToUnicodeString("1,50\\u00A0$"))) - errln((UnicodeString)"FAIL: Expected 1,50$ but got " + s); + errln(UnicodeString("FAIL: Expected 1,50$ but got ") + s); delete currencyFmt; s.truncate(0); char loc[256]={0}; @@ -945,20 +945,20 @@ NumberFormatTest::TestCurrency() (void)len; // Suppress unused variable warning. currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc),status); currencyFmt->format(1.50, s); - logln((UnicodeString)"Un pauvre en Allemagne a.." + s); + logln(UnicodeString("Un pauvre en Allemagne a..") + s); if (!(s==CharsToUnicodeString("1,50\\u00A0DM"))) - errln((UnicodeString)"FAIL: Expected 1,50DM but got " + s); + errln(UnicodeString("FAIL: Expected 1,50DM but got ") + s); delete currencyFmt; s.truncate(0); len = uloc_canonicalize("fr_FR@currency=FRF", loc, 256, &status); currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc), status); currencyFmt->format(1.50, s); - logln((UnicodeString)"Un pauvre en France a....." + s); + logln(UnicodeString("Un pauvre en France a.....") + s); if (!(s==CharsToUnicodeString("1,50\\u00A0F"))) - errln((UnicodeString)"FAIL: Expected 1,50F"); + errln(UnicodeString("FAIL: Expected 1,50F")); delete currencyFmt; if (U_FAILURE(status)) - errln((UnicodeString)"FAIL: Status " + (int32_t)status); + errln(UnicodeString("FAIL: Status ") + static_cast(status)); for(int i=0; i < UPRV_LENGTHOF(testCases); i++){ status = U_ZERO_ERROR; @@ -980,7 +980,7 @@ NumberFormatTest::TestCurrency() + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ - errln((UnicodeString)"FAIL: Status " + (int32_t)status); + errln(UnicodeString("FAIL: Status ") + static_cast(status)); } delete currencyFmt; } @@ -1057,11 +1057,11 @@ NumberFormatTest::TestParse() DecimalFormat* format = new DecimalFormat("00", status); //try { Formattable n; format->parse(arg, n, status); - logln((UnicodeString)"parse(" + arg + ") = " + n.getLong()); + logln(UnicodeString("parse(") + arg + ") = " + n.getLong()); if (n.getType() != Formattable::kLong || - n.getLong() != 0) errln((UnicodeString)"FAIL: Expected 0"); + n.getLong() != 0) errln(UnicodeString("FAIL: Expected 0")); delete format; - if (U_FAILURE(status)) errcheckln(status, (UnicodeString)"FAIL: Status " + u_errorName(status)); + if (U_FAILURE(status)) errcheckln(status, UnicodeString("FAIL: Status ") + u_errorName(status)); //} //catch(Exception e) { // errln((UnicodeString)"Exception caught: " + e); @@ -1152,12 +1152,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientAffixTestCases[t]); format->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != 1) { - dataerrln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientAffixTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + dataerrln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientAffixTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1177,11 +1177,11 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientMinusTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1198,11 +1198,11 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientMinusTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1219,12 +1219,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientCurrencyTestCases[t]); cFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientCurrencyTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientCurrencyTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1233,12 +1233,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientNegativeCurrencyTestCases[t]); cFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != -1000) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativeCurrencyTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientNegativeCurrencyTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1256,12 +1256,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientPercentTestCases[t]); pFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != 0.25) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientPercentTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status) + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientPercentTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } @@ -1271,12 +1271,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(lenientNegativePercentTestCases[t]); pFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != -0.25) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativePercentTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status) + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(lenientNegativePercentTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } @@ -1297,11 +1297,11 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (! U_FAILURE(status)) { - errln((UnicodeString)"Strict Parse succeeded for \"" + (UnicodeString) strictFailureTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Strict Parse succeeded for \"") + UnicodeString(strictFailureTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); } status = U_ZERO_ERROR; @@ -1313,12 +1313,12 @@ NumberFormatTest::TestLenientParse() UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); - logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); + logln(UnicodeString("parse(") + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { - errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) strictFailureTestCases[t] - + (UnicodeString) "\"; error code = " + u_errorName(status)); + errln(UnicodeString("Lenient parse failed for \"") + UnicodeString(strictFailureTestCases[t]) + + UnicodeString("\"; error code = ") + u_errorName(status)); status = U_ZERO_ERROR; } } @@ -1350,7 +1350,7 @@ NumberFormatTest::TestRounding487() roundingTest(*nf, 12.4999, 0, "12"); roundingTest(*nf, - 19.5, 0, "-20"); delete nf; - if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + (int32_t)status); + if (U_FAILURE(status)) errln(UnicodeString("FAIL: Status ") + static_cast(status)); } /** @@ -1364,19 +1364,19 @@ void NumberFormatTest::TestSecondaryGrouping() { DecimalFormat f("#,##,###", US, status); CHECK(status, "DecimalFormat ct"); - expect2(f, (int32_t)123456789L, "12,34,56,789"); + expect2(f, static_cast(123456789L), "12,34,56,789"); expectPat(f, "#,##,##0"); f.applyPattern("#,###", status); CHECK(status, "applyPattern"); f.setSecondaryGroupingSize(4); - expect2(f, (int32_t)123456789L, "12,3456,789"); + expect2(f, static_cast(123456789L), "12,3456,789"); expectPat(f, "#,####,##0"); NumberFormat *g = NumberFormat::createInstance(Locale("hi", "IN"), status); CHECK_DATA(status, "createInstance(hi_IN)"); UnicodeString out; - int32_t l = (int32_t)1876543210L; + int32_t l = static_cast(1876543210L); g->format(l, out); delete g; // expect "1,87,65,43,210", but with Hindi digits @@ -1405,11 +1405,11 @@ void NumberFormatTest::TestSecondaryGrouping() { } } if (!ok) { - errln((UnicodeString)"FAIL Expected " + l + + errln(UnicodeString("FAIL Expected ") + l + " x hi_IN -> \"1,87,65,43,210\" (with Hindi digits), got \"" + escape(out) + "\""); } else { - logln((UnicodeString)"Ok " + l + + logln(UnicodeString("Ok ") + l + " x hi_IN -> \"" + escape(out) + "\""); } @@ -1460,8 +1460,8 @@ NumberFormatTest::roundingTest(NumberFormat& nf, double x, int32_t maxFractionDi { nf.setMaximumFractionDigits(maxFractionDigits); UnicodeString out; nf.format(x, out); - logln((UnicodeString)"" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); - if (!(out==expected)) errln((UnicodeString)"FAIL: Expected " + expected); + logln(UnicodeString("") + x + " formats with " + maxFractionDigits + " fractional digits to " + out); + if (!(out == expected)) errln(UnicodeString("FAIL: Expected ") + expected); } /** @@ -1562,7 +1562,7 @@ void NumberFormatTest::TestScientific() { 12345.00001, "12.35E3", status); expect2(new DecimalFormat("##0.####E0", US, status), - (int32_t) 12345, + static_cast(12345), "12.345E3", status); expect2(NumberFormat::createScientificInstance(Locale::getFrance(), status), 12345.678901, @@ -1577,7 +1577,7 @@ void NumberFormatTest::TestScientific() { 45678.0, ".457E5", status); expect2(new DecimalFormat(".###E0", US, status), - (int32_t) 0, + static_cast(0), ".0E0", status); /* expect(new DecimalFormat[] { new DecimalFormat("#E0", US), @@ -1601,17 +1601,17 @@ void NumberFormatTest::TestScientific() { ! */ expect2(new DecimalFormat("#E0", US, status), - (int32_t) 45678000, "4.5678E7", status); + static_cast(45678000), "4.5678E7", status); expect2(new DecimalFormat("##E0", US, status), - (int32_t) 45678000, "45.678E6", status); + static_cast(45678000), "45.678E6", status); expect2(new DecimalFormat("####E0", US, status), - (int32_t) 45678000, "4567.8E4", status); + static_cast(45678000), "4567.8E4", status); expect(new DecimalFormat("0E0", US, status), - (int32_t) 45678000, "5E7", status); + static_cast(45678000), "5E7", status); expect(new DecimalFormat("00E0", US, status), - (int32_t) 45678000, "46E6", status); + static_cast(45678000), "46E6", status); expect(new DecimalFormat("000E0", US, status), - (int32_t) 45678000, "457E5", status); + static_cast(45678000), "457E5", status); /* expect(new DecimalFormat("###E0", US, status), new Object[] { new Double(0.0000123), "12.3E-6", @@ -1658,7 +1658,7 @@ void NumberFormatTest::TestScientific() { expect2(new DecimalFormat("0.#E+00", US, status), 0.00012, "1.2E-04", status); expect2(new DecimalFormat("0.#E+00", US, status), - (int32_t) 12000, "1.2E+04", status); + static_cast(12000), "1.2E+04", status); } /** @@ -1670,26 +1670,26 @@ void NumberFormatTest::TestPad() { CHECK(status, "DecimalFormatSymbols constructor"); expect2(new DecimalFormat("*^##.##", US, status), - int32_t(0), "^^^^0", status); + static_cast(0), "^^^^0", status); expect2(new DecimalFormat("*^##.##", US, status), -1.3, "^-1.3", status); expect2(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), - int32_t(0), "0.0E0______ g-m/s^2", status); + static_cast(0), "0.0E0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), 1.0/3, "333.333E-3_ g-m/s^2", status); expect2(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), - int32_t(0), "0.0______ g-m/s^2", status); + static_cast(0), "0.0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), 1.0/3, "0.33333__ g-m/s^2", status); // Test padding before a sign const char *formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)"; expect2(new DecimalFormat(formatStr, US, status), - int32_t(-10), "xxxxxxxxxx(10.0)", status); + static_cast(-10), "xxxxxxxxxx(10.0)", status); expect2(new DecimalFormat(formatStr, US, status), - int32_t(-1000),"xxxxxxx(1,000.0)", status); + static_cast(-1000), "xxxxxxx(1,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), - int32_t(-1000000),"xxx(1,000,000.0)", status); + static_cast(-1000000), "xxx(1,000,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), -100.37, "xxxxxxxx(100.37)", status); expect2(new DecimalFormat(formatStr, US, status), @@ -1702,11 +1702,11 @@ void NumberFormatTest::TestPad() { -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr, US, status), - int32_t(10), "xxxxxxxxxxxx10.0", status); + static_cast(10), "xxxxxxxxxxxx10.0", status); expect2(new DecimalFormat(formatStr, US, status), - int32_t(1000),"xxxxxxxxx1,000.0", status); + static_cast(1000), "xxxxxxxxx1,000.0", status); expect2(new DecimalFormat(formatStr, US, status), - int32_t(1000000),"xxxxx1,000,000.0", status); + static_cast(1000000), "xxxxx1,000,000.0", status); expect2(new DecimalFormat(formatStr, US, status), 100.37, "xxxxxxxxxx100.37", status); expect2(new DecimalFormat(formatStr, US, status), @@ -1722,11 +1722,11 @@ void NumberFormatTest::TestPad() { // Test padding between a sign and a number const char *formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)"; expect2(new DecimalFormat(formatStr2, US, status), - int32_t(-10), "(10.0xxxxxxxxxx)", status); + static_cast(-10), "(10.0xxxxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), - int32_t(-1000),"(1,000.0xxxxxxx)", status); + static_cast(-1000), "(1,000.0xxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), - int32_t(-1000000),"(1,000,000.0xxx)", status); + static_cast(-1000000), "(1,000,000.0xxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -100.37, "(100.37xxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), @@ -1739,11 +1739,11 @@ void NumberFormatTest::TestPad() { -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr2, US, status), - int32_t(10), "10.0xxxxxxxxxxxx", status); + static_cast(10), "10.0xxxxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), - int32_t(1000),"1,000.0xxxxxxxxx", status); + static_cast(1000), "1,000.0xxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), - int32_t(1000000),"1,000,000.0xxxxx", status); + static_cast(1000000), "1,000,000.0xxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 100.37, "100.37xxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), @@ -1761,8 +1761,8 @@ void NumberFormatTest::TestPad() { UnicodeString padString("P"); fmt.setPadCharacter(padString); expectPad(fmt, "*P##.##", DecimalFormat::kPadBeforePrefix, 5, padString); - fmt.setPadCharacter((UnicodeString)"^"); - expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, (UnicodeString)"^"); + fmt.setPadCharacter(UnicodeString("^")); + expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, UnicodeString("^")); //commented until implementation is complete /* fmt.setPadCharacter((UnicodeString)"^^^"); expectPad(fmt, "*^^^#", DecimalFormat::kPadBeforePrefix, 3, (UnicodeString)"^^^"); @@ -1797,11 +1797,11 @@ void NumberFormatTest::TestPatterns2() { expectPad(fmt, "$*^$#", ILLEGAL); expectPad(fmt, "#$*^$", ILLEGAL); expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat::kPadBeforeSuffix, - 12, (char16_t)0x0078 /*x*/); + 12, static_cast(0x0078) /*x*/); expectPad(fmt, "''#0*x", DecimalFormat::kPadBeforeSuffix, - 3, (char16_t)0x0078 /*x*/); + 3, static_cast(0x0078) /*x*/); expectPad(fmt, "'I''ll'*a###.##", DecimalFormat::kPadAfterPrefix, - 10, (char16_t)0x0061 /*a*/); + 10, static_cast(0x0061) /*a*/); fmt.applyPattern("AA#,##0.00ZZ", status); CHECK(status, "applyPattern"); @@ -1856,31 +1856,31 @@ void NumberFormatTest::TestSurrogateSupport() { UnicodeString expStr("\\U00010000\\U00010000\\U00010000\\U000100000", ""); expStr = expStr.unescape(); expect2(new DecimalFormat(patternStr, custom, status), - int32_t(0), expStr, status); + static_cast(0), expStr, status); status = U_ZERO_ERROR; expect2(new DecimalFormat("*^##.##", custom, status), - int32_t(0), "^^^^0", status); + static_cast(0), "^^^^0", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##.##", custom, status), -1.3, " minus 1decimal3", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), - int32_t(0), "0decimal0exponent0 g-m/s^2", status); + static_cast(0), "0decimal0exponent0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), 1.0/3, "333decimal333exponent minus 3 g-m/s^2", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), - int32_t(0), "0decimal0 g-m/s^2", status); + static_cast(0), "0decimal0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), 1.0/3, "0decimal33333 g-m/s^2", status); - UnicodeString zero((UChar32)0x10000); - UnicodeString one((UChar32)0x10001); - UnicodeString two((UChar32)0x10002); - UnicodeString five((UChar32)0x10005); + UnicodeString zero(static_cast(0x10000)); + UnicodeString one(static_cast(0x10001)); + UnicodeString two(static_cast(0x10002)); + UnicodeString five(static_cast(0x10005)); custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, zero); custom.setSymbol(DecimalFormatSymbols::kOneDigitSymbol, one); custom.setSymbol(DecimalFormatSymbols::kTwoDigitSymbol, two); @@ -1891,7 +1891,7 @@ void NumberFormatTest::TestSurrogateSupport() { expect2(new DecimalFormat("##0.000", custom, status), 1.25, expStr, status); - custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, (char16_t)0x30); + custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, static_cast(0x30)); custom.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "units of money"); custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, "money separator"); patternStr = UNICODE_STRING_SIMPLE("0.00 \\u00A4' in your bank account'"); @@ -1899,7 +1899,7 @@ void NumberFormatTest::TestSurrogateSupport() { expStr = UnicodeString(" minus 20money separator00 units of money in your bank account", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), - int32_t(-20), expStr, status); + static_cast(-20), expStr, status); custom.setSymbol(DecimalFormatSymbols::kPercentSymbol, "percent"); patternStr = "'You''ve lost ' -0.00 %' of your money today'"; @@ -1907,7 +1907,7 @@ void NumberFormatTest::TestSurrogateSupport() { expStr = UnicodeString(" minus You've lost minus 2000decimal00 percent of your money today", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), - int32_t(-20), expStr, status); + static_cast(-20), expStr, status); } void NumberFormatTest::TestCurrencyPatterns() { @@ -1927,7 +1927,7 @@ void NumberFormatTest::TestCurrencyPatterns() { UnicodeString a, b; nf->format(1.0, a); nf->format(1.125, b); - errln((UnicodeString)"FAIL: " + locs[i].getName() + + errln(UnicodeString("FAIL: ") + locs[i].getName() + " min fraction digits != max fraction digits; " "x 1.0 => " + escape(a) + "; x 1.125 => " + escape(b)); @@ -1940,7 +1940,7 @@ void NumberFormatTest::TestCurrencyPatterns() { if (min != 2 || max != 2) { UnicodeString a; nf->format(1.0, a); - errln((UnicodeString)"FAIL: " + locs[i].getName() + + errln(UnicodeString("FAIL: ") + locs[i].getName() + " is a EURO format but it does not have 2 fraction digits; " "x 1.0 => " + escape(a)); @@ -2207,11 +2207,11 @@ void NumberFormatTest::TestCurrencyUnit(){ static const char16_t jpy[] = u"jpy"; static const char jpy8[] = "jpy"; - char16_t* EUR = (char16_t*) malloc(6); + char16_t* EUR = static_cast(malloc(6)); EUR[0] = u'E'; EUR[1] = u'U'; EUR[2] = u'R'; - char* EUR8 = (char*) malloc(3); + char* EUR8 = static_cast(malloc(3)); EUR8[0] = 'E'; EUR8[1] = 'U'; EUR8[2] = 'R'; @@ -2387,9 +2387,9 @@ void NumberFormatTest::TestSymbolsWithBadLocale() { Locale locBad(localeName); assertTrue(WHERE, !locBad.isBogus()); UErrorCode status = U_ZERO_ERROR; - UnicodeString intlCurrencySymbol((char16_t)0xa4); + UnicodeString intlCurrencySymbol(static_cast(0xa4)); - intlCurrencySymbol.append((char16_t)0xa4); + intlCurrencySymbol.append(static_cast(0xa4)); logln("Current locale is %s", Locale::getDefault().getName()); Locale::setDefault(locBad, status); @@ -2401,13 +2401,13 @@ void NumberFormatTest::TestSymbolsWithBadLocale() { if (strcmp(mySymbols.getLocale().getName(), locBad.getName()) != 0) { errln("DecimalFormatSymbols does not have the right locale.", locBad.getName()); } - int symbolEnum = (int)DecimalFormatSymbols::kDecimalSeparatorSymbol; - for (; symbolEnum < (int)DecimalFormatSymbols::kFormatSymbolCount; symbolEnum++) { - UnicodeString symbolString = mySymbols.getSymbol((DecimalFormatSymbols::ENumberFormatSymbol)symbolEnum); + int symbolEnum = static_cast(DecimalFormatSymbols::kDecimalSeparatorSymbol); + for (; symbolEnum < static_cast(DecimalFormatSymbols::kFormatSymbolCount); symbolEnum++) { + UnicodeString symbolString = mySymbols.getSymbol(static_cast(symbolEnum)); logln(UnicodeString("DecimalFormatSymbols[") + symbolEnum + UnicodeString("] = ") + prettify(symbolString)); if (symbolString.length() == 0 - && symbolEnum != (int)DecimalFormatSymbols::kGroupingSeparatorSymbol - && symbolEnum != (int)DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol) + && symbolEnum != static_cast(DecimalFormatSymbols::kGroupingSeparatorSymbol) + && symbolEnum != static_cast(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol)) { errln("DecimalFormatSymbols has an empty string at index %d.", symbolEnum); } @@ -2433,7 +2433,7 @@ void NumberFormatTest::TestAdoptDecimalFormatSymbols() { return; } UnicodeString pat(" #,##0.00"); - pat.insert(0, (char16_t)0x00A4); + pat.insert(0, static_cast(0x00A4)); DecimalFormat fmt(pat, sym, ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormat constructor"); @@ -2720,14 +2720,14 @@ void NumberFormatTest::TestCases() { // fpc: if (!tokens.next(currAmt, ec)) goto error; if (!tokens.next(str, ec)) goto error; - parseCurrencyAmount(currAmt, *ref, (char16_t)0x2F/*'/'*/, n, ec); + parseCurrencyAmount(currAmt, *ref, static_cast(0x2F)/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, mfmt->format(n, out.remove(), ec)); assertSuccess("format", ec); } if (!tokens.next(currAmt, ec)) goto error; - parseCurrencyAmount(currAmt, *ref, (char16_t)0x2F/*'/'*/, n, ec); + parseCurrencyAmount(currAmt, *ref, static_cast(0x2F)/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { Formattable m; @@ -2822,19 +2822,19 @@ UBool NumberFormatTest::equalValue(const Formattable& a, const Formattable& b) { if (b.getType() == Formattable::kInt64) { return a.getLong() == b.getLong(); } else if (b.getType() == Formattable::kDouble) { - return (double) a.getLong() == b.getDouble(); // TODO check use of double instead of long + return static_cast(a.getLong()) == b.getDouble(); // TODO check use of double instead of long } } else if (a.getType() == Formattable::kDouble) { if (b.getType() == Formattable::kLong) { - return a.getDouble() == (double) b.getLong(); + return a.getDouble() == static_cast(b.getLong()); } else if (b.getType() == Formattable::kInt64) { - return a.getDouble() == (double)b.getInt64(); + return a.getDouble() == static_cast(b.getInt64()); } } else if (a.getType() == Formattable::kInt64) { if (b.getType() == Formattable::kLong) { - return a.getInt64() == (int64_t)b.getLong(); + return a.getInt64() == static_cast(b.getLong()); } else if (b.getType() == Formattable::kDouble) { - return a.getInt64() == (int64_t)b.getDouble(); + return a.getInt64() == static_cast(b.getDouble()); } } return false; @@ -2926,7 +2926,7 @@ void NumberFormatTest::expect_rbnf(NumberFormat& fmt, const Formattable& n, fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { - errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + + errln(UnicodeString("FAIL \"") + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } @@ -2964,7 +2964,7 @@ void NumberFormatTest::expect(NumberFormat& fmt, const Formattable& n, fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { - errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + + errln(UnicodeString("FAIL \"") + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } @@ -3002,7 +3002,7 @@ void NumberFormatTest::expectCurrency(NumberFormat& nf, const Locale& locale, } UnicodeString s; fmt.format(value, s); - s.findAndReplace((UChar32)0x00A0, (UChar32)0x0020); + s.findAndReplace(static_cast(0x00A0), static_cast(0x0020)); // Default display of the number yields "1234.5599999999999" // instead of "1234.56". Use a formatter to fix this. @@ -3011,7 +3011,7 @@ void NumberFormatTest::expectCurrency(NumberFormat& nf, const Locale& locale, UnicodeString v; if (U_FAILURE(ec)) { // Oops; bad formatter. Use default op+= display. - v = (UnicodeString)"" + value; + v = UnicodeString("") + value; } else { f->setMaximumFractionDigits(4); f->setGroupingUsed(false); @@ -3020,9 +3020,9 @@ void NumberFormatTest::expectCurrency(NumberFormat& nf, const Locale& locale, delete f; if (s == string) { - logln((UnicodeString)"Ok: " + v + " x " + curr + " => " + prettify(s)); + logln(UnicodeString("Ok: ") + v + " x " + curr + " => " + prettify(s)); } else { - errln((UnicodeString)"FAIL: " + v + " x " + curr + " => " + prettify(s) + + errln(UnicodeString("FAIL: ") + v + " x " + curr + " => " + prettify(s) + ", expected " + prettify(string)); } } @@ -3039,7 +3039,7 @@ void NumberFormatTest::expectPat(DecimalFormat& fmt, const UnicodeString& exp) { void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos) { - expectPad(fmt, pat, pos, 0, (UnicodeString)""); + expectPad(fmt, pat, pos, 0, UnicodeString("")); } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos, int32_t width, char16_t pad) { @@ -3170,7 +3170,7 @@ void NumberFormatTest::TestHost() #endif Locale loc("en_US@compat=host"); for (UNumberFormatStyle k = UNUM_DECIMAL; - k < UNUM_FORMAT_STYLE_COUNT; k = (UNumberFormatStyle)(k+1)) { + k < UNUM_FORMAT_STYLE_COUNT; k = static_cast(k + 1)) { UErrorCode status = U_ZERO_ERROR; LocalPointer full(NumberFormat::createInstance(loc, k, status)); if (!NumberFormat::isStyleSupported(k)) { @@ -3306,7 +3306,7 @@ void NumberFormatTest::TestRounding() { for (int j=0; j<2; j++) { for (int mode=DecimalFormat::kRoundUp;modesetRoundingMode((DecimalFormat::ERoundingMode)mode); + df->setRoundingMode(static_cast(mode)); for (int increment=0; increment<6; increment++) { double base=testValues[j]; double rInc=roundingIncrements[increment]; @@ -3326,8 +3326,8 @@ void NumberFormatTest::TestRoundingPattern() { double testCase; UnicodeString expected; } tests[] = { - { (UnicodeString)"##0.65", 1.234, (UnicodeString)"1.30" }, - { (UnicodeString)"#50", 1230, (UnicodeString)"1250" } + { UnicodeString("##0.65"), 1.234, UnicodeString("1.30") }, + { UnicodeString("#50"), 1230, UnicodeString("1250") } }; int32_t numOfTests = UPRV_LENGTHOF(tests); UnicodeString result; @@ -3434,8 +3434,8 @@ void NumberFormatTest::TestNonpositiveMultiplier() { // to looking at the decimal parsed value, but it doesn't. expect(df, U_INT64_MIN, "9223372036854775808", false); expect(df, U_INT64_MIN+1, "9223372036854775807"); - expect(df, (int64_t)-123, "123"); - expect(df, (int64_t)123, "-123"); + expect(df, static_cast(-123), "123"); + expect(df, static_cast(123), "-123"); expect(df, U_INT64_MAX-1, "-9223372036854775806"); expect(df, U_INT64_MAX, "-9223372036854775807"); @@ -3733,10 +3733,10 @@ NumberFormatTest::TestCurrencyFormatForMixParsing() { ) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number "); if (curramt->getNumber().getDouble() != 1234.56) { - errln((UnicodeString)"wong number, expect: 1234.56" + ", got: " + curramt->getNumber().getDouble()); + errln(UnicodeString("wong number, expect: 1234.56") + ", got: " + curramt->getNumber().getDouble()); } if (curramt->getISOCurrency() != ISO_CURRENCY_USD) { - errln((UnicodeString)"wong currency, expect: USD" + ", got: " + curramt->getISOCurrency()); + errln(UnicodeString("wong currency, expect: USD") + ", got: " + curramt->getISOCurrency()); } } } @@ -3815,13 +3815,13 @@ NumberFormatTest::TestDecimalFormatCurrencyParse() { UErrorCode status = U_ZERO_ERROR; Formattable result; fmt->parse(stringToBeParsed, result, status); - logln((UnicodeString)"Input: " + stringToBeParsed + "; output: " + result.getDouble(status)); + logln(UnicodeString("Input: ") + stringToBeParsed + "; output: " + result.getDouble(status)); if (U_FAILURE(status) || (result.getType() == Formattable::kDouble && result.getDouble() != parsedResult) || (result.getType() == Formattable::kLong && result.getLong() != parsedResult)) { - errln((UnicodeString)"FAIL parse: Expected " + parsedResult); + errln(UnicodeString("FAIL parse: Expected ") + parsedResult); } } delete fmt; @@ -3873,7 +3873,7 @@ NumberFormatTest::TestCurrencyIsoPluralFormat() { NumberFormat* numFmt = NumberFormat::createInstance(locale, k, status); if (U_FAILURE(status)) { delete numFmt; - dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); + dataerrln(UnicodeString("can not create instance, locale:") + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } char16_t currencyCode[4]; @@ -3881,7 +3881,7 @@ NumberFormatTest::TestCurrencyIsoPluralFormat() { numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; - errln((UnicodeString)"can not set currency:" + currencyISOCode); + errln(UnicodeString("can not set currency:") + currencyISOCode); continue; } @@ -3913,12 +3913,12 @@ NumberFormatTest::TestCurrencyIsoPluralFormat() { parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { - errln((UnicodeString)"FAIL: getCurrencyFormat of locale " + + errln(UnicodeString("FAIL: getCurrencyFormat of locale ") + localeString + " failed roundtripping the number"); if (parseResult.getType() == Formattable::kDouble) { - errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getDouble()); + errln(UnicodeString("expected: ") + numberToBeFormat + "; actual: " + parseResult.getDouble()); } else { - errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getLong()); + errln(UnicodeString("expected: ") + numberToBeFormat + "; actual: " + parseResult.getLong()); } } } @@ -3988,7 +3988,7 @@ for (;;) { if (U_FAILURE(status)) { delete numFmt; - dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); + dataerrln(UnicodeString("can not create instance, locale:") + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } char16_t currencyCode[4]; @@ -3996,7 +3996,7 @@ for (;;) { numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; - errln((UnicodeString)"can not set currency:" + currencyISOCode); + errln(UnicodeString("can not set currency:") + currencyISOCode); continue; } @@ -4029,14 +4029,14 @@ for (;;) { parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { - errln((UnicodeString)"FAIL: NumberFormat(" + localeString +", " + currencyStyleNames[kIndex] + - "), Currency="+currencyISOCode+", parse("+DATA[i][j]+") returned error " + (UnicodeString)u_errorName(status)+". Testcase: data[" + i + "][" + currencyStyleNames[j-3] +"="+j+"]"); + errln(UnicodeString("FAIL: NumberFormat(") + localeString + ", " + currencyStyleNames[kIndex] + + "), Currency=" + currencyISOCode + ", parse(" + DATA[i][j] + ") returned error " + UnicodeString(u_errorName(status)) + ". Testcase: data[" + i + "][" + currencyStyleNames[j - 3] + "=" + j + "]"); if (parseResult.getType() == Formattable::kDouble) { - errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (double): " +parseResult.getDouble()); + errln(UnicodeString("expected: ") + numberToBeFormat + "; actual (double): " + parseResult.getDouble()); } else { - errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (long): " +parseResult.getLong()); + errln(UnicodeString("expected: ") + numberToBeFormat + "; actual (long): " + parseResult.getLong()); } - errln((UnicodeString)" round-trip would be: " + strBuf); + errln(UnicodeString(" round-trip would be: ") + strBuf); } } delete numFmt; @@ -6677,7 +6677,7 @@ void NumberFormatTest::expectPositions(FieldPositionIterator& iter, int32_t *val } } - assertTrue((UnicodeString)"found [" + id + "," + start + "," + limit + "]", ok); + assertTrue(UnicodeString("found [") + id + "," + start + "," + limit + "]", ok); } // check that all were found @@ -6685,7 +6685,7 @@ void NumberFormatTest::expectPositions(FieldPositionIterator& iter, int32_t *val for (int i = 0; i < tupleCount; ++i) { if (!found[i]) { ok = false; - assertTrue((UnicodeString) "missing [" + values[i*3] + "," + values[i*3+1] + "," + values[i*3+2] + "]", found[i]); + assertTrue(UnicodeString("missing [") + values[i * 3] + "," + values[i * 3 + 1] + "," + values[i * 3 + 2] + "]", found[i]); } } assertTrue("no expected values were missing", ok); @@ -6694,9 +6694,9 @@ void NumberFormatTest::expectPositions(FieldPositionIterator& iter, int32_t *val void NumberFormatTest::expectPosition(FieldPosition& pos, int32_t id, int32_t start, int32_t limit, const UnicodeString& str) { logln(str); - assertTrue((UnicodeString)"id " + id + " == " + pos.getField(), id == pos.getField()); - assertTrue((UnicodeString)"begin " + start + " == " + pos.getBeginIndex(), start == pos.getBeginIndex()); - assertTrue((UnicodeString)"end " + limit + " == " + pos.getEndIndex(), limit == pos.getEndIndex()); + assertTrue(UnicodeString("id ") + id + " == " + pos.getField(), id == pos.getField()); + assertTrue(UnicodeString("begin ") + start + " == " + pos.getBeginIndex(), start == pos.getBeginIndex()); + assertTrue(UnicodeString("end ") + limit + " == " + pos.getEndIndex(), limit == pos.getEndIndex()); } void NumberFormatTest::TestFieldPositionIterator() { @@ -6713,17 +6713,17 @@ void NumberFormatTest::TestFieldPositionIterator() { UnicodeString str1; UnicodeString str2; - assertTrue((UnicodeString)"self==", iter1 == iter1); - assertTrue((UnicodeString)"iter1==iter2", iter1 == iter2); + assertTrue(UnicodeString("self=="), iter1 == iter1); + assertTrue(UnicodeString("iter1==iter2"), iter1 == iter2); decFmt->format(num, str1, &iter1, status); - assertTrue((UnicodeString)"iter1 != iter2", iter1 != iter2); + assertTrue(UnicodeString("iter1 != iter2"), iter1 != iter2); decFmt->format(num, str2, &iter2, status); - assertTrue((UnicodeString)"iter1 == iter2 (2)", iter1 == iter2); + assertTrue(UnicodeString("iter1 == iter2 (2)"), iter1 == iter2); iter1.next(pos); - assertTrue((UnicodeString)"iter1 != iter2 (2)", iter1 != iter2); + assertTrue(UnicodeString("iter1 != iter2 (2)"), iter1 != iter2); iter2.next(pos); - assertTrue((UnicodeString)"iter1 == iter2 (3)", iter1 == iter2); + assertTrue(UnicodeString("iter1 == iter2 (3)"), iter1 == iter2); // should format ok with no iterator str2.remove(); @@ -6998,7 +6998,7 @@ void NumberFormatTest::TestCurrencyFractionDigits() { fmt->format(value, text2); if (text1 != text2) { - errln((UnicodeString)"NumberFormat::format() should return the same result - text1=" + errln(UnicodeString("NumberFormat::format() should return the same result - text1=") + text1 + " text2=" + text2); } } @@ -7015,7 +7015,7 @@ void NumberFormatTest::TestExponentParse() { status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getDefault(), status); if(U_FAILURE(status)) { - dataerrln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (Default)"); + dataerrln(UnicodeString("ERROR: Could not create DecimalFormatSymbols (Default)")); return; } @@ -7023,7 +7023,7 @@ void NumberFormatTest::TestExponentParse() { status = U_ZERO_ERROR; DecimalFormat fmt(u"#####", symbols, status); if(U_FAILURE(status)) { - errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); + errln(UnicodeString("ERROR: Could not create DecimalFormat (pattern, symbols*)")); } // parse the text @@ -7074,7 +7074,7 @@ void NumberFormatTest::TestExplicitParents() { + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ - errln((UnicodeString)"FAIL: Status " + (int32_t)status); + errln(UnicodeString("FAIL: Status ") + static_cast(status)); } delete fmt; } @@ -7163,7 +7163,7 @@ NumberFormatTest::Test9087() unum_formatDouble(fmt,inf,outputbuf,50,&position,&status); if ( u_strcmp(infstr, outputbuf)) { - errln((UnicodeString)"FAIL: unexpected result for infinity - expected " + infstr + " got " + outputbuf); + errln(UnicodeString("FAIL: unexpected result for infinity - expected ") + infstr + " got " + outputbuf); } unum_close(fmt); @@ -7391,7 +7391,7 @@ UBool NumberFormatTest::testFormattableAsUFormattable(const char *file, int line } if(uType != expectUType) { - errln("%s:%d: got type (%d) expected (%d) from ufmt_getType", file, line, (int) uType, (int) expectUType); + errln("%s:%d: got type (%d) expected (%d) from ufmt_getType", file, line, static_cast(uType), static_cast(expectUType)); } if(triedExact) { @@ -7458,19 +7458,19 @@ void NumberFormatTest::TestUFormattable() { LocalUFormattablePointer defaultUFormattable(ufmt_open(&status)); assertSuccess("calling umt_open", status); Formattable defaultFormattable; - assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", + assertTrue(UnicodeString("comparing ufmt_open() with Formattable()"), (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); - assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", + assertTrue(UnicodeString("comparing ufmt_open() with Formattable()"), (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); - assertTrue((UnicodeString)"comparing Formattable() round tripped through UFormattable", + assertTrue(UnicodeString("comparing Formattable() round tripped through UFormattable"), (defaultFormattable == *(Formattable::fromUFormattable(defaultFormattable.toUFormattable())))); - assertTrue((UnicodeString)"comparing &Formattable() round tripped through UFormattable", + assertTrue(UnicodeString("comparing &Formattable() round tripped through UFormattable"), ((&defaultFormattable) == Formattable::fromUFormattable(defaultFormattable.toUFormattable()))); - assertFalse((UnicodeString)"comparing &Formattable() with ufmt_open()", + assertFalse(UnicodeString("comparing &Formattable() with ufmt_open()"), ((&defaultFormattable) == Formattable::fromUFormattable(defaultUFormattable.getAlias()))); testFormattableAsUFormattable(__FILE__, __LINE__, defaultFormattable); @@ -7481,15 +7481,15 @@ void NumberFormatTest::TestUFormattable() { testFormattableAsUFormattable(__FILE__, __LINE__, f); } { - Formattable f((double)1.61803398874989484820); // golden ratio + Formattable f(1.61803398874989484820); // golden ratio testFormattableAsUFormattable(__FILE__, __LINE__, f); } { - Formattable f((int64_t)80994231587905127LL); // weight of the moon, in kilotons http://solarsystem.nasa.gov/planets/profile.cfm?Display=Facts&Object=Moon + Formattable f(static_cast(80994231587905127LL)); // weight of the moon, in kilotons http://solarsystem.nasa.gov/planets/profile.cfm?Display=Facts&Object=Moon testFormattableAsUFormattable(__FILE__, __LINE__, f); } { - Formattable f((int32_t)4); // random number, source: http://www.xkcd.com/221/ + Formattable f(static_cast(4)); // random number, source: http://www.xkcd.com/221/ testFormattableAsUFormattable(__FILE__, __LINE__, f); } { @@ -7512,8 +7512,8 @@ void NumberFormatTest::TestUFormattable() { { const Formattable array[] = { Formattable(ucal_getNow(), Formattable::kIsDate), - Formattable((int32_t)4), - Formattable((double)1.234), + Formattable(static_cast(4)), + Formattable(1.234), }; Formattable fa(array, 3); @@ -7570,7 +7570,7 @@ void NumberFormatTest::TestSignificantDigits() { numberFormat->format(input[i], result); UnicodeString expectedResult(expected[i]); if (result != expectedResult) { - errln((UnicodeString)"Expected: '" + expectedResult + "' got '" + result); + errln(UnicodeString("Expected: '") + expectedResult + "' got '" + result); } result.remove(); } @@ -7618,7 +7618,7 @@ void NumberFormatTest::TestShowZero() { UnicodeString result; numberFormat->format(0.0, result); if (result != "0") { - errln((UnicodeString)"Expected: 0, got " + result); + errln(UnicodeString("Expected: 0, got ") + result); } } @@ -7700,13 +7700,13 @@ void NumberFormatTest::TestCustomCurrencySignAndSeparator() { custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, ":"); UnicodeString pat(" #,##0.00"); - pat.insert(0, (char16_t)0x00A4); + pat.insert(0, static_cast(0x00A4)); DecimalFormat fmt(pat, custom, status); CHECK(status, "DecimalFormat constructor"); UnicodeString numstr("* 1^234:56"); - expect2(fmt, (Formattable)((double)1234.56), numstr); + expect2(fmt, Formattable(1234.56), numstr); } typedef struct { @@ -7810,10 +7810,10 @@ void NumberFormatTest::TestParseSignsAndMarks() { if (ppos.getIndex() == itemPtr->numString.length()) { double parsedValue = fmtobj.getDouble(status); if (U_FAILURE(status) || parsedValue != itemPtr->value) { - errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives value " + parsedValue); + errln(UnicodeString("FAIL: locale ") + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives value " + parsedValue); } } else { - errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives position " + ppos.getIndex()); + errln(UnicodeString("FAIL: locale ") + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives position " + ppos.getIndex()); } } else { dataerrln("FAIL: NumberFormat::createInstance for locale % gives error %s", itemPtr->locale, u_errorName(status)); @@ -8085,27 +8085,27 @@ void NumberFormatTest::TestAccountingCurrency() { UNumberFormatStyle style = UNUM_CURRENCY_ACCOUNTING; expect(NumberFormat::createInstance("en_US", style, status), - (Formattable)(double)1234.5, "$1,234.50", true, status); + Formattable(1234.5), "$1,234.50", true, status); expect(NumberFormat::createInstance("en_US", style, status), - (Formattable)(double)-1234.5, "($1,234.50)", true, status); + Formattable(-1234.5), "($1,234.50)", true, status); expect(NumberFormat::createInstance("en_US", style, status), - (Formattable)(double)0, "$0.00", true, status); + Formattable(static_cast(0)), "$0.00", true, status); expect(NumberFormat::createInstance("en_US", style, status), - (Formattable)(double)-0.2, "($0.20)", true, status); + Formattable(-0.2), "($0.20)", true, status); expect(NumberFormat::createInstance("ja_JP", style, status), - (Formattable)(double)10000, UnicodeString("\\uFFE510,000").unescape(), true, status); + Formattable(static_cast(10000)), UnicodeString("\\uFFE510,000").unescape(), true, status); expect(NumberFormat::createInstance("ja_JP", style, status), - (Formattable)(double)-1000.5, UnicodeString("(\\uFFE51,000)").unescape(), false, status); + Formattable(-1000.5), UnicodeString("(\\uFFE51,000)").unescape(), false, status); expect(NumberFormat::createInstance("de_DE", style, status), - (Formattable)(double)-23456.7, UnicodeString("-23.456,70\\u00A0\\u20AC").unescape(), true, status); + Formattable(-23456.7), UnicodeString("-23.456,70\\u00A0\\u20AC").unescape(), true, status); expect(NumberFormat::createInstance("en_ID", style, status), - (Formattable)(double)0, UnicodeString("Rp\\u00A00,00").unescape(), true, status); + Formattable(static_cast(0)), UnicodeString("Rp\\u00A00,00").unescape(), true, status); expect(NumberFormat::createInstance("en_ID", style, status), - (Formattable)(double)-0.2, UnicodeString("(Rp\\u00A00,20)").unescape(), true, status); + Formattable(-0.2), UnicodeString("(Rp\\u00A00,20)").unescape(), true, status); expect(NumberFormat::createInstance("sh_ME", style, status), - (Formattable)(double)0, UnicodeString("0,00\\u00A0\\u20AC").unescape(), true, status); + Formattable(static_cast(0)), UnicodeString("0,00\\u00A0\\u20AC").unescape(), true, status); expect(NumberFormat::createInstance("sh_ME", style, status), - (Formattable)(double)-0.2, UnicodeString("(0,20\\u00A0\\u20AC)").unescape(), true, status); + Formattable(-0.2), UnicodeString("(0,20\\u00A0\\u20AC)").unescape(), true, status); } /** @@ -8196,7 +8196,7 @@ void NumberFormatTest::TestCurrencyUsage() { // test the getter here UCurrencyUsage curUsage = fmt->getCurrencyUsage(); - assertEquals("Test usage getter - standard", (int32_t)curUsage, (int32_t)UCURR_USAGE_STANDARD); + assertEquals("Test usage getter - standard", static_cast(curUsage), static_cast(UCURR_USAGE_STANDARD)); fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ @@ -8208,7 +8208,7 @@ void NumberFormatTest::TestCurrencyUsage() { // must be usage = cash UCurrencyUsage curUsage = fmt->getCurrencyUsage(); - assertEquals("Test usage getter - cash", (int32_t)curUsage, (int32_t)UCURR_USAGE_CASH); + assertEquals("Test usage getter - cash", static_cast(curUsage), static_cast(UCURR_USAGE_CASH)); UnicodeString cash_currency; fmt->format(agent,cash_currency); @@ -8291,22 +8291,22 @@ void NumberFormatTest::TestCurrencyUsage() { void NumberFormatTest::TestDoubleLimit11439() { char buf[50]; for (int64_t num = MAX_INT64_IN_DOUBLE-10; num<=MAX_INT64_IN_DOUBLE; num++) { - snprintf(buf, sizeof(buf), "%lld", (long long)num); + snprintf(buf, sizeof(buf), "%lld", static_cast(num)); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast(fNum); if (num != rtNum) { - errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); + errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, static_cast(num), static_cast(rtNum)); return; } } for (int64_t num = -MAX_INT64_IN_DOUBLE+10; num>=-MAX_INT64_IN_DOUBLE; num--) { - snprintf(buf, sizeof(buf), "%lld", (long long)num); + snprintf(buf, sizeof(buf), "%lld", static_cast(num)); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast(fNum); if (num != rtNum) { - errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); + errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, static_cast(num), static_cast(rtNum)); return; } } @@ -8481,13 +8481,13 @@ void NumberFormatTest::TestCtorApplyPatternDifference() { assertEquals( "ctor favors precision of currency", "$5.00", - fmt.format((double)5, result)); + fmt.format(static_cast(5), result)); result.remove(); fmt.applyPattern(pattern.unescape(), status); assertEquals( "applyPattern favors precision of pattern", "$5", - fmt.format((double)5, result)); + fmt.format(static_cast(5), result)); } void NumberFormatTest::Test11868() { @@ -9030,9 +9030,9 @@ void NumberFormatTest::TestFormatFailIfMoreThanMaxDigits() { if (status.errDataIfFailureAndReset()) { return; } - assertEquals("Coverage for getter 1", (UBool) false, df.isFormatFailIfMoreThanMaxDigits()); + assertEquals("Coverage for getter 1", static_cast(false), df.isFormatFailIfMoreThanMaxDigits()); df.setFormatFailIfMoreThanMaxDigits(true); - assertEquals("Coverage for getter 2", (UBool) true, df.isFormatFailIfMoreThanMaxDigits()); + assertEquals("Coverage for getter 2", static_cast(true), df.isFormatFailIfMoreThanMaxDigits()); df.setMaximumIntegerDigits(2); UnicodeString result; df.format(1234, result, status); @@ -9046,9 +9046,9 @@ void NumberFormatTest::TestParseCaseSensitive() { if (status.errDataIfFailureAndReset()) { return; } - assertEquals("Coverage for getter 1", (UBool) false, df.isParseCaseSensitive()); + assertEquals("Coverage for getter 1", static_cast(false), df.isParseCaseSensitive()); df.setParseCaseSensitive(true); - assertEquals("Coverage for getter 1", (UBool) true, df.isParseCaseSensitive()); + assertEquals("Coverage for getter 1", static_cast(true), df.isParseCaseSensitive()); Formattable result; ParsePosition ppos; df.parse(u"1e2", result, ppos); @@ -9063,9 +9063,9 @@ void NumberFormatTest::TestParseNoExponent() { if (status.errDataIfFailureAndReset()) { return; } - assertEquals("Coverage for getter 1", (UBool) false, df.isParseNoExponent()); + assertEquals("Coverage for getter 1", static_cast(false), df.isParseNoExponent()); df.setParseNoExponent(true); - assertEquals("Coverage for getter 1", (UBool) true, df.isParseNoExponent()); + assertEquals("Coverage for getter 1", static_cast(true), df.isParseNoExponent()); Formattable result; ParsePosition ppos; df.parse(u"1E2", result, ppos); @@ -9080,9 +9080,9 @@ void NumberFormatTest::TestSignAlwaysShown() { if (status.errDataIfFailureAndReset()) { return; } - assertEquals("Coverage for getter 1", (UBool) false, df.isSignAlwaysShown()); + assertEquals("Coverage for getter 1", static_cast(false), df.isSignAlwaysShown()); df.setSignAlwaysShown(true); - assertEquals("Coverage for getter 1", (UBool) true, df.isSignAlwaysShown()); + assertEquals("Coverage for getter 1", static_cast(true), df.isSignAlwaysShown()); UnicodeString result; df.format(1234, result, status); status.errIfFailureAndReset(); diff --git a/icu4c/source/test/intltest/numfmtst.h b/icu4c/source/test/intltest/numfmtst.h index 4cb0f01e6a04..5bdbc131cda3 100644 --- a/icu4c/source/test/intltest/numfmtst.h +++ b/icu4c/source/test/intltest/numfmtst.h @@ -399,7 +399,7 @@ class NumberFormatTest: public CalendarTimeZoneTest { void expectPad(DecimalFormat& fmt, const char *pat, int32_t pos) { - expectPad(fmt, pat, pos, 0, (char16_t)0); + expectPad(fmt, pat, pos, 0, static_cast(0)); } void expect_rbnf(NumberFormat& fmt, const UnicodeString& str, const Formattable& n); diff --git a/icu4c/source/test/intltest/numrgts.cpp b/icu4c/source/test/intltest/numrgts.cpp index 56316d35d4db..c517a22d7397 100644 --- a/icu4c/source/test/intltest/numrgts.cpp +++ b/icu4c/source/test/intltest/numrgts.cpp @@ -69,7 +69,7 @@ class MyNumberFormatTest : public NumberFormat Formattable& result, ParsePosition& /* parsePosition */) const override { - result.setLong((int32_t)0); + result.setLong(static_cast(0)); } virtual void parse( const UnicodeString& text, @@ -334,7 +334,7 @@ void NumberFormatRegressionTest::Test4087245() FieldPosition pos(FieldPosition::DONT_CARE); logln(UnicodeString("format(") + n + ") = " + df->format(n, buf1, pos)); - symbols->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, UnicodeString((char16_t)0x70)); // change value of field + symbols->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, UnicodeString(static_cast(0x70))); // change value of field logln(UnicodeString("format(") + n + ") = " + df->format(n, buf2, pos)); if(buf1 != buf2) @@ -387,7 +387,7 @@ void NumberFormatRegressionTest::Test4088503() UnicodeString sBuf; FieldPosition fp(FieldPosition::DONT_CARE); //try { - logln(df->format((int32_t)123, sBuf, fp)); + logln(df->format(static_cast(123), sBuf, fp)); //if(fp == FieldPosition(FieldPosition::DONT_CARE)) // errln("Test for bug 4088503 failed."); /*} catch (Exception foo) { @@ -425,7 +425,7 @@ NumberFormatRegressionTest::assignFloatValue(float returnfloat) Formattable result; nfcommon->parse(stringValue, result, status); failure(status, "nfcommon->parse", Locale::getUS()); - float floatResult = (float) (result.getType() == Formattable::kDouble + float floatResult = static_cast(result.getType() == Formattable::kDouble ? result.getDouble() : result.getLong()); if( uprv_fabs(floatResult - returnfloat) > 0.0001) //String stringValue = nfcommon.format(returnfloat).substring(1); @@ -540,8 +540,8 @@ void NumberFormatRegressionTest::Test4086575() logln("nf toLocPattern2: " + nf->toLocalizedPattern(temp)); FieldPosition pos(FieldPosition::DONT_CARE); - logln("nf: " + nf->format((int32_t)1234, temp, pos)); // 1234,00 - logln("nf: " + nf->format((int32_t)-1234, temp, pos)); // (1234,00) + logln("nf: " + nf->format(static_cast(1234), temp, pos)); // 1234,00 + logln("nf: " + nf->format(static_cast(-1234), temp, pos)); // (1234,00) // Space as group separator @@ -558,7 +558,7 @@ void NumberFormatRegressionTest::Test4086575() logln("nf toPattern2: " + nf->toPattern(temp)); logln("nf toLocPattern2: " + nf->toLocalizedPattern(temp)); UnicodeString buffer; - buffer = nf->format((int32_t)1234, buffer, pos); + buffer = nf->format(static_cast(1234), buffer, pos); //if (buffer != UnicodeString("1\u00a0234,00")) char16_t c[] = { 0x31, 0x202f, 0x32, 0x33, 0x34, 0x2c, 0x30, 0x30 @@ -568,7 +568,7 @@ void NumberFormatRegressionTest::Test4086575() errln("nf : " + buffer); // Expect 1 234,00 buffer.remove(); - buffer = nf->format((int32_t)-1234, buffer, pos); + buffer = nf->format(static_cast(-1234), buffer, pos); char16_t c1[] = { 0x28, 0x31, 0x202f, 0x32, 0x33, 0x34, 0x2c, 0x30, 0x30, 0x29 }; @@ -811,28 +811,28 @@ void NumberFormatRegressionTest::Test4092480() if (dfFoo->toPattern(temp) != UnicodeString("0000")) errln("ERROR: dfFoo.toPattern : " + dfFoo->toPattern(temp)); FieldPosition pos(FieldPosition::DONT_CARE); - logln(dfFoo->format((int32_t)42, temp, pos)); - logln(dfFoo->format((int32_t)-42, temp, pos)); + logln(dfFoo->format(static_cast(42), temp, pos)); + logln(dfFoo->format(static_cast(-42), temp, pos)); dfFoo->applyPattern("000;-000", status); failure(status, "dfFoo->applyPattern"); if (dfFoo->toPattern(temp) != UnicodeString("000")) errln("ERROR: dfFoo.toPattern : " + dfFoo->toPattern(temp)); - logln(dfFoo->format((int32_t)42,temp, pos)); - logln(dfFoo->format((int32_t)-42, temp, pos)); + logln(dfFoo->format(static_cast(42), temp, pos)); + logln(dfFoo->format(static_cast(-42), temp, pos)); dfFoo->applyPattern("000;-0000", status); failure(status, "dfFoo->applyPattern"); if (dfFoo->toPattern(temp) != UnicodeString("000")) errln("ERROR: dfFoo.toPattern : " + dfFoo->toPattern(temp)); - logln(dfFoo->format((int32_t)42, temp, pos)); - logln(dfFoo->format((int32_t)-42, temp, pos)); + logln(dfFoo->format(static_cast(42), temp, pos)); + logln(dfFoo->format(static_cast(-42), temp, pos)); dfFoo->applyPattern("0000;-000", status); failure(status, "dfFoo->applyPattern"); if (dfFoo->toPattern(temp) != UnicodeString("0000")) errln("ERROR: dfFoo.toPattern : " + dfFoo->toPattern(temp)); - logln(dfFoo->format((int32_t)42, temp, pos)); - logln(dfFoo->format((int32_t)-42, temp, pos)); + logln(dfFoo->format(static_cast(42), temp, pos)); + logln(dfFoo->format(static_cast(-42), temp, pos)); /*} catch (Exception foo) { errln("Message " + foo.getMessage()); }*/ @@ -876,9 +876,9 @@ void NumberFormatRegressionTest::Test4087244() { FieldPosition pos; df->format(1.23, str, pos); UnicodeString monStr("1x23"); - monStr.replace((int32_t)1, 1, monSep); + monStr.replace(static_cast(1), 1, monSep); UnicodeString decStr("1x23"); - decStr.replace((int32_t)1, 1, decSep); + decStr.replace(static_cast(1), 1, decSep); if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) { logln(UnicodeString("OK: 1.23 -> \"") + str + "\" contains \"" + monStr + "\" and not \"" + decStr + '"'); @@ -1367,16 +1367,16 @@ void NumberFormatRegressionTest::Test4061302() } UnicodeString monDecSeparatorStr; monDecSeparatorStr.append(monDecSeparator); - logln((UnicodeString)"Before set ==> Currency : " + currency +(UnicodeString)" Intl Currency : " + intlCurrency + (UnicodeString)" Monetary Decimal Separator : " + monDecSeparatorStr); + logln(UnicodeString("Before set ==> Currency : ") + currency + UnicodeString(" Intl Currency : ") + intlCurrency + UnicodeString(" Monetary Decimal Separator : ") + monDecSeparatorStr); fmt->setSymbol(DecimalFormatSymbols::kCurrencySymbol, UnicodeString("XYZ")); fmt->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, UnicodeString("ABC")); - fmt->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, UnicodeString((char16_t)0x002A/*'*'*/)); + fmt->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, UnicodeString(static_cast(0x002A)/*'*'*/)); currency = fmt->getSymbol(DecimalFormatSymbols::kCurrencySymbol); intlCurrency = fmt->getSymbol(DecimalFormatSymbols::kIntlCurrencySymbol); monDecSeparator = fmt->getSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol); if (currency != UnicodeString("XYZ") || intlCurrency != UnicodeString("ABC") || - monDecSeparator != UnicodeString((char16_t)0x002A/*'*'*/)) { + monDecSeparator != UnicodeString(static_cast(0x002A)/*'*'*/)) { errln("setCurrencySymbols failed."); } monDecSeparatorStr.remove(); @@ -1754,7 +1754,7 @@ void NumberFormatRegressionTest::Test4122840() fmt2->format(1.111, result2, pos); if (result1 != result2) { - errln("Results for " + (UnicodeString)(locales[i].getName()) + " differ: " + + errln("Results for " + UnicodeString(locales[i].getName()) + " differ: " + result1 + " vs " + result2); } @@ -1819,7 +1819,7 @@ void NumberFormatRegressionTest::Test4134034() errln("9.02 -> " + f + "; want 9.02"); f.remove(); - f = nf->format((int32_t)0, f, pos); + f = nf->format(static_cast(0), f, pos); if (f == UnicodeString(".00")) logln(f + " ok"); else @@ -1948,7 +1948,7 @@ void NumberFormatRegressionTest::Test4145457() { } DecimalFormatSymbols *sym = const_cast(nf->getDecimalFormatSymbols()); - sym->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, (char16_t)/*'\''*/0x0027); + sym->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, static_cast(0x0027)); nf->setDecimalFormatSymbols(*sym); double pi = 3.14159; @@ -2335,23 +2335,23 @@ void NumberFormatRegressionTest::Test4212072() { UnicodeString s; FieldPosition pos; - sym.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, (char16_t)0x5e); + sym.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, static_cast(0x5e)); fmt.setDecimalFormatSymbols(sym); s.remove(); - if (fmt.format((int32_t)-1, s, pos) != UNICODE_STRING("^1", 2)) { + if (fmt.format(static_cast(-1), s, pos) != UNICODE_STRING("^1", 2)) { errln(UnicodeString("FAIL: -1 x (minus=^) -> ") + s + ", exp ^1"); } s.remove(); - if (fmt.getNegativePrefix(s) != UnicodeString((char16_t)0x5e)) { + if (fmt.getNegativePrefix(s) != UnicodeString(static_cast(0x5e))) { errln(UnicodeString("FAIL: (minus=^).getNegativePrefix -> ") + s + ", exp ^"); } - sym.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, (char16_t)0x2d); + sym.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, static_cast(0x2d)); fmt.applyPattern(UnicodeString("#%"), status); failure(status, "applyPattern percent"); - sym.setSymbol(DecimalFormatSymbols::kPercentSymbol, (char16_t)0x5e); + sym.setSymbol(DecimalFormatSymbols::kPercentSymbol, static_cast(0x5e)); fmt.setDecimalFormatSymbols(sym); s.remove(); if (fmt.format(0.25, s, pos) != UNICODE_STRING("25^", 3)) { @@ -2359,15 +2359,15 @@ void NumberFormatRegressionTest::Test4212072() { ", exp 25^"); } s.remove(); - if (fmt.getPositiveSuffix(s) != UnicodeString((char16_t)0x5e)) { + if (fmt.getPositiveSuffix(s) != UnicodeString(static_cast(0x5e))) { errln(UnicodeString("FAIL: (percent=^).getPositiveSuffix -> ") + s + ", exp ^"); } - sym.setSymbol(DecimalFormatSymbols::kPercentSymbol, (char16_t)0x25); + sym.setSymbol(DecimalFormatSymbols::kPercentSymbol, static_cast(0x25)); fmt.applyPattern(str("#\\u2030"), status); failure(status, "applyPattern permill"); - sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, (char16_t)0x5e); + sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, static_cast(0x5e)); fmt.setDecimalFormatSymbols(sym); s.remove(); if (fmt.format(0.25, s, pos) != UNICODE_STRING("250^", 4)) { @@ -2375,11 +2375,11 @@ void NumberFormatRegressionTest::Test4212072() { ", exp 250^"); } s.remove(); - if (fmt.getPositiveSuffix(s) != UnicodeString((char16_t)0x5e)) { + if (fmt.getPositiveSuffix(s) != UnicodeString(static_cast(0x5e))) { errln(UnicodeString("FAIL: (permill=^).getPositiveSuffix -> ") + s + ", exp ^"); } - sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, (char16_t)0x2030); + sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, static_cast(0x2030)); fmt.applyPattern(str("\\u00A4#.00"), status); failure(status, "applyPattern currency"); @@ -2519,7 +2519,7 @@ void NumberFormatRegressionTest::Test4216742() { int32_t DATA[] = { INT32_MIN, INT32_MAX, -100000000, 100000000 }; int DATA_length = UPRV_LENGTHOF(DATA); for (int i=0; isetMultiplier(m); Formattable num; @@ -2531,7 +2531,7 @@ void NumberFormatRegressionTest::Test4216742() { toString(num)); } else { double d = num.getType() == Formattable::kDouble ? - num.getDouble() : (double) num.getLong(); + num.getDouble() : static_cast(num.getLong()); if ((d > 0) != (DATA[i] > 0)) { errln(UnicodeString("\"") + str + "\" parse(x " + fmt->getMultiplier() + @@ -2687,14 +2687,14 @@ void NumberFormatRegressionTest::TestJ691() { // create a Calendar for this locale LocalPointer cal(Calendar::createInstance(loc, status)); if (U_FAILURE(status)) { - dataerrln("FAIL: Calendar::createInstance() returned " + (UnicodeString)u_errorName(status)); + dataerrln("FAIL: Calendar::createInstance() returned " + UnicodeString(u_errorName(status))); return; } // create a NumberFormat for this locale LocalPointer nf(NumberFormat::createInstance(loc, status)); if (U_FAILURE(status)) { - dataerrln("FAIL: NumberFormat::createInstance() returned " + (UnicodeString)u_errorName(status)); + dataerrln("FAIL: NumberFormat::createInstance() returned " + UnicodeString(u_errorName(status))); return; } @@ -2707,7 +2707,7 @@ void NumberFormatRegressionTest::TestJ691() { // create the DateFormat LocalPointer df(DateFormat::createDateInstance(DateFormat::kShort, loc)); if (U_FAILURE(status)) { - errln("FAIL: DateFormat::createInstance() returned " + (UnicodeString)u_errorName(status)); + errln("FAIL: DateFormat::createInstance() returned " + UnicodeString(u_errorName(status))); return; } diff --git a/icu4c/source/test/intltest/pluralmaptest.cpp b/icu4c/source/test/intltest/pluralmaptest.cpp index 6b8aa1834e6e..4d8b745df54e 100644 --- a/icu4c/source/test/intltest/pluralmaptest.cpp +++ b/icu4c/source/test/intltest/pluralmaptest.cpp @@ -56,24 +56,24 @@ void PluralMapTest::runIndexedTest(int32_t index, UBool exec, const char* &name, } void PluralMapTest::TestToCategory() { - assertEquals("", (int32_t)PluralMapBase::OTHER, PluralMapBase::toCategory("other")); - assertEquals("", (int32_t)PluralMapBase::ZERO, PluralMapBase::toCategory("zero")); - assertEquals("", (int32_t)PluralMapBase::ONE, PluralMapBase::toCategory("one")); - assertEquals("", (int32_t)PluralMapBase::TWO, PluralMapBase::toCategory("two")); - assertEquals("", (int32_t)PluralMapBase::FEW, PluralMapBase::toCategory("few")); - assertEquals("", (int32_t)PluralMapBase::MANY, PluralMapBase::toCategory("many")); - assertEquals("", (int32_t)PluralMapBase::NONE, PluralMapBase::toCategory("Many")); + assertEquals("", static_cast(PluralMapBase::OTHER), PluralMapBase::toCategory("other")); + assertEquals("", static_cast(PluralMapBase::ZERO), PluralMapBase::toCategory("zero")); + assertEquals("", static_cast(PluralMapBase::ONE), PluralMapBase::toCategory("one")); + assertEquals("", static_cast(PluralMapBase::TWO), PluralMapBase::toCategory("two")); + assertEquals("", static_cast(PluralMapBase::FEW), PluralMapBase::toCategory("few")); + assertEquals("", static_cast(PluralMapBase::MANY), PluralMapBase::toCategory("many")); + assertEquals("", static_cast(PluralMapBase::NONE), PluralMapBase::toCategory("Many")); assertEquals( "", - (int32_t)PluralMapBase::FEW, + static_cast(PluralMapBase::FEW), PluralMapBase::toCategory(UnicodeString("few"))); assertEquals( "", - (int32_t)PluralMapBase::MANY, + static_cast(PluralMapBase::MANY), PluralMapBase::toCategory(UnicodeString("many"))); assertEquals( "", - (int32_t)PluralMapBase::NONE, + static_cast(PluralMapBase::NONE), PluralMapBase::toCategory(UnicodeString("Many"))); } @@ -117,24 +117,24 @@ void PluralMapTest::TestIterate() { PluralMapBase::Category index = PluralMapBase::NONE; const UnicodeString *current = map.next(index); assertEquals("", "pickles", *current); - assertEquals("", (int32_t)PluralMapBase::OTHER, index); + assertEquals("", static_cast(PluralMapBase::OTHER), index); current = map.next(index); assertEquals("", "pickle", *current); - assertEquals("", (int32_t)PluralMapBase::ONE, index); + assertEquals("", static_cast(PluralMapBase::ONE), index); current = map.next(index); assertEquals("", "picklefew", *current); - assertEquals("", (int32_t)PluralMapBase::FEW, index); + assertEquals("", static_cast(PluralMapBase::FEW), index); current = map.next(index); - assertEquals("", (int32_t)PluralMapBase::CATEGORY_COUNT, index); + assertEquals("", static_cast(PluralMapBase::CATEGORY_COUNT), index); assertTrue("", current == nullptr); PluralMapForPluralMapTest map2; index = PluralMapBase::NONE; current = map2.next(index); assertEquals("", "", *current); - assertEquals("", (int32_t)PluralMapBase::OTHER, index); + assertEquals("", static_cast(PluralMapBase::OTHER), index); current = map2.next(index); - assertEquals("", (int32_t)PluralMapBase::CATEGORY_COUNT, index); + assertEquals("", static_cast(PluralMapBase::CATEGORY_COUNT), index); assertTrue("", current == nullptr); } diff --git a/icu4c/source/test/intltest/plurfmts.cpp b/icu4c/source/test/intltest/plurfmts.cpp index 9183ae8da11b..6cae4488deb5 100644 --- a/icu4c/source/test/intltest/plurfmts.cpp +++ b/icu4c/source/test/intltest/plurfmts.cpp @@ -147,7 +147,7 @@ void PluralFormatTest::pluralFormatBasicTest(/*char *par*/) PluralFormat *pf = new PluralFormat(stat); Formattable *f = new Formattable(); ParsePosition *pp = new ParsePosition(); - pf->parseObject((UnicodeString)"",*f,*pp); + pf->parseObject(UnicodeString(""), *f, *pp); if(U_FAILURE(stat)) { dataerrln("ERROR: PluralFormat::parseObject: %s", u_errorName(stat)); } @@ -268,7 +268,7 @@ void PluralFormatTest::pluralFormatUnitTest(/*char *par*/) } numberFormatTest(&pluralFmt, numFmt.getAlias(), 5, 5, nullptr, nullptr, false, &message); pluralFmt.applyPattern(UNICODE_STRING_SIMPLE("odd__{odd} other{even}"), status); - if (pluralFmt.format((int32_t)1, status) != UNICODE_STRING_SIMPLE("even")) { + if (pluralFmt.format(static_cast(1), status) != UNICODE_STRING_SIMPLE("even")) { errln("SetLocale should reset rules but did not."); } status = U_ZERO_ERROR; @@ -558,7 +558,7 @@ PluralFormatTest::pluralFormatExtendedTest() { UErrorCode status = U_ZERO_ERROR; UnicodeString fmtString(fmt, -1, US_INV); PluralFormat pf(Locale::getEnglish(), fmtString, status); - MessageFormat mf(UNICODE_STRING_SIMPLE("{0,plural,").append(fmtString).append((char16_t)0x7d /* '}' */), + MessageFormat mf(UNICODE_STRING_SIMPLE("{0,plural,").append(fmtString).append(static_cast(0x7d) /* '}' */), Locale::getEnglish(), status); Formattable args; FieldPosition ignore; @@ -627,17 +627,17 @@ PluralFormatTest::ordinalFormatTest() { if (errorCode.errDataIfFailureAndReset("PluralFormat(en, UPLURAL_TYPE_ORDINAL, pattern) failed")) { return; } - UnicodeString result = pf.format((int32_t)321, errorCode); + UnicodeString result = pf.format(static_cast(321), errorCode); if (!errorCode.errIfFailureAndReset("PluralFormat.format(321) failed") && result != UNICODE_STRING_SIMPLE("321st file")) { errln(UnicodeString("PluralFormat.format(321) wrong result string: ") + result); } - result = pf.format((int32_t)22, errorCode); + result = pf.format(static_cast(22), errorCode); if (!errorCode.errIfFailureAndReset("PluralFormat.format(22) failed") && result != UNICODE_STRING_SIMPLE("22nd file")) { errln(UnicodeString("PluralFormat.format(22) wrong result string: ") + result); } - result = pf.format((int32_t)3, errorCode); + result = pf.format(static_cast(3), errorCode); if (!errorCode.errIfFailureAndReset("PluralFormat.format(3) failed") && result != UNICODE_STRING_SIMPLE("3rd file")) { errln(UnicodeString("PluralFormat.format(3) wrong result string: ") + result); @@ -649,12 +649,12 @@ PluralFormatTest::ordinalFormatTest() { if (errorCode.errIfFailureAndReset("PluralFormat(en, UPLURAL_TYPE_ORDINAL, pattern) failed")) { return; } - result = pf2.format((int32_t)456, errorCode); + result = pf2.format(static_cast(456), errorCode); if (!errorCode.errIfFailureAndReset("PluralFormat.format(456) failed") && result != UNICODE_STRING_SIMPLE("456th file")) { errln(UnicodeString("PluralFormat.format(456) wrong result string: ") + result); } - result = pf2.format((int32_t)111, errorCode); + result = pf2.format(static_cast(111), errorCode); if (!errorCode.errIfFailureAndReset("PluralFormat.format(111) failed") && result != UNICODE_STRING_SIMPLE("111th file")) { errln(UnicodeString("PluralFormat.format(111) wrong result string: ") + result); @@ -666,14 +666,14 @@ PluralFormatTest::TestDecimals() { IcuTestErrorCode errorCode(*this, "TestDecimals"); // Simple number replacement. PluralFormat pf(Locale::getEnglish(), "one{one meter}other{# meters}", errorCode); - assertEquals("simple format(1)", "one meter", pf.format((int32_t)1, errorCode), true); + assertEquals("simple format(1)", "one meter", pf.format(static_cast(1), errorCode), true); assertEquals("simple format(1.5)", "1.5 meters", pf.format(1.5, errorCode), true); PluralFormat pf2(Locale::getEnglish(), "offset:1 one{another meter}other{another # meters}", errorCode); DecimalFormat df("0.0", new DecimalFormatSymbols(Locale::getEnglish(), errorCode), errorCode); pf2.setNumberFormat(&df, errorCode); - assertEquals("offset-decimals format(1)", "another 0.0 meters", pf2.format((int32_t)1, errorCode), true); - assertEquals("offset-decimals format(2)", "another 1.0 meters", pf2.format((int32_t)2, errorCode), true); + assertEquals("offset-decimals format(1)", "another 0.0 meters", pf2.format(static_cast(1), errorCode), true); + assertEquals("offset-decimals format(2)", "another 1.0 meters", pf2.format(static_cast(2), errorCode), true); assertEquals("offset-decimals format(2.5)", "another 1.5 meters", pf2.format(2.5, errorCode), true); errorCode.reset(); } @@ -750,7 +750,7 @@ PluralFormatTest::helperTestResults(const char** localeArray, for (int32_t i=0; i(0), us.length(), (char*)nullptr, static_cast(0)) + 1; + buf = static_cast(uprv_malloc(bufLen)); us.extract(0, us.length(), buf, bufLen); } const char *cstr() {return buf;} ~US() { uprv_free(buf);} @@ -746,7 +746,7 @@ void PluralRulesTest::testWithin() { return; } - UnicodeString keyword = rules->select((int32_t)26); + UnicodeString keyword = rules->select(static_cast(26)); if (keyword != "a") { errln("expected 'a' for 26 but didn't get it."); } diff --git a/icu4c/source/test/intltest/quantityformattertest.cpp b/icu4c/source/test/intltest/quantityformattertest.cpp index e1bacc5d9edd..3c410bce6a01 100644 --- a/icu4c/source/test/intltest/quantityformattertest.cpp +++ b/icu4c/source/test/intltest/quantityformattertest.cpp @@ -47,12 +47,12 @@ void QuantityFormatterTest::TestBasic() { assertFalse( "adding bad variant", fmt.addIfAbsent("a bad variant", "{0} pounds", status)); - assertEquals("adding bad variant status", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status); + assertEquals("adding bad variant status", static_cast(U_ILLEGAL_ARGUMENT_ERROR), status); status = U_ZERO_ERROR; assertFalse( "Adding bad pattern", fmt.addIfAbsent("other", "{0} {1} too many placeholders", status)); - assertEquals("adding bad pattern status", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status); + assertEquals("adding bad pattern status", static_cast(U_ILLEGAL_ARGUMENT_ERROR), status); status = U_ZERO_ERROR; assertFalse("isValid with no patterns", fmt.isValid()); assertTrue( diff --git a/icu4c/source/test/intltest/rbbiapts.cpp b/icu4c/source/test/intltest/rbbiapts.cpp index 9013f18bb7df..60fbcdaa7db3 100644 --- a/icu4c/source/test/intltest/rbbiapts.cpp +++ b/icu4c/source/test/intltest/rbbiapts.cpp @@ -67,9 +67,9 @@ void RBBIAPITest::TestCloneEquals() bi3->setText("hello"); - logln((UnicodeString)"Testing equals()"); + logln(UnicodeString("Testing equals()")); - logln((UnicodeString)"Testing == and !="); + logln(UnicodeString("Testing == and !=")); bool b = (*bi1 != *biequal); b |= *bi1 == *bi2; b |= *bi1 == *bi3; @@ -131,7 +131,7 @@ void RBBIAPITest::TestCloneEquals() - logln((UnicodeString)"Testing clone()"); + logln(UnicodeString("Testing clone()")); RuleBasedBreakIterator* bi1clone = bi1->clone(); RuleBasedBreakIterator* bi2clone = bi2->clone(); @@ -198,7 +198,7 @@ void RBBIAPITest::TestgetRules() return; } - logln((UnicodeString)"Testing getRules()"); + logln(UnicodeString("Testing getRules()")); UnicodeString text(u"Hello there"); bi1->setText(text); @@ -232,22 +232,22 @@ void RBBIAPITest::TestHashCode() } - logln((UnicodeString)"Testing hashCode()"); + logln(UnicodeString("Testing hashCode()")); - bi1->setText((UnicodeString)"Hash code"); - bi2->setText((UnicodeString)"Hash code"); - bi3->setText((UnicodeString)"Hash code"); + bi1->setText(UnicodeString("Hash code")); + bi2->setText(UnicodeString("Hash code")); + bi3->setText(UnicodeString("Hash code")); RuleBasedBreakIterator* bi1clone= bi1->clone(); RuleBasedBreakIterator* bi2clone= bi2->clone(); if(bi1->hashCode() != bi1clone->hashCode() || bi1->hashCode() != bi3->hashCode() || bi1clone->hashCode() != bi3->hashCode() || bi2->hashCode() != bi2clone->hashCode()) - errln((UnicodeString)"ERROR: identical objects have different hashcodes"); + errln(UnicodeString("ERROR: identical objects have different hashcodes")); if(bi1->hashCode() == bi2->hashCode() || bi2->hashCode() == bi3->hashCode() || bi1clone->hashCode() == bi2clone->hashCode() || bi1clone->hashCode() == bi2->hashCode()) - errln((UnicodeString)"ERROR: different objects have same hashcodes"); + errln(UnicodeString("ERROR: different objects have same hashcodes")); delete bi1clone; delete bi2clone; @@ -258,7 +258,7 @@ void RBBIAPITest::TestHashCode() } void RBBIAPITest::TestGetSetAdoptText() { - logln((UnicodeString)"Testing getText setText "); + logln(UnicodeString("Testing getText setText ")); IcuTestErrorCode status(*this, "TestGetSetAdoptText"); UnicodeString str1="first string."; UnicodeString str2="Second string."; @@ -281,13 +281,13 @@ void RBBIAPITest::TestGetSetAdoptText() tci->getText(tstr); TEST_ASSERT(tstr == str1); if(wordIter1->current() != 0) - errln((UnicodeString)"ERROR:1 setText did not set the iteration position to the beginning of the text, it is" + wordIter1->current() + (UnicodeString)"\n"); + errln(UnicodeString("ERROR:1 setText did not set the iteration position to the beginning of the text, it is") + wordIter1->current() + UnicodeString("\n")); wordIter1->next(2); wordIter1->setText(str2); if(wordIter1->current() != 0) - errln((UnicodeString)"ERROR:2 setText did not reset the iteration position to the beginning of the text, it is" + wordIter1->current() + (UnicodeString)"\n"); + errln(UnicodeString("ERROR:2 setText did not reset the iteration position to the beginning of the text, it is") + wordIter1->current() + UnicodeString("\n")); charIter1->adoptText(text1Clone); @@ -303,10 +303,10 @@ void RBBIAPITest::TestGetSetAdoptText() LocalPointer rb(wordIter1->clone()); rb->adoptText(text1); if(rb->getText() != *text1) - errln((UnicodeString)"ERROR:1 error in adoptText "); + errln(UnicodeString("ERROR:1 error in adoptText ")); rb->adoptText(text2); if(rb->getText() != *text2) - errln((UnicodeString)"ERROR:2 error in adoptText "); + errln(UnicodeString("ERROR:2 error in adoptText ")); // Adopt where iterator range is less than the entire original source string. // (With the change of the break engine to working with UText internally, @@ -1068,9 +1068,9 @@ void RBBIAPITest::RoundtripRule(const char *dataFile) { return; } - builtRules = (const uint8_t *)udata_getMemory(data.getAlias()); + builtRules = static_cast(udata_getMemory(data.getAlias())); builtSource = UnicodeString::fromUTF8( - (const char *)(builtRules + ((RBBIDataHeader *)builtRules)->fRuleSource)); + reinterpret_cast(builtRules + reinterpret_cast(builtRules)->fRuleSource)); LocalPointer brkItr (new RuleBasedBreakIterator(builtSource, parseError, status)); if (U_FAILURE(status)) { errln("%s:%d createRuleBasedBreakIterator: ICU Error \"%s\" at line %d, column %d\n", @@ -1080,7 +1080,7 @@ void RBBIAPITest::RoundtripRule(const char *dataFile) { } rbbiRules = brkItr->getBinaryRules(length); logln("Comparing \"%s\" len=%d", dataFile, length); - if (memcmp(builtRules, rbbiRules, (int32_t)length) != 0) { + if (memcmp(builtRules, rbbiRules, static_cast(length)) != 0) { errln("%s:%d Built rules and rebuilt rules are different %s", __FILE__, __LINE__, dataFile); return; } @@ -1214,16 +1214,16 @@ static void prtbrks(BreakIterator* brk, const UnicodeString &ustr, IntlTest &it) } } UnicodeString out; - out.append((char16_t)CHSTR); + out.append(CHSTR); int32_t prev = 0; for(int32_t i=0;i " + isB); + logln(UnicodeString("bi.isBoundary(") + i + ") -> " + isB); if (i == boundaries[p]) { if (!isB) - errln((UnicodeString)"Wrong result from isBoundary() for " + i + (UnicodeString)": expected true, got false"); + errln(UnicodeString("Wrong result from isBoundary() for ") + i + UnicodeString(": expected true, got false")); p++; } else { if (isB) - errln((UnicodeString)"Wrong result from isBoundary() for " + i + (UnicodeString)": expected false, got true"); + errln(UnicodeString("Wrong result from isBoundary() for ") + i + UnicodeString(": expected false, got true")); } } } @@ -1501,7 +1501,7 @@ void RBBIAPITest::doTest(UnicodeString& testString, int32_t start, int32_t gotof UnicodeString expected=CharsToUnicodeString(expectedString); if(gotoffset != expectedOffset) - errln((UnicodeString)"ERROR:****returned #" + gotoffset + (UnicodeString)" instead of #" + expectedOffset); + errln(UnicodeString("ERROR:****returned #") + gotoffset + UnicodeString(" instead of #") + expectedOffset); if(start <= gotoffset){ testString.extractBetween(start, gotoffset, selected); } @@ -1509,7 +1509,7 @@ void RBBIAPITest::doTest(UnicodeString& testString, int32_t start, int32_t gotof testString.extractBetween(gotoffset, start, selected); } if(selected.compare(expected) != 0) - errln(prettify((UnicodeString)"ERROR:****selected \"" + selected + "\" instead of \"" + expected + "\"")); + errln(prettify(UnicodeString("ERROR:****selected \"") + selected + "\" instead of \"" + expected + "\"")); else logln(prettify("****selected \"" + selected + "\"")); } diff --git a/icu4c/source/test/intltest/rbbimonkeytest.cpp b/icu4c/source/test/intltest/rbbimonkeytest.cpp index 45fe3e43a419..b3ab0b009cbb 100644 --- a/icu4c/source/test/intltest/rbbimonkeytest.cpp +++ b/icu4c/source/test/intltest/rbbimonkeytest.cpp @@ -195,11 +195,11 @@ void BreakRules::addRule(const UnicodeString &name, const UnicodeString &definit // Replace the divide sign (\u00f7) with a regular expression named capture. // When running the rules, a match that includes this group means we found a break position. - int32_t dividePos = thisRule->fExpandedRule.indexOf((char16_t)0x00f7); + int32_t dividePos = thisRule->fExpandedRule.indexOf(static_cast(0x00f7)); if (dividePos >= 0) { thisRule->fExpandedRule.replace(dividePos, 1, UnicodeString("(?)")); } - if (thisRule->fExpandedRule.indexOf((char16_t)0x00f7) != -1) { + if (thisRule->fExpandedRule.indexOf(static_cast(0x00f7)) != -1) { status = U_ILLEGAL_ARGUMENT_ERROR; // TODO: produce a good error message. } @@ -207,7 +207,7 @@ void BreakRules::addRule(const UnicodeString &name, const UnicodeString &definit // Regular expression set expressions don't accept this. Substitute with [^\u0000-\U0010ffff], which // also matches nothing. - static const char16_t emptySet[] = {(char16_t)0x5b, (char16_t)0x5d, 0}; + static const char16_t emptySet[] = {static_cast(0x5b), static_cast(0x5d), 0}; int32_t where = 0; while ((where = thisRule->fExpandedRule.indexOf(emptySet, 2, 0)) >= 0) { thisRule->fExpandedRule.replace(where, 2, UnicodeString("[^\\u0000-\\U0010ffff]")); @@ -343,7 +343,7 @@ void BreakRules::compileRules(UCHARBUF *rules, UErrorCode &status) { // Also compute the "other" set, consisting of any characters not included in // one or more of the user defined sets. - UnicodeSet otherSet((UChar32)0, 0x10ffff); + UnicodeSet otherSet(static_cast(0), 0x10ffff); int32_t pos = UHASH_FIRST; const UHashElement *el = nullptr; while ((el = uhash_nextElement(fCharClasses.getAlias(), &pos)) != nullptr) { @@ -446,7 +446,7 @@ void MonkeyTestData::set(BreakRules *rules, IntlTest::icu_rand &rand, UErrorCode // Apply reference rules to find the expected breaks. - fExpectedBreaks.setCharAt(0, (char16_t)1); // Force an expected break before the start of the text. + fExpectedBreaks.setCharAt(0, static_cast(1)); // Force an expected break before the start of the text. // ICU always reports a break there. // The reference rules do not have a means to do so. int32_t strIdx = 0; @@ -501,9 +501,9 @@ void MonkeyTestData::set(BreakRules *rules, IntlTest::icu_rand &rand, UErrorCode // Record which rule matched over the length of the match. for (int i = matchStart; i < matchEnd; i++) { if (fRuleForPosition.charAt(i) == 0) { - fRuleForPosition.setCharAt(i, (char16_t)ruleNum); + fRuleForPosition.setCharAt(i, static_cast(ruleNum)); } else { - f2ndRuleForPos.setCharAt(i, (char16_t)ruleNum); + f2ndRuleForPos.setCharAt(i, static_cast(ruleNum)); } } @@ -520,7 +520,7 @@ void MonkeyTestData::set(BreakRules *rules, IntlTest::icu_rand &rand, UErrorCode status = U_INVALID_FORMAT_ERROR; break; } - fExpectedBreaks.setCharAt(breakPos, (char16_t)1); + fExpectedBreaks.setCharAt(breakPos, static_cast(1)); // printf("recording break at %d\n", breakPos); // For the next iteration, pick up applying rules immediately after the break, // which may differ from end of the match. The matching rule may have included @@ -556,7 +556,7 @@ void MonkeyTestData::clearActualBreaks() { // Actual Breaks length is one longer than the data string length, allowing // for breaks before the first and after the last character in the data. for (int32_t i=0; i<=fString.length(); i++) { - fActualBreaks.append((char16_t)0); + fActualBreaks.append(static_cast(0)); } } diff --git a/icu4c/source/test/intltest/rbbitst.cpp b/icu4c/source/test/intltest/rbbitst.cpp index 9e3157bdfacc..38dd3be39d78 100644 --- a/icu4c/source/test/intltest/rbbitst.cpp +++ b/icu4c/source/test/intltest/rbbitst.cpp @@ -200,7 +200,7 @@ static void printStringBreaks(UText *tstr, int expected[], int expectedCount) { UChar32 c = utext_next32(tstr); u_charName(c, U_UNICODE_CHAR_NAME, name, 100, &status); - printf("%7x %5d %6d %8d %4s %4s %4s %4s %s\n", (int)c, + printf("%7x %5d %6d %8d %4s %4s %4s %4s %s\n", static_cast(c), u_isUAlphabetic(c), u_hasBinaryProperty(c, UCHAR_GRAPHEME_EXTEND), u_isalnum(c), @@ -351,7 +351,7 @@ void RBBITest::TestBug4153072() { for (index = -1; index < begin + 1; ++index) { onBoundary = iter->isBoundary(index); if (index == 0? !onBoundary : onBoundary) { - errln((UnicodeString)"Didn't handle isBoundary correctly with offset = " + index + + errln(UnicodeString("Didn't handle isBoundary correctly with offset = ") + index + " and begin index = " + begin); } } @@ -1394,7 +1394,7 @@ void RBBITest::runUnicodeTestData(const char *fileName, RuleBasedBreakIterator * if (length<=8) { char buf[10]; hexNumber.extract (0, length, buf, sizeof(buf), US_INV); - UChar32 c = (UChar32)strtol(buf, nullptr, 16); + UChar32 c = static_cast(strtol(buf, nullptr, 16)); if (c<=0x10ffff) { testString.append(c); } else { @@ -1423,7 +1423,7 @@ void RBBITest::runUnicodeTestData(const char *fileName, RuleBasedBreakIterator * // Scanner catchall. Something unrecognized appeared on the line. char token[16]; UnicodeString uToken = tokenMatcher.group(0, status); - uToken.extract(0, uToken.length(), token, (uint32_t)sizeof(token)); + uToken.extract(0, uToken.length(), token, static_cast(sizeof(token))); token[sizeof(token)-1] = 0; errln("Syntax error in test data file \'%s\', line %d. Scanning \"%s\"\n", fileName, lineNumber, token); @@ -1636,7 +1636,7 @@ static uint32_t m_seed = 1; static uint32_t m_rand() { m_seed = m_seed * 1103515245 + 12345; - return (uint32_t)(m_seed/65536) % 32768; + return (m_seed / 65536) % 32768; } @@ -3560,8 +3560,8 @@ static int32_t getIntParam(UnicodeString name, UnicodeString ¶ms, int32_t d // The param exists. Convert the string to an int. char valString[100]; int32_t paramLength = m.end(1, status) - m.start(1, status); - if (paramLength >= (int32_t)(sizeof(valString)-1)) { - paramLength = (int32_t)(sizeof(valString)-2); + if (paramLength >= static_cast(sizeof(valString) - 1)) { + paramLength = static_cast(sizeof(valString) - 2); } params.extract(m.start(1, status), paramLength, valString, sizeof(valString)); val = strtol(valString, nullptr, 10); @@ -4188,7 +4188,7 @@ void RBBITest::RunMonkey(BreakIterator *bi, RBBIMonkeyKind &mk, const char *name testText.truncate(0); for (i=0; ielementAt(aClassNum); + UnicodeSet* classSet = static_cast(chClasses->elementAt(aClassNum)); int32_t charIdx = m_rand() % classSet->size(); UChar32 c = classSet->charAt(charIdx); if (c < 0) { // TODO: deal with sets containing strings. @@ -4304,7 +4304,7 @@ void RBBITest::RunMonkey(BreakIterator *bi, RBBIMonkeyKind &mk, const char *name "Out of range value returned by BreakIterator::preceding().\n" "index=%d; prev returned %d; lastBreak=%d" , name, i, breakPos, lastBreakPos); - if (breakPos >= 0 && breakPos < (int32_t)sizeof(precedingBreaks)) { + if (breakPos >= 0 && breakPos < static_cast(sizeof(precedingBreaks))) { precedingBreaks[i] = 2; // Forces an error. } } else { @@ -4468,7 +4468,7 @@ void RBBITest::TestBug5532() { UErrorCode status = U_ZERO_ERROR; UText utext=UTEXT_INITIALIZER; - utext_openUTF8(&utext, (const char *)utf8Data, -1, &status); + utext_openUTF8(&utext, reinterpret_cast(utf8Data), -1, &status); TEST_ASSERT_SUCCESS(status); BreakIterator *bi = BreakIterator::createWordInstance(Locale("th"), status); @@ -4664,7 +4664,7 @@ void RBBITest::TestEmoji() { } CharString hex8; hex8.appendInvariantChars(hex, status); - UChar32 c = (UChar32)strtol(hex8.data(), nullptr, 16); + UChar32 c = static_cast(strtol(hex8.data(), nullptr, 16)); if (c<=0x10ffff) { testString.append(c); } else { @@ -4770,7 +4770,7 @@ void RBBITest::TestTableRedundancies() { std::vector columns; for (int32_t column = 0; column < numCharClasses; column++) { UnicodeString s; - for (int32_t r = 1; r < (int32_t)fwtbl->fNumStates; r++) { + for (int32_t r = 1; r < static_cast(fwtbl->fNumStates); r++) { char *rowBytes = const_cast(fwtbl->fTableData + (fwtbl->fRowLen * r)); if (in8Bits) { RBBIStateTableRow8 *row = reinterpret_cast(rowBytes); @@ -4784,7 +4784,7 @@ void RBBITest::TestTableRedundancies() { } // Ignore column (char class) 0 while checking; it's special, and may have duplicates. for (int c1=1; c1fDictCategoriesStart ? fwtbl->fDictCategoriesStart : numCharClasses; + int limit = c1 < static_cast(fwtbl->fDictCategoriesStart) ? fwtbl->fDictCategoriesStart : numCharClasses; for (int c2 = c1+1; c2 < limit; c2++) { if (columns.at(c1) == columns.at(c2)) { errln("%s:%d Duplicate columns (%d, %d)\n", __FILE__, __LINE__, c1, c2); @@ -4796,7 +4796,7 @@ void RBBITest::TestTableRedundancies() { // Check for duplicate states std::vector rows; - for (int32_t r=0; r < (int32_t)fwtbl->fNumStates; r++) { + for (int32_t r = 0; r < static_cast(fwtbl->fNumStates); r++) { UnicodeString s; char *rowBytes = const_cast(fwtbl->fTableData + (fwtbl->fRowLen * r)); if (in8Bits) { @@ -4818,8 +4818,8 @@ void RBBITest::TestTableRedundancies() { } rows.push_back(s); } - for (int r1=0; r1 < (int32_t)fwtbl->fNumStates; r1++) { - for (int r2 = r1+1; r2 < (int32_t)fwtbl->fNumStates; r2++) { + for (int r1 = 0; r1 < static_cast(fwtbl->fNumStates); r1++) { + for (int r2 = r1 + 1; r2 < static_cast(fwtbl->fNumStates); r2++) { if (rows.at(r1) == rows.at(r2)) { errln("%s:%d Duplicate rows (%d, %d)\n", __FILE__, __LINE__, r1, r2); return; @@ -4942,7 +4942,7 @@ void RBBITest::TestBug13692() { return; } constexpr int32_t LENGTH = 1000000; - UnicodeString longNumber(LENGTH, (UChar32)u'3', LENGTH); + UnicodeString longNumber(LENGTH, static_cast(u'3'), LENGTH); for (int i=0; i<20; i+=2) { longNumber.setCharAt(i, u' '); } @@ -5763,7 +5763,7 @@ class FakeTaiLeBreakEngine : public ExternalBreakEngine { utext_setNativeIndex(text, start); } int32_t current; - while((current = (int32_t)utext_getNativeIndex(text)) < end) { + while ((current = static_cast(utext_getNativeIndex(text))) < end) { UChar32 c = utext_current32(text); // Break after tone marks as a fake break point. if (tones.contains(c)) { @@ -5942,7 +5942,7 @@ void RBBITest::TestBug22585() { // Test a long string with a ; in the end will not cause stack overflow. void RBBITest::TestBug22602() { - UnicodeString rule(25000, (UChar32)'A', 25000-1); + UnicodeString rule(25000, static_cast('A'), 25000 - 1); rule.append(u";"); UParseError pe {}; UErrorCode ec {U_ZERO_ERROR}; @@ -5969,7 +5969,7 @@ void RBBITest::TestBug22584() { // Failure of this test showed as a crash during the break iterator construction. - UnicodeString ruleStr(100000, (UChar32)0, 100000); + UnicodeString ruleStr(100000, static_cast(0), 100000); UParseError pe {}; UErrorCode ec {U_ZERO_ERROR}; diff --git a/icu4c/source/test/intltest/regcoll.cpp b/icu4c/source/test/intltest/regcoll.cpp index 7fdca21a2eed..d401d625bb76 100644 --- a/icu4c/source/test/intltest/regcoll.cpp +++ b/icu4c/source/test/intltest/regcoll.cpp @@ -90,14 +90,14 @@ void CollationRegressionTest::Test4051866(/* char* par */) rules += "&n < o "; rules += "& oe ,o"; - rules += (char16_t)0x3080; + rules += static_cast(0x3080); rules += "& oe ,"; - rules += (char16_t)0x1530; + rules += static_cast(0x1530); rules += " ,O"; rules += "& OE ,O"; - rules += (char16_t)0x3080; + rules += static_cast(0x3080); rules += "& OE ,"; - rules += (char16_t)0x1520; + rules += static_cast(0x1520); rules += "< p ,P"; // Build a collator containing expanding characters @@ -300,9 +300,9 @@ void CollationRegressionTest::Test4060154(/* char* par */) rules += "&f < g, G < h, H < i, I < j, J"; rules += " & H < "; - rules += (char16_t)0x0131; + rules += static_cast(0x0131); rules += ", "; - rules += (char16_t)0x0130; + rules += static_cast(0x0130); rules += ", i, I"; RuleBasedCollator *c = nullptr; @@ -554,8 +554,8 @@ void CollationRegressionTest::Test4078588(/* char *par */) if (result != Collator::LESS) { - errln((UnicodeString)"Compare(a,bb) returned " + (int)result - + (UnicodeString)"; expected -1"); + errln(UnicodeString("Compare(a,bb) returned ") + static_cast(result) + + UnicodeString("; expected -1")); } delete rbc; @@ -1199,10 +1199,10 @@ void CollationRegressionTest::caseFirstCompressionSub(Collator *col, UnicodeStri for (int32_t len = 1; len <= maxLength; len++) { int32_t i = 0; for (; i < len - 1; i++) { - str1[i] = str2[i] = (char16_t)0x61; // 'a' + str1[i] = str2[i] = static_cast(0x61); // 'a' } - str1[i] = (char16_t)0x41; // 'A' - str2[i] = (char16_t)0x61; // 'a' + str1[i] = static_cast(0x41); // 'A' + str2[i] = static_cast(0x61); // 'a' UErrorCode status = U_ZERO_ERROR; col->getCollationKey(str1, len, key1, status); @@ -1214,7 +1214,7 @@ void CollationRegressionTest::caseFirstCompressionSub(Collator *col, UnicodeStri if (U_FAILURE(status)) { errln("Error in caseFirstCompressionSub"); } else if (cmpKey != cmpCol) { - errln((UnicodeString)"Inconsistent comparison(" + opt + errln(UnicodeString("Inconsistent comparison(") + opt + "): str1=" + UnicodeString(str1, len) + ", str2=" + UnicodeString(str2, len) + ", cmpKey=" + cmpKey + ", cmpCol=" + cmpCol); } @@ -1226,7 +1226,7 @@ void CollationRegressionTest::TestTrailingComment() { // Check that the rule parser handles a comment without terminating end-of-line. IcuTestErrorCode errorCode(*this, "TestTrailingComment"); RuleBasedCollator coll(UNICODE_STRING_SIMPLE("&c(0x61)), b(static_cast(0x62)), c(static_cast(0x63)); assertTrue("c(utext_nativeLength(&expectedText)), buf, static_cast(utext_nativeLength(actual))); } utext_close(&expectedText); } @@ -290,7 +290,7 @@ void RegexTest::assertUTextInvariant(const char *expected, UText *actual, const char expectedBuf[201]; utextToPrintable(buf, UPRV_LENGTHOF(buf), actual); utextToPrintable(expectedBuf, UPRV_LENGTHOF(expectedBuf), &expectedText); - errln("%s:%d: assertUTextInvariant: Failure: expected \"%s\" (%d uchars), got \"%s\" (%d chars)", file, line, expectedBuf, (int)utext_nativeLength(&expectedText), buf, (int)utext_nativeLength(actual)); + errln("%s:%d: assertUTextInvariant: Failure: expected \"%s\" (%d uchars), got \"%s\" (%d chars)", file, line, expectedBuf, static_cast(utext_nativeLength(&expectedText)), buf, static_cast(utext_nativeLength(actual))); } utext_close(&expectedText); } @@ -1445,7 +1445,7 @@ void RegexTest::API_Replace() { UnicodeString result = matcher->replaceAll(substitute, status); REGEX_CHECK_STATUS; UnicodeString expected = UnicodeString("--"); - expected.append((UChar32)0x10000); + expected.append(static_cast(0x10000)); expected.append("-- !"); REGEX_ASSERT(result == expected); } @@ -2244,7 +2244,7 @@ void RegexTest::API_Match_UTF8() { // Check that the bump goes over characters outside the BMP OK // "\\U00010001\\U00010002\\U00010003\\U00010004".unescape()...in UTF-8 unsigned char aboveBMP[] = {0xF0, 0x90, 0x80, 0x81, 0xF0, 0x90, 0x80, 0x82, 0xF0, 0x90, 0x80, 0x83, 0xF0, 0x90, 0x80, 0x84, 0x00}; - utext_openUTF8(&s, (char *)aboveBMP, -1, &status); + utext_openUTF8(&s, reinterpret_cast(aboveBMP), -1, &status); m.reset(&s); for (i=0; ; i+=4) { if (m.find() == false) { @@ -2641,7 +2641,7 @@ void RegexTest::API_Replace_UTF8() { supplDigitChars[23] = 0x9D; supplDigitChars[24] = 0x9F; supplDigitChars[25] = 0x8F; - utext_openUTF8(&replText, (char *)supplDigitChars, -1, &status); + utext_openUTF8(&replText, reinterpret_cast(supplDigitChars), -1, &status); result = matcher2->replaceFirst(&replText, nullptr, status); REGEX_CHECK_STATUS; @@ -3333,7 +3333,7 @@ static UBool utextOffsetToNative(UText *utext, int32_t unistrOffset, int32_t& na break; } } - nativeIndex = (int32_t)UTEXT_GETNATIVEINDEX(utext); + nativeIndex = static_cast(UTEXT_GETNATIVEINDEX(utext)); return couldFind; } @@ -3378,26 +3378,26 @@ void RegexTest::regex_find(const UnicodeString &pattern, // Compile the caller's pattern // uint32_t bflags = 0; - if (flags.indexOf((char16_t)0x69) >= 0) { // 'i' flag + if (flags.indexOf(static_cast(0x69)) >= 0) { // 'i' flag bflags |= UREGEX_CASE_INSENSITIVE; } - if (flags.indexOf((char16_t)0x78) >= 0) { // 'x' flag + if (flags.indexOf(static_cast(0x78)) >= 0) { // 'x' flag bflags |= UREGEX_COMMENTS; } - if (flags.indexOf((char16_t)0x73) >= 0) { // 's' flag + if (flags.indexOf(static_cast(0x73)) >= 0) { // 's' flag bflags |= UREGEX_DOTALL; } - if (flags.indexOf((char16_t)0x6d) >= 0) { // 'm' flag + if (flags.indexOf(static_cast(0x6d)) >= 0) { // 'm' flag bflags |= UREGEX_MULTILINE; } - if (flags.indexOf((char16_t)0x65) >= 0) { // 'e' flag + if (flags.indexOf(static_cast(0x65)) >= 0) { // 'e' flag bflags |= UREGEX_ERROR_ON_UNKNOWN_ESCAPES; } - if (flags.indexOf((char16_t)0x44) >= 0) { // 'D' flag + if (flags.indexOf(static_cast(0x44)) >= 0) { // 'D' flag bflags |= UREGEX_UNIX_LINES; } - if (flags.indexOf((char16_t)0x51) >= 0) { // 'Q' flag + if (flags.indexOf(static_cast(0x51)) >= 0) { // 'Q' flag bflags |= UREGEX_LITERAL; } @@ -3411,9 +3411,9 @@ void RegexTest::regex_find(const UnicodeString &pattern, goto cleanupAndReturn; } #endif - if (flags.indexOf((char16_t)0x45) >= 0) { // flags contain 'E' + if (flags.indexOf(static_cast(0x45)) >= 0) { // flags contain 'E' // Expected pattern compilation error. - if (flags.indexOf((char16_t)0x64) >= 0) { // flags contain 'd' + if (flags.indexOf(static_cast(0x64)) >= 0) { // flags contain 'd' logln("Pattern Compile returns \"%s\"", u_errorName(status)); } goto cleanupAndReturn; @@ -3444,9 +3444,9 @@ void RegexTest::regex_find(const UnicodeString &pattern, goto cleanupAndReturn; } #endif - if (flags.indexOf((char16_t)0x45) >= 0) { // flags contain 'E' + if (flags.indexOf(static_cast(0x45)) >= 0) { // flags contain 'E' // Expected pattern compilation error. - if (flags.indexOf((char16_t)0x64) >= 0) { // flags contain 'd' + if (flags.indexOf(static_cast(0x64)) >= 0) { // flags contain 'd' logln("Pattern Compile returns \"%s\" (UTF8)", u_errorName(status)); } goto cleanupAndReturn; @@ -3464,11 +3464,11 @@ void RegexTest::regex_find(const UnicodeString &pattern, status = U_ZERO_ERROR; } - if (flags.indexOf((char16_t)0x64) >= 0) { // 'd' flag + if (flags.indexOf(static_cast(0x64)) >= 0) { // 'd' flag callerPattern->dumpPattern(); } - if (flags.indexOf((char16_t)0x45) >= 0) { // 'E' flag + if (flags.indexOf(static_cast(0x45)) >= 0) { // 'E' flag errln("%s, Line %d: Expected, but did not get, a pattern compilation error.", srcPath, line); goto cleanupAndReturn; } @@ -3479,7 +3479,7 @@ void RegexTest::regex_find(const UnicodeString &pattern, // numFinds = 1; for (i=2; i<=9; i++) { - if (flags.indexOf((char16_t)(0x30 + i)) >= 0) { // digit flag + if (flags.indexOf(static_cast(0x30 + i)) >= 0) { // digit flag if (numFinds != 1) { errln("Line %d: more than one digit flag. Scanning %d.", line, i); goto cleanupAndReturn; @@ -3489,10 +3489,10 @@ void RegexTest::regex_find(const UnicodeString &pattern, } // 'M' flag. Use matches() instead of find() - if (flags.indexOf((char16_t)0x4d) >= 0) { + if (flags.indexOf(static_cast(0x4d)) >= 0) { useMatchesFunc = true; } - if (flags.indexOf((char16_t)0x4c) >= 0) { + if (flags.indexOf(static_cast(0x4c)) >= 0) { useLookingAtFunc = true; } @@ -3548,7 +3548,7 @@ void RegexTest::regex_find(const UnicodeString &pattern, // matcher = callerPattern->matcher(deTaggedInput, status); REGEX_CHECK_STATUS_L(line); - if (flags.indexOf((char16_t)0x74) >= 0) { // 't' trace flag + if (flags.indexOf(static_cast(0x74)) >= 0) { // 't' trace flag matcher->setTrace(true); } @@ -3575,7 +3575,7 @@ void RegexTest::regex_find(const UnicodeString &pattern, // Generate native indices for UTF8 versions of region and capture group info // if (UTF8Matcher != nullptr) { - if (flags.indexOf((char16_t)0x74) >= 0) { // 't' trace flag + if (flags.indexOf(static_cast(0x74)) >= 0) { // 't' trace flag UTF8Matcher->setTrace(true); } if (regionStart>=0) (void) utextOffsetToNative(&inputText, regionStart, regionStartUTF8); @@ -3618,13 +3618,13 @@ void RegexTest::regex_find(const UnicodeString &pattern, REGEX_CHECK_STATUS_L(line); } } - if (flags.indexOf((char16_t)0x61) >= 0) { // 'a' anchoring bounds flag + if (flags.indexOf(static_cast(0x61)) >= 0) { // 'a' anchoring bounds flag matcher->useAnchoringBounds(false); if (UTF8Matcher != nullptr) { UTF8Matcher->useAnchoringBounds(false); } } - if (flags.indexOf((char16_t)0x62) >= 0) { // 'b' transparent bounds flag + if (flags.indexOf(static_cast(0x62)) >= 0) { // 'b' transparent bounds flag matcher->useTransparentBounds(true); if (UTF8Matcher != nullptr) { UTF8Matcher->useTransparentBounds(true); @@ -3690,7 +3690,7 @@ void RegexTest::regex_find(const UnicodeString &pattern, failed = true; } - if (flags.indexOf((char16_t)0x47 /*G*/) >= 0) { + if (flags.indexOf(static_cast(0x47) /*G*/) >= 0) { // Only check for match / no match. Don't check capture groups. goto cleanupAndReturn; } @@ -3738,41 +3738,41 @@ void RegexTest::regex_find(const UnicodeString &pattern, failed = true; } - if ((flags.indexOf((char16_t)0x59) >= 0) && // 'Y' flag: RequireEnd() == false + if ((flags.indexOf(static_cast(0x59)) >= 0) && // 'Y' flag: RequireEnd() == false matcher->requireEnd() == true) { errln("Error at line %d: requireEnd() returned true. Expected false", line); failed = true; - } else if (UTF8Matcher != nullptr && (flags.indexOf((char16_t)0x59) >= 0) && // 'Y' flag: RequireEnd() == false + } else if (UTF8Matcher != nullptr && (flags.indexOf(static_cast(0x59)) >= 0) && // 'Y' flag: RequireEnd() == false UTF8Matcher->requireEnd() == true) { errln("Error at line %d: requireEnd() returned true. Expected false (UTF8)", line); failed = true; } - if ((flags.indexOf((char16_t)0x79) >= 0) && // 'y' flag: RequireEnd() == true + if ((flags.indexOf(static_cast(0x79)) >= 0) && // 'y' flag: RequireEnd() == true matcher->requireEnd() == false) { errln("Error at line %d: requireEnd() returned false. Expected true", line); failed = true; - } else if (UTF8Matcher != nullptr && (flags.indexOf((char16_t)0x79) >= 0) && // 'Y' flag: RequireEnd() == false + } else if (UTF8Matcher != nullptr && (flags.indexOf(static_cast(0x79)) >= 0) && // 'Y' flag: RequireEnd() == false UTF8Matcher->requireEnd() == false) { errln("Error at line %d: requireEnd() returned false. Expected true (UTF8)", line); failed = true; } - if ((flags.indexOf((char16_t)0x5A) >= 0) && // 'Z' flag: hitEnd() == false + if ((flags.indexOf(static_cast(0x5A)) >= 0) && // 'Z' flag: hitEnd() == false matcher->hitEnd() == true) { errln("Error at line %d: hitEnd() returned true. Expected false", line); failed = true; - } else if (UTF8Matcher != nullptr && (flags.indexOf((char16_t)0x5A) >= 0) && // 'Z' flag: hitEnd() == false + } else if (UTF8Matcher != nullptr && (flags.indexOf(static_cast(0x5A)) >= 0) && // 'Z' flag: hitEnd() == false UTF8Matcher->hitEnd() == true) { errln("Error at line %d: hitEnd() returned true. Expected false (UTF8)", line); failed = true; } - if ((flags.indexOf((char16_t)0x7A) >= 0) && // 'z' flag: hitEnd() == true + if ((flags.indexOf(static_cast(0x7A)) >= 0) && // 'z' flag: hitEnd() == true matcher->hitEnd() == false) { errln("Error at line %d: hitEnd() returned false. Expected true", line); failed = true; - } else if (UTF8Matcher != nullptr && (flags.indexOf((char16_t)0x7A) >= 0) && // 'z' flag: hitEnd() == true + } else if (UTF8Matcher != nullptr && (flags.indexOf(static_cast(0x7A)) >= 0) && // 'z' flag: hitEnd() == true UTF8Matcher->hitEnd() == false) { errln("Error at line %d: hitEnd() returned false. Expected true (UTF8)", line); failed = true; @@ -3781,8 +3781,8 @@ void RegexTest::regex_find(const UnicodeString &pattern, cleanupAndReturn: if (failed) { - infoln((UnicodeString)"\""+pattern+(UnicodeString)"\" " - +flags+(UnicodeString)" \""+inputString+(UnicodeString)"\""); + infoln(UnicodeString("\"") + pattern + UnicodeString("\" ") + + flags + UnicodeString(" \"") + inputString + UnicodeString("\"")); // callerPattern->dump(); } delete parseMatcher; @@ -4229,7 +4229,7 @@ void RegexTest::PerlTests() { if (expectedS.compare(resultString) != 0) { err("Line %d: Incorrect perl expression results.", lineNum); - infoln((UnicodeString)"Expected \""+expectedS+(UnicodeString)"\"; got \""+resultString+(UnicodeString)"\""); + infoln(UnicodeString("Expected \"") + expectedS + UnicodeString("\"; got \"") + resultString + UnicodeString("\"")); } delete testMat; @@ -4619,7 +4619,7 @@ void RegexTest::PerlTestsUTF8() { if (expectedS.compare(resultString) != 0) { err("Line %d: Incorrect perl expression results.", lineNum); - infoln((UnicodeString)"Expected \""+expectedS+(UnicodeString)"\"; got \""+resultString+(UnicodeString)"\""); + infoln(UnicodeString("Expected \"") + expectedS + UnicodeString("\"; got \"") + resultString + UnicodeString("\"")); } delete testMat; @@ -5677,7 +5677,7 @@ void RegexTest::TestBug11480() { uregex_setText(re, text.getBuffer(), text.length(), &status); REGEX_CHECK_STATUS; REGEX_ASSERT(uregex_lookingAt(re, 0, &status)); - char16_t buf[10] = {(char16_t)13, (char16_t)13, (char16_t)13, (char16_t)13}; + char16_t buf[10] = {static_cast(13), static_cast(13), static_cast(13), static_cast(13)}; int32_t length = uregex_group(re, 2, buf+1, UPRV_LENGTHOF(buf)-1, &status); REGEX_ASSERT(length == 0); REGEX_ASSERT(buf[0] == 13); diff --git a/icu4c/source/test/intltest/regiontst.cpp b/icu4c/source/test/intltest/regiontst.cpp index 685cc73cba3b..3304838b3361 100644 --- a/icu4c/source/test/intltest/regiontst.cpp +++ b/icu4c/source/test/intltest/regiontst.cpp @@ -760,7 +760,7 @@ void RegionTest::TestGroupingChildren() { if (expectedChildEnd == nullptr) { expectedChildEnd = expectedChildStart + uprv_strlen(expectedChildStart); } - if (uprv_strlen(actualChild) != size_t(expectedChildEnd - expectedChildStart) || uprv_strncmp(actualChild, expectedChildStart, expectedChildEnd - expectedChildStart) != 0) { + if (uprv_strlen(actualChild) != static_cast(expectedChildEnd - expectedChildStart) || uprv_strncmp(actualChild, expectedChildStart, expectedChildEnd - expectedChildStart) != 0) { errln("Mismatch in child list for %s at position %d: expected %s, got %s\n", groupingCode, numExpectedChildren, expectedChildStart, actualChild); } expectedChildStart = (*expectedChildEnd != '\0') ? expectedChildEnd + 1 : expectedChildEnd; diff --git a/icu4c/source/test/intltest/reldatefmttest.cpp b/icu4c/source/test/intltest/reldatefmttest.cpp index d9506f4625a0..cbcdeb6c325a 100644 --- a/icu4c/source/test/intltest/reldatefmttest.cpp +++ b/icu4c/source/test/intltest/reldatefmttest.cpp @@ -1109,10 +1109,10 @@ void RelativeDateTimeFormatterTest::TestGetters() { // copy and assignment. RelativeDateTimeFormatter fmt2(fmt); fmt3 = fmt2; - assertEquals("style", (int32_t)UDAT_STYLE_NARROW, fmt3.getFormatStyle()); + assertEquals("style", static_cast(UDAT_STYLE_NARROW), fmt3.getFormatStyle()); assertEquals( "context", - (int32_t)UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, + static_cast(UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE), fmt3.getCapitalizationContext()); assertSuccess("", status); } diff --git a/icu4c/source/test/intltest/reptest.cpp b/icu4c/source/test/intltest/reptest.cpp index f306b86dc846..415e28eed89e 100644 --- a/icu4c/source/test/intltest/reptest.cpp +++ b/icu4c/source/test/intltest/reptest.cpp @@ -64,7 +64,7 @@ class TestReplaceable : public Replaceable { if (text.charAt(i) == NO_STYLE_MARK) { s.append(NO_STYLE); } else { - s.append((char16_t)(i + 0x0031)); + s.append(static_cast(i + 0x0031)); } } } diff --git a/icu4c/source/test/intltest/restest.cpp b/icu4c/source/test/intltest/restest.cpp index 95af882f23b1..381dfa25627a 100644 --- a/icu4c/source/test/intltest/restest.cpp +++ b/icu4c/source/test/intltest/restest.cpp @@ -95,7 +95,7 @@ itoa(int32_t i, char* buf) char* p = buf; do { - *p++ = (char)('0' + (i % 10)); + *p++ = static_cast('0' + (i % 10)); i /= 10; } while (i); @@ -155,13 +155,13 @@ randul() static UBool initialized = false; if (!initialized) { - srand((unsigned)time(nullptr)); + srand(static_cast(time(nullptr))); initialized = true; } // Assume rand has at least 12 bits of precision uint32_t l = 0; for (uint32_t i=0; i> 4); + reinterpret_cast(&l)[i] = static_cast((rand() & 0x0FF0) >> 4); return l; } @@ -171,7 +171,7 @@ randul() double randd() { - return (double)(randul() / ULONG_MAX); + return static_cast(randul() / ULONG_MAX); } /** @@ -179,7 +179,7 @@ randd() */ int32_t randi(int32_t n) { - return (int32_t)(randd() * n); + return static_cast(randd() * n); } //*************************************************************************************** @@ -285,7 +285,7 @@ ResourceBundleTest::TestConstruction() Locale::setDefault(Locale("en_US"), err); } - ResourceBundle test1((UnicodeString)testdatapath, err); + ResourceBundle test1(UnicodeString(testdatapath), err); ResourceBundle test2(testdatapath, locale, err); //ResourceBundle test1("c:\\icu\\icu\\source\\test\\testdata\\testdata", err); //ResourceBundle test2("c:\\icu\\icu\\source\\test\\testdata\\testdata", locale, err); @@ -498,13 +498,13 @@ ResourceBundleTest::testTag(const char* frag, } else if (status != expected_resource_status) { - record_fail("Error getting " + (UnicodeString)tag); - return (UBool)(failOrig != fail); + record_fail("Error getting " + UnicodeString(tag)); + return static_cast(failOrig != fail); } } - return (UBool)(failOrig != fail); + return static_cast(failOrig != fail); } void diff --git a/icu4c/source/test/intltest/restsnew.cpp b/icu4c/source/test/intltest/restsnew.cpp index d2f2dd5b8548..1bdfa2140781 100644 --- a/icu4c/source/test/intltest/restsnew.cpp +++ b/icu4c/source/test/intltest/restsnew.cpp @@ -126,7 +126,7 @@ itoa(int32_t i, char* buf) char* p = buf; do { - *p++ = (char)('0' + (i % 10)); + *p++ = static_cast('0' + (i % 10)); i /= 10; } while (i); @@ -186,13 +186,13 @@ randul() static UBool initialized = false; if (!initialized) { - srand((unsigned)time(nullptr)); + srand(static_cast(time(nullptr))); initialized = true; } // Assume rand has at least 12 bits of precision uint32_t l = 0; for (uint32_t i=0; i> 4); + reinterpret_cast(&l)[i] = static_cast((rand() & 0x0FF0) >> 4); return l; } @@ -202,7 +202,7 @@ randul() static double randd() { - return (double)(randul() / ULONG_MAX); + return static_cast(randul() / ULONG_MAX); } /** @@ -210,7 +210,7 @@ randd() */ static int32_t randi(int32_t n) { - return (int32_t)(randd() * n); + return static_cast(randd() * n); } //*************************************************************************************** @@ -296,7 +296,7 @@ NewResourceBundleTest::TestConstruction() Locale::setDefault(Locale("en_US"), err); } - ResourceBundle test1((UnicodeString)testdatapath, err); + ResourceBundle test1(UnicodeString(testdatapath), err); ResourceBundle test2(testdatapath, locale, err); UnicodeString result1; @@ -548,7 +548,7 @@ NewResourceBundleTest::TestOtherAPI(){ // defaultresource is for a locale like en_US with an empty resource bundle. // (Before ICU-21028 such a bundle would have contained at least a Version string.) if(defaultresource.getSize() != 0) { - ResourceBundle defaultSub = defaultresource.get((int32_t)0, err); + ResourceBundle defaultSub = defaultresource.get(static_cast(0), err); ResourceBundle defSubCopy(defaultSub); if(strcmp(defSubCopy.getName(), defaultSub.getName()) != 0 || strcmp(defSubCopy.getLocale().getName(), defaultSub.getLocale().getName() ) != 0) { @@ -1051,7 +1051,7 @@ NewResourceBundleTest::testTag(const char* frag, CONFIRM_EQ(count, tag_count); } - return (UBool)(failOrig == fail); + return static_cast(failOrig == fail); } void @@ -1124,7 +1124,7 @@ NewResourceBundleTest::TestNewTypes() { res = theBundle.get("binarytest", status); CONFIRM_UErrorCode(status, U_ZERO_ERROR); CONFIRM_EQ(res.getType(), URES_BINARY); - binResult=(uint8_t*)res.getBinary(len, status); + binResult = const_cast(res.getBinary(len, status)); if(U_SUCCESS(status)){ CONFIRM_UErrorCode(status, U_ZERO_ERROR); CONFIRM_EQ(len, 15); @@ -1137,7 +1137,7 @@ NewResourceBundleTest::TestNewTypes() { res = theBundle.get("importtest",status); CONFIRM_UErrorCode(status, U_ZERO_ERROR); CONFIRM_EQ(res.getType(), URES_BINARY); - binResult=(uint8_t*)res.getBinary(len, status); + binResult = const_cast(res.getBinary(len, status)); if(U_SUCCESS(status)){ CONFIRM_UErrorCode(status, U_ZERO_ERROR); CONFIRM_EQ(len, 15); @@ -1197,7 +1197,7 @@ NewResourceBundleTest::TestNewTypes() { UnicodeString str = theBundle.getStringEx("testescape",status); CONFIRM_UErrorCode(status, U_ZERO_ERROR); if(U_SUCCESS(status)){ - u_charsToUChars(expect,uExpect,(int32_t)uprv_strlen(expect)+1); + u_charsToUChars(expect, uExpect, static_cast(uprv_strlen(expect)) + 1); if(str.compare(uExpect)!=0){ errln("Did not get the expected string for testescape expected. Expected : " +UnicodeString(uExpect )+ " Got: " + str); @@ -1209,7 +1209,7 @@ NewResourceBundleTest::TestNewTypes() { UnicodeString str = theBundle.getStringEx("test_underscores",status); expect ="test message ...."; CONFIRM_UErrorCode(status, U_ZERO_ERROR); - u_charsToUChars(expect,uExpect,(int32_t)uprv_strlen(expect)+1); + u_charsToUChars(expect, uExpect, static_cast(uprv_strlen(expect)) + 1); if(str.compare(uExpect)!=0){ errln("Did not get the expected string for test_underscores.\n"); } diff --git a/icu4c/source/test/intltest/sdtfmtts.cpp b/icu4c/source/test/intltest/sdtfmtts.cpp index eda12f6b9dc4..c7f4340edf32 100644 --- a/icu4c/source/test/intltest/sdtfmtts.cpp +++ b/icu4c/source/test/intltest/sdtfmtts.cpp @@ -147,14 +147,14 @@ void IntlTestSimpleDateFormatAPI::testAPI(/*char *par*/) FieldPosition pos1(FieldPosition::DONT_CARE), pos2(FieldPosition::DONT_CARE); res1 = def.format(d, res1, pos1); - logln( (UnicodeString) "" + d + " formatted to " + res1); + logln(UnicodeString("") + d + " formatted to " + res1); status = U_ZERO_ERROR; res2 = cust1.format(fD, res2, pos2, status); if(U_FAILURE(status)) { errln("ERROR: format(Formattable [Date]) failed"); } - logln((UnicodeString) "" + fD.getDate() + " formatted to " + res2); + logln(UnicodeString("") + fD.getDate() + " formatted to " + res2); // ======= Test parse() @@ -268,7 +268,7 @@ void IntlTestSimpleDateFormatAPI::testAPI(/*char *par*/) object.setLenient(false); ParsePosition pp(0); UDate udDate = object.parse("2007W014", pp); - if ((double)udDate == 0.0) { + if (static_cast(udDate) == 0.0) { errln("ERROR: Parsing failed using 'Y' and 'e'"); } diff --git a/icu4c/source/test/intltest/sfwdchit.cpp b/icu4c/source/test/intltest/sfwdchit.cpp index 2731b6d0e111..418d778afe3a 100644 --- a/icu4c/source/test/intltest/sfwdchit.cpp +++ b/icu4c/source/test/intltest/sfwdchit.cpp @@ -96,7 +96,7 @@ int32_t SimpleFwdCharIterator::hashCode() const { { UHashTok key; key.pointer = fStart; - ((SimpleFwdCharIterator *)this)->fHashCode = uhash_hashUChars(key); + const_cast(this)->fHashCode = uhash_hashUChars(key); } return fHashCode; } diff --git a/icu4c/source/test/intltest/simpleformattertest.cpp b/icu4c/source/test/intltest/simpleformattertest.cpp index 9755568b44d4..fe272b1e4059 100644 --- a/icu4c/source/test/intltest/simpleformattertest.cpp +++ b/icu4c/source/test/intltest/simpleformattertest.cpp @@ -91,10 +91,10 @@ void SimpleFormatterTest::TestNoArguments() { void SimpleFormatterTest::TestSyntaxErrors() { UErrorCode status = U_ZERO_ERROR; SimpleFormatter fmt("{}", status); - assertEquals("syntax error {}", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status); + assertEquals("syntax error {}", static_cast(U_ILLEGAL_ARGUMENT_ERROR), status); status = U_ZERO_ERROR; fmt.applyPattern("{12d", status); - assertEquals("syntax error {12d", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status); + assertEquals("syntax error {12d", static_cast(U_ILLEGAL_ARGUMENT_ERROR), status); } void SimpleFormatterTest::TestOneArgument() { diff --git a/icu4c/source/test/intltest/srchtest.cpp b/icu4c/source/test/intltest/srchtest.cpp index d8abe9dc737b..fddf7fdd5e39 100644 --- a/icu4c/source/test/intltest/srchtest.cpp +++ b/icu4c/source/test/intltest/srchtest.cpp @@ -226,7 +226,7 @@ char * StringSearchTest::toCharString(const UnicodeString &text) for (; count < length; count ++) { char16_t ch = text[count]; if (ch >= 0x20 && ch <= 0x7e) { - result[index ++] = (char)ch; + result[index++] = static_cast(ch); } else { snprintf(result+index, sizeof(result)-index, "\\u%04x", ch); @@ -2210,7 +2210,7 @@ void StringSearchTest::TestContractionCanonical() void StringSearchTest::TestUClassID() { - char id = *((char *)StringSearch::getStaticClassID()); + char id = *static_cast(StringSearch::getStaticClassID()); if (id != 0) { errln("Static class id for StringSearch should be 0"); } @@ -2219,7 +2219,7 @@ void StringSearchTest::TestUClassID() UnicodeString pattern("pattern"); StringSearch *strsrch = new StringSearch(pattern, text, m_en_us_, nullptr, status); - id = *((char *)strsrch->getDynamicClassID()); + id = *static_cast(strsrch->getDynamicClassID()); if (id != 0) { errln("Dynamic class id for StringSearch should be 0"); } diff --git a/icu4c/source/test/intltest/ssearch.cpp b/icu4c/source/test/intltest/ssearch.cpp index d951f3d52dbf..a13df7fcd76f 100644 --- a/icu4c/source/test/intltest/ssearch.cpp +++ b/icu4c/source/test/intltest/ssearch.cpp @@ -945,7 +945,7 @@ const char *cPattern = "maketh houndes ete hem"; // Find the match position usgin strstr const char *pm = strstr(longishText, cPattern); TEST_ASSERT_M(pm!=nullptr, "No pattern match with strstr"); - int32_t refMatchPos = (int32_t)(pm - longishText); + int32_t refMatchPos = static_cast(pm - longishText); int32_t icuMatchPos; int32_t icuMatchEnd; usearch_search(uss.getAlias(), 0, &icuMatchPos, &icuMatchEnd, &status); @@ -988,7 +988,7 @@ static uint32_t m_seed = 1; static uint32_t m_rand() { m_seed = m_seed * 1103515245 + 12345; - return (uint32_t)(m_seed/65536) % 32768; + return (m_seed / 65536) % 32768; } class Monkey @@ -1142,7 +1142,7 @@ UnicodeString &StringSetMonkey::generateAlternative(const UnicodeString &testCas matches = ceList.matchesAt(offset, ceList2); if (! matches) { - collData->freeCEList((CEList *) ceList2); + collData->freeCEList(const_cast(ceList2)); } } while (! matches); @@ -1289,8 +1289,8 @@ static int32_t getIntParam(UnicodeString name, UnicodeString ¶ms, int32_t d char valString[100]; int32_t paramLength = m.end(1, status) - m.start(1, status); - if (paramLength >= (int32_t)(sizeof(valString)-1)) { - paramLength = (int32_t)(sizeof(valString)-2); + if (paramLength >= static_cast(sizeof(valString) - 1)) { + paramLength = static_cast(sizeof(valString) - 2); } params.extract(m.start(1, status), paramLength, valString, sizeof(valString)); diff --git a/icu4c/source/test/intltest/strcase.cpp b/icu4c/source/test/intltest/strcase.cpp index 31d2be275077..70cb8a399674 100644 --- a/icu4c/source/test/intltest/strcase.cpp +++ b/icu4c/source/test/intltest/strcase.cpp @@ -149,7 +149,7 @@ StringCaseTest::TestCaseConversion() UnicodeString expectedResult; UnicodeString test3; - test3 += (UChar32)0x0130; + test3 += static_cast(0x0130); test3 += "STANBUL, NOT CONSTANTINOPLE!"; UnicodeString test4(test3); @@ -165,7 +165,7 @@ StringCaseTest::TestCaseConversion() errln("2. toLower failed: expected \"" + expectedResult + "\", got \"" + test4 + "\"."); test3 = "topkap"; - test3 += (UChar32)0x0131; + test3 += static_cast(0x0131); test3 += " palace, istanbul"; test4 = test3; @@ -483,32 +483,32 @@ StringCaseTest::TestCasingImpl(const UnicodeString &input, } #endif - u_strToUTF8(utf8In, (int32_t)sizeof(utf8In), &utf8InLength, input.getBuffer(), input.length(), errorCode); + u_strToUTF8(utf8In, static_cast(sizeof(utf8In)), &utf8InLength, input.getBuffer(), input.length(), errorCode); switch(whichCase) { case TEST_LOWER: name="ucasemap_utf8ToLower"; utf8OutLength=ucasemap_utf8ToLower(csm.getAlias(), - utf8Out, (int32_t)sizeof(utf8Out), + utf8Out, static_cast(sizeof(utf8Out)), utf8In, utf8InLength, errorCode); break; case TEST_UPPER: name="ucasemap_utf8ToUpper"; utf8OutLength=ucasemap_utf8ToUpper(csm.getAlias(), - utf8Out, (int32_t)sizeof(utf8Out), + utf8Out, static_cast(sizeof(utf8Out)), utf8In, utf8InLength, errorCode); break; #if !UCONFIG_NO_BREAK_ITERATION case TEST_TITLE: name="ucasemap_utf8ToTitle"; utf8OutLength=ucasemap_utf8ToTitle(csm.getAlias(), - utf8Out, (int32_t)sizeof(utf8Out), + utf8Out, static_cast(sizeof(utf8Out)), utf8In, utf8InLength, errorCode); break; #endif case TEST_FOLD: name="ucasemap_utf8FoldCase"; utf8OutLength=ucasemap_utf8FoldCase(csm.getAlias(), - utf8Out, (int32_t)sizeof(utf8Out), + utf8Out, static_cast(sizeof(utf8Out)), utf8In, utf8InLength, errorCode); break; default: @@ -566,7 +566,7 @@ StringCaseTest::TestCasing() { if(whichCase==TEST_TITLE) { type = myCase->getInt("Type", status); if(type>=0) { - iter.adoptInstead(ubrk_open((UBreakIteratorType)type, cLocaleID, nullptr, 0, &status)); + iter.adoptInstead(ubrk_open(static_cast(type), cLocaleID, nullptr, 0, &status)); } else if(type==-2) { // Open a trivial break iterator that only delivers { 0, length } // or even just { 0 } as boundaries. @@ -579,13 +579,13 @@ StringCaseTest::TestCasing() { options = 0; if(whichCase==TEST_TITLE || whichCase==TEST_FOLD) { optionsString = myCase->getString("Options", status); - if(optionsString.indexOf((char16_t)0x54)>=0) { // T + if (optionsString.indexOf(static_cast(0x54)) >= 0) { // T options|=U_FOLD_CASE_EXCLUDE_SPECIAL_I; } - if(optionsString.indexOf((char16_t)0x4c)>=0) { // L + if (optionsString.indexOf(static_cast(0x4c)) >= 0) { // L options|=U_TITLECASE_NO_LOWERCASE; } - if(optionsString.indexOf((char16_t)0x41)>=0) { // A + if (optionsString.indexOf(static_cast(0x41)) >= 0) { // A options|=U_TITLECASE_NO_BREAK_ADJUSTMENT; } } @@ -786,14 +786,14 @@ StringCaseTest::TestFullCaseFoldingIterator() { ++count; // Check that the full Case_Folding has more than 1 code point. if(!full.hasMoreChar32Than(0, 0x7fffffff, 1)) { - errln("error: FullCaseFoldingIterator.next()=U+%04lX full Case_Folding has at most 1 code point", (long)c); + errln("error: FullCaseFoldingIterator.next()=U+%04lX full Case_Folding has at most 1 code point", static_cast(c)); continue; } // Check that full == Case_Folding(c). UnicodeString cf(c); cf.foldCase(); if(full!=cf) { - errln("error: FullCaseFoldingIterator.next()=U+%04lX full Case_Folding != cf(c)", (long)c); + errln("error: FullCaseFoldingIterator.next()=U+%04lX full Case_Folding != cf(c)", static_cast(c)); continue; } // Spot-check a couple of specific cases. @@ -805,7 +805,7 @@ StringCaseTest::TestFullCaseFoldingIterator() { errln("error: FullCaseFoldingIterator did not yield exactly the expected specific cases"); } if(count<70) { - errln("error: FullCaseFoldingIterator yielded only %d (cp, full) pairs", (int)count); + errln("error: FullCaseFoldingIterator yielded only %d (cp, full) pairs", static_cast(count)); } } @@ -894,7 +894,7 @@ void StringCaseTest::assertGreekUpperNormalized(const UnicodeString &s16, } else { expectedErrorCode = U_ZERO_ERROR; // Casts to int32_t to avoid matching UBool. - assertEquals(msg + cap + " NUL", (int32_t)0, (int32_t)dest8b[length]); + assertEquals(msg + cap + " NUL", static_cast(0), static_cast(dest8b[length])); } assertEquals(msg + cap + " errorCode", expectedErrorCode, errorCode); if (cap >= expected8Length) { @@ -968,7 +968,7 @@ StringCaseTest::TestLongUpper() { // U+0390 maps to 0399 0308 0301 so that the result is three times as long // and overflows an int32_t. int32_t length = 0x40000004; // more than 1G UChars - UnicodeString s(length, (UChar32)0x390, length); + UnicodeString s(length, static_cast(0x390), length); UnicodeString result; char16_t *dest = result.getBuffer(length + 1); if (s.isBogus() || dest == nullptr) { @@ -981,7 +981,7 @@ StringCaseTest::TestLongUpper() { result.releaseBuffer(destLength); if (errorCode.reset() != U_INDEX_OUTOFBOUNDS_ERROR) { errln("expected U_INDEX_OUTOFBOUNDS_ERROR, got %s (destLength is undefined, got %ld)", - errorCode.errorName(), (long)destLength); + errorCode.errorName(), static_cast(destLength)); } } @@ -993,14 +993,14 @@ void StringCaseTest::TestMalformedUTF8() { errln("ucasemap_open(English) failed - %s", errorCode.errorName()); return; } - char src[1] = { (char)0x85 }; // malformed UTF-8 + char src[1] = {static_cast(0x85)}; // malformed UTF-8 char dest[3] = { 0, 0, 0 }; int32_t destLength; #if !UCONFIG_NO_BREAK_ITERATION destLength = ucasemap_utf8ToTitle(csm.getAlias(), dest, 3, src, 1, errorCode); if (errorCode.isFailure() || destLength != 1 || dest[0] != src[0]) { errln("ucasemap_utf8ToTitle(\\x85) failed: %s destLength=%d dest[0]=0x%02x", - errorCode.errorName(), (int)destLength, dest[0]); + errorCode.errorName(), static_cast(destLength), dest[0]); } #endif @@ -1009,7 +1009,7 @@ void StringCaseTest::TestMalformedUTF8() { destLength = ucasemap_utf8ToLower(csm.getAlias(), dest, 3, src, 1, errorCode); if (errorCode.isFailure() || destLength != 1 || dest[0] != src[0]) { errln("ucasemap_utf8ToLower(\\x85) failed: %s destLength=%d dest[0]=0x%02x", - errorCode.errorName(), (int)destLength, dest[0]); + errorCode.errorName(), static_cast(destLength), dest[0]); } errorCode.reset(); @@ -1017,7 +1017,7 @@ void StringCaseTest::TestMalformedUTF8() { destLength = ucasemap_utf8ToUpper(csm.getAlias(), dest, 3, src, 1, errorCode); if (errorCode.isFailure() || destLength != 1 || dest[0] != src[0]) { errln("ucasemap_utf8ToUpper(\\x85) failed: %s destLength=%d dest[0]=0x%02x", - errorCode.errorName(), (int)destLength, dest[0]); + errorCode.errorName(), static_cast(destLength), dest[0]); } errorCode.reset(); @@ -1025,7 +1025,7 @@ void StringCaseTest::TestMalformedUTF8() { destLength = ucasemap_utf8FoldCase(csm.getAlias(), dest, 3, src, 1, errorCode); if (errorCode.isFailure() || destLength != 1 || dest[0] != src[0]) { errln("ucasemap_utf8FoldCase(\\x85) failed: %s destLength=%d dest[0]=0x%02x", - errorCode.errorName(), (int)destLength, dest[0]); + errorCode.errorName(), static_cast(destLength), dest[0]); } } @@ -1055,7 +1055,7 @@ void StringCaseTest::TestBufferOverflow() { data.toUTF8String(data_utf8); #if !UCONFIG_NO_BREAK_ITERATION result = ucasemap_utf8ToTitle(csm.getAlias(), nullptr, 0, data_utf8.c_str(), static_cast(data_utf8.length()), errorCode); - if (errorCode.get() != U_BUFFER_OVERFLOW_ERROR || result != (int32_t)data_utf8.length()) { + if (errorCode.get() != U_BUFFER_OVERFLOW_ERROR || result != static_cast(data_utf8.length())) { errln("%s:%d ucasemap_toTitle(\"hello world\") failed: " "expected (U_BUFFER_OVERFLOW_ERROR, %d), got (%s, %d)", __FILE__, __LINE__, data_utf8.length(), errorCode.errorName(), result); diff --git a/icu4c/source/test/intltest/strtest.cpp b/icu4c/source/test/intltest/strtest.cpp index 9b28e81076b5..3654b5afc270 100644 --- a/icu4c/source/test/intltest/strtest.cpp +++ b/icu4c/source/test/intltest/strtest.cpp @@ -170,12 +170,12 @@ StringTest::TestUpperOrdinal() { if (0 <= expected && expected <= 25) { if (actual != expected) { errln("uprv_upperOrdinal('%c')=%d != expected %d", - ic, (int)actual, (int)expected); + ic, static_cast(actual), static_cast(expected)); } } else { if (0 <= actual && actual <= 25) { errln("uprv_upperOrdinal('%c')=%d should have been outside 0..25", - ic, (int)actual); + ic, static_cast(actual)); } } if (ic == 0) { break; } @@ -192,12 +192,12 @@ StringTest::TestLowerOrdinal() { if (0 <= expected && expected <= 25) { if (actual != expected) { errln("uprv_lowerOrdinal('%c')=%d != expected %d", - ic, (int)actual, (int)expected); + ic, static_cast(actual), static_cast(expected)); } } else { if (0 <= actual && actual <= 25) { errln("uprv_lowerOrdinal('%c')=%d should have been outside 0..25", - ic, (int)actual); + ic, static_cast(actual)); } } if (ic == 0) { break; } @@ -596,7 +596,7 @@ StringTest::TestByteSink() { } char scratch[20]; int32_t capacity = -1; - char *dest = sink.GetAppendBuffer(0, 50, scratch, (int32_t)sizeof(scratch), &capacity); + char* dest = sink.GetAppendBuffer(0, 50, scratch, static_cast(sizeof(scratch)), &capacity); if(dest != nullptr || capacity != 0) { errln("ByteSink.GetAppendBuffer(min_capacity<1) did not properly return nullptr[0]"); return; @@ -606,8 +606,8 @@ StringTest::TestByteSink() { errln("ByteSink.GetAppendBuffer(scratch_capacity(sizeof(scratch)), &capacity); + if (dest != scratch || capacity != static_cast(sizeof(scratch))) { errln("ByteSink.GetAppendBuffer() did not properly return the scratch buffer"); } } @@ -616,7 +616,7 @@ void StringTest::TestCheckedArrayByteSink() { char buffer[20]; // < 26 for the test code to work buffer[3] = '!'; - CheckedArrayByteSink sink(buffer, (int32_t)sizeof(buffer)); + CheckedArrayByteSink sink(buffer, static_cast(sizeof(buffer))); sink.Append("abc", 3); if(!(sink.NumberOfBytesAppended() == 3 && sink.NumberOfBytesWritten() == 3 && 0 == memcmp("abc", buffer, 3) && buffer[3] == '!') && @@ -627,7 +627,7 @@ StringTest::TestCheckedArrayByteSink() { } char scratch[10]; int32_t capacity = -1; - char *dest = sink.GetAppendBuffer(0, 50, scratch, (int32_t)sizeof(scratch), &capacity); + char* dest = sink.GetAppendBuffer(0, 50, scratch, static_cast(sizeof(scratch)), &capacity); if(dest != nullptr || capacity != 0) { errln("CheckedArrayByteSink.GetAppendBuffer(min_capacity<1) did not properly return nullptr[0]"); return; @@ -637,8 +637,8 @@ StringTest::TestCheckedArrayByteSink() { errln("CheckedArrayByteSink.GetAppendBuffer(scratch_capacity(sizeof(scratch)), &capacity); + if (dest != buffer + 3 || capacity != static_cast(sizeof(buffer)) - 3) { errln("CheckedArrayByteSink.GetAppendBuffer() did not properly return its own buffer"); return; } @@ -651,15 +651,15 @@ StringTest::TestCheckedArrayByteSink() { errln("CheckedArrayByteSink did not Append(its own buffer) as expected"); return; } - dest = sink.GetAppendBuffer(10, 50, scratch, (int32_t)sizeof(scratch), &capacity); - if(dest != scratch || capacity != (int32_t)sizeof(scratch)) { + dest = sink.GetAppendBuffer(10, 50, scratch, static_cast(sizeof(scratch)), &capacity); + if (dest != scratch || capacity != static_cast(sizeof(scratch))) { errln("CheckedArrayByteSink.GetAppendBuffer() did not properly return the scratch buffer"); } memcpy(dest, "nopqrstuvw", 10); sink.Append(dest, 10); if(!(sink.NumberOfBytesAppended() == 23 && - sink.NumberOfBytesWritten() == (int32_t)sizeof(buffer) && - 0 == memcmp("abcdefghijklmnopqrstuvwxyz", buffer, (int32_t)sizeof(buffer)) && + sink.NumberOfBytesWritten() == static_cast(sizeof(buffer)) && + 0 == memcmp("abcdefghijklmnopqrstuvwxyz", buffer, static_cast(sizeof(buffer))) && sink.Overflowed()) ) { errln("CheckedArrayByteSink did not Append(scratch buffer) as expected"); @@ -667,7 +667,7 @@ StringTest::TestCheckedArrayByteSink() { } sink.Reset().Append("123", 3); if(!(sink.NumberOfBytesAppended() == 3 && sink.NumberOfBytesWritten() == 3 && - 0 == memcmp("123defghijklmnopqrstuvwxyz", buffer, (int32_t)sizeof(buffer)) && + 0 == memcmp("123defghijklmnopqrstuvwxyz", buffer, static_cast(sizeof(buffer))) && !sink.Overflowed()) ) { errln("CheckedArrayByteSink did not Reset().Append() as expected"); @@ -688,7 +688,7 @@ StringTest::TestStringByteSink() { StringByteSink sink2(&result, 20); if(result.capacity() < (result.length() + 20)) { errln("StringByteSink should have 20 append capacity, has only %d", - (int)(result.capacity() - result.length())); + static_cast(result.capacity() - result.length())); } sink.Append("ghi", 3); if(result != "abcdefghi") { @@ -730,13 +730,13 @@ StringTest::TestCharString() { static const char longStr[] = "This is a long string that is meant to cause reallocation of the internal buffer of CharString."; CharString chStr(longStr, errorCode); - if (0 != strcmp(longStr, chStr.data()) || (int32_t)strlen(longStr) != chStr.length()) { + if (0 != strcmp(longStr, chStr.data()) || static_cast(strlen(longStr)) != chStr.length()) { errln("CharString(longStr) failed."); } CharString test("Test", errorCode); CharString copy(test,errorCode); copy.copyFrom(chStr, errorCode); - if (0 != strcmp(longStr, copy.data()) || (int32_t)strlen(longStr) != copy.length()) { + if (0 != strcmp(longStr, copy.data()) || static_cast(strlen(longStr)) != copy.length()) { errln("CharString.copyFrom() failed."); } StringPiece sp(chStr.toStringPiece()); @@ -746,7 +746,7 @@ StringTest::TestCharString() { strcat(expected, longStr+4); strcat(expected, longStr); strcat(expected, longStr+4); - if (0 != strcmp(expected, chStr.data()) || (int32_t)strlen(expected) != chStr.length()) { + if (0 != strcmp(expected, chStr.data()) || static_cast(strlen(expected)) != chStr.length()) { errln("CharString(longStr).append(substring of self).append(self) failed."); } chStr.clear().append("abc", errorCode).append("defghij", 3, errorCode); @@ -758,7 +758,7 @@ StringTest::TestCharString() { errorCode); strcpy(expected, "abcdef"); strcat(expected, longStr); - if (0 != strcmp(expected, chStr.data()) || (int32_t)strlen(expected) != chStr.length()) { + if (0 != strcmp(expected, chStr.data()) || static_cast(strlen(expected)) != chStr.length()) { errln("CharString.appendInvariantChars(longStr) failed."); } int32_t appendCapacity = 0; @@ -770,7 +770,7 @@ StringTest::TestCharString() { chStr.append(buffer, 5, errorCode); chStr.truncate(chStr.length()-3); strcat(expected, "**"); - if (0 != strcmp(expected, chStr.data()) || (int32_t)strlen(expected) != chStr.length()) { + if (0 != strcmp(expected, chStr.data()) || static_cast(strlen(expected)) != chStr.length()) { errln("CharString.getAppendBuffer().append(**) failed."); } @@ -871,6 +871,6 @@ void StringTest::Testctou() { const char *cs = "Fa\\u0127mu"; UnicodeString u = ctou(cs); - assertEquals("Testing unescape@0", (int32_t)0x0046, u.charAt(0)); - assertEquals("Testing unescape@2", (int32_t)295, u.charAt(2)); + assertEquals("Testing unescape@0", static_cast(0x0046), u.charAt(0)); + assertEquals("Testing unescape@2", static_cast(295), u.charAt(2)); } diff --git a/icu4c/source/test/intltest/svccoll.cpp b/icu4c/source/test/intltest/svccoll.cpp index 61a041362179..6bb64622991e 100644 --- a/icu4c/source/test/intltest/svccoll.cpp +++ b/icu4c/source/test/intltest/svccoll.cpp @@ -275,7 +275,7 @@ class TestFactory : public CollatorFactory { { CollatorInfo** p; for (p = info; *p; ++p) {} - count = (int32_t)(p - info); + count = static_cast(p - info); } ~TestFactory() { @@ -505,7 +505,7 @@ int32_t CollationServiceTest::checkStringEnumeration(const char* msg, UnicodeString exp(expected[j], (char*)nullptr); if (*s == exp) { seenMask |= bit; - logln((UnicodeString)"Ok: \"" + exp + "\" seen"); + logln(UnicodeString("Ok: \"") + exp + "\" seen"); } } } @@ -532,7 +532,7 @@ int32_t CollationServiceTest::checkStringEnumeration(const char* msg, if (((1<setFormat( 2, *filenumform ); - Formattable testArgs[] = {(int32_t)0, "Disk_A", (int32_t)0}; + Formattable testArgs[] = {static_cast(0), "Disk_A", static_cast(0)}; UnicodeString str; UnicodeString res1, res2; pattform->toPattern( res1 ); @@ -207,7 +207,7 @@ TestChoiceFormat::TestComplexExample() for (i = start; i < 4; ++i) { str = ""; status = U_ZERO_ERROR; - testArgs[0] = Formattable((int32_t)i); + testArgs[0] = Formattable(i); testArgs[2] = testArgs[0]; res2 = pattform->format(testArgs, 3, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format" )) { @@ -273,7 +273,7 @@ TestChoiceFormat::TestComplexExample() for (i = 0; i < 4; ++i) { str = ""; status = U_ZERO_ERROR; - testArgs[0] = Formattable((int32_t)i); + testArgs[0] = Formattable(i); testArgs[2] = testArgs[0]; res2 = pattform->format(testArgs, 3, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format 2" )) { @@ -389,7 +389,7 @@ TestChoiceFormat::TestComplexExample() it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (int32_t, ...) result!"); - Formattable ft( (int32_t)3 ); + Formattable ft(static_cast(3)); str = ""; fpos = 0; status = U_ZERO_ERROR; @@ -403,7 +403,7 @@ TestChoiceFormat::TestComplexExample() it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (Formattable, ...) result!"); - Formattable fta[] = { (int32_t)3 }; + Formattable fta[] = {static_cast(3)}; str = ""; fpos = 0; status = U_ZERO_ERROR; @@ -548,9 +548,9 @@ void TestChoiceFormat::TestClosures() { double x = ix / 10.0; // -0.5 to 5.5 step +0.5 FMT[pass]->format(x, str); if (str == exp[j]) { - logln((UnicodeString)"Ok: " + x + " => " + str); + logln(UnicodeString("Ok: ") + x + " => " + str); } else { - errln((UnicodeString)"FAIL: " + x + " => " + str + + errln(UnicodeString("FAIL: ") + x + " => " + str + ", expected " + exp[j]); } str.truncate(0); @@ -571,20 +571,20 @@ void TestChoiceFormat::_testPattern(const char* pattern, ChoiceFormat fmt(pattern, ec); if (!isValid) { if (U_FAILURE(ec)) { - logln((UnicodeString)"Ok: " + pattern + " failed"); + logln(UnicodeString("Ok: ") + pattern + " failed"); } else { - logln((UnicodeString)"FAIL: " + pattern + " accepted"); + logln(UnicodeString("FAIL: ") + pattern + " accepted"); } return; } if (U_FAILURE(ec)) { - errln((UnicodeString)"FAIL: ChoiceFormat(" + pattern + ") failed"); + errln(UnicodeString("FAIL: ChoiceFormat(") + pattern + ") failed"); return; } else { - logln((UnicodeString)"Ok: Pattern: " + pattern); + logln(UnicodeString("Ok: Pattern: ") + pattern); } UnicodeString out; - logln((UnicodeString)" toPattern: " + fmt.toPattern(out)); + logln(UnicodeString(" toPattern: ") + fmt.toPattern(out)); double v[] = {v1, v2, v3}; const char* str[] = {str1, str2, str3}; @@ -592,9 +592,9 @@ void TestChoiceFormat::_testPattern(const char* pattern, out.truncate(0); fmt.format(v[i], out); if (out == str[i]) { - logln((UnicodeString)"Ok: " + v[i] + " => " + out); + logln(UnicodeString("Ok: ") + v[i] + " => " + out); } else { - errln((UnicodeString)"FAIL: " + v[i] + " => " + out + + errln(UnicodeString("FAIL: ") + v[i] + " => " + out + ", expected " + str[i]); } } diff --git a/icu4c/source/test/intltest/testidn.cpp b/icu4c/source/test/intltest/testidn.cpp index 56854db106ab..be8981d722e3 100644 --- a/icu4c/source/test/intltest/testidn.cpp +++ b/icu4c/source/test/intltest/testidn.cpp @@ -88,7 +88,7 @@ testData(TestIDNA& test) { return errorCode; } - char* filename = (char*) malloc(strlen(IntlTest::pathToDataDirectory())*1024); + char* filename = static_cast(malloc(strlen(IntlTest::pathToDataDirectory()) * 1024)); //TODO get the srcDir dynamically const char *srcDir=IntlTest::pathToDataDirectory(); @@ -233,7 +233,7 @@ getValues(uint32_t result, int32_t& value, UBool& isIndex){ isIndex =false; value = 0; }else if(result >= _SPREP_TYPE_THRESHOLD){ - type = (UStringPrepType) (result - _SPREP_TYPE_THRESHOLD); + type = static_cast(result - _SPREP_TYPE_THRESHOLD); isIndex =false; value = 0; }else{ @@ -246,7 +246,7 @@ getValues(uint32_t result, int32_t& value, UBool& isIndex){ }else{ isIndex = false; - value = (int16_t)result; + value = static_cast(result); value = (value >> 2); } @@ -381,7 +381,7 @@ compareMapping(uint32_t codepoint, uint32_t* mapping,int32_t mapLength, if(isIndex){ for(int8_t i =0; i< mapLength; i++){ if(mapping[i] <= 0xFFFF){ - if(mappingData[index+i] != (uint16_t)mapping[i]){ + if (mappingData[index + i] != static_cast(mapping[i])) { pTestIDNA->errln("Did not get the expected result. Expected: 0x%04X Got: 0x%04X \n", mapping[i], mappingData[index+i]); } }else{ @@ -394,7 +394,7 @@ compareMapping(uint32_t codepoint, uint32_t* mapping,int32_t mapLength, } } }else{ - if(retType!=USPREP_DELETE && (codepoint-delta) != (uint16_t)mapping[0]){ + if (retType != USPREP_DELETE && (codepoint - delta) != static_cast(mapping[0])) { pTestIDNA->errln("Did not get the expected result. Expected: 0x%04X Got: 0x%04X \n", mapping[0],(codepoint-delta)); } } diff --git a/icu4c/source/test/intltest/testidna.cpp b/icu4c/source/test/intltest/testidna.cpp index 77a8c145f423..66d7cf35d310 100644 --- a/icu4c/source/test/intltest/testidna.cpp +++ b/icu4c/source/test/intltest/testidna.cpp @@ -430,7 +430,7 @@ void TestIDNA::debug(const char16_t* src, int32_t srcLength, int32_t options){ transOutLength = trans->process(src,srcLength,transOut, 0, prepOptions>0, &parseError, transStatus); if( transStatus == U_BUFFER_OVERFLOW_ERROR){ transStatus = U_ZERO_ERROR; - transOut = (char16_t*) malloc(U_SIZEOF_UCHAR * transOutLength); + transOut = static_cast(malloc(U_SIZEOF_UCHAR * transOutLength)); transOutLength = trans->process(src,srcLength,transOut, transOutLength, prepOptions>0, &parseError, transStatus); } @@ -438,7 +438,7 @@ void TestIDNA::debug(const char16_t* src, int32_t srcLength, int32_t options){ if( prepStatus == U_BUFFER_OVERFLOW_ERROR){ prepStatus = U_ZERO_ERROR; - prepOut = (char16_t*) malloc(U_SIZEOF_UCHAR * prepOutLength); + prepOut = static_cast(malloc(U_SIZEOF_UCHAR * prepOutLength)); prepOutLength = usprep_prepare(prep.getAlias(), src, srcLength, prepOut, prepOutLength, prepOptions, &parseError, &prepStatus); } @@ -467,7 +467,7 @@ void TestIDNA::testAPI(const char16_t* src, const char16_t* expected, const char if(src != nullptr){ tSrcLen = u_strlen(src); - tSrc =(char16_t*) malloc( U_SIZEOF_UCHAR * tSrcLen ); + tSrc = static_cast(malloc(U_SIZEOF_UCHAR * tSrcLen)); memcpy(tSrc,src,tSrcLen * U_SIZEOF_UCHAR); } @@ -703,7 +703,7 @@ void TestIDNA::testToASCII(const char* testName, TestFunc func){ char16_t buf[MAX_DEST_SIZE]; for(i=0;i< UPRV_LENGTHOF(unicodeIn); i++){ - u_charsToUChars(asciiIn[i],buf, (int32_t)(strlen(asciiIn[i])+1)); + u_charsToUChars(asciiIn[i], buf, static_cast(strlen(asciiIn[i]) + 1)); testAPI(unicodeIn[i], buf,testName, false,U_ZERO_ERROR, true, true, func); } @@ -715,7 +715,7 @@ void TestIDNA::testToUnicode(const char* testName, TestFunc func){ char16_t buf[MAX_DEST_SIZE]; for(i=0;i< UPRV_LENGTHOF(asciiIn); i++){ - u_charsToUChars(asciiIn[i],buf, (int32_t)(strlen(asciiIn[i])+1)); + u_charsToUChars(asciiIn[i], buf, static_cast(strlen(asciiIn[i]) + 1)); testAPI(buf,unicodeIn[i],testName,false,U_ZERO_ERROR, true, true, func); } } @@ -729,7 +729,7 @@ void TestIDNA::testIDNToUnicode(const char* testName, TestFunc func){ int32_t bufLen = 0; UParseError parseError; for(i=0;i< UPRV_LENGTHOF(domainNames); i++){ - bufLen = (int32_t)strlen(domainNames[i]); + bufLen = static_cast(strlen(domainNames[i])); bufLen = u_unescape(domainNames[i],buf, bufLen+1); func(buf,bufLen,expected,MAX_DEST_SIZE, UIDNA_ALLOW_UNASSIGNED, &parseError,&status); if(U_FAILURE(status)){ @@ -755,7 +755,7 @@ void TestIDNA::testIDNToASCII(const char* testName, TestFunc func){ int32_t bufLen = 0; UParseError parseError; for(i=0;i< UPRV_LENGTHOF(domainNames); i++){ - bufLen = (int32_t)strlen(domainNames[i]); + bufLen = static_cast(strlen(domainNames[i])); bufLen = u_unescape(domainNames[i],buf, bufLen+1); func(buf,bufLen,expected,MAX_DEST_SIZE, UIDNA_ALLOW_UNASSIGNED, &parseError,&status); if(U_FAILURE(status)){ @@ -785,23 +785,23 @@ void TestIDNA::testCompare(const char* testName, CompareFunc func){ uni0.append(unicodeIn[0]); uni0.append(com); - uni0.append((char16_t)0x0000); + uni0.append(static_cast(0x0000)); uni1.append(unicodeIn[1]); uni1.append(com); - uni1.append((char16_t)0x0000); + uni1.append(static_cast(0x0000)); ascii0.append(asciiIn[0]); ascii0.append(com); - ascii0.append((char16_t)0x0000); + ascii0.append(static_cast(0x0000)); ascii1.append(asciiIn[1]); ascii1.append(com); - ascii1.append((char16_t)0x0000); + ascii1.append(static_cast(0x0000)); for(i=0;i< UPRV_LENGTHOF(unicodeIn); i++){ - u_charsToUChars(asciiIn[i],buf+4, (int32_t)(strlen(asciiIn[i])+1)); + u_charsToUChars(asciiIn[i], buf + 4, static_cast(strlen(asciiIn[i]) + 1)); u_strcat(buf,com); // for every entry in unicodeIn array @@ -809,7 +809,7 @@ void TestIDNA::testCompare(const char* testName, CompareFunc func){ source.truncate(4); source.append(unicodeIn[i]); source.append(com); - source.append((char16_t)0x0000); + source.append(static_cast(0x0000)); // a) compare it with itself const char16_t* src = source.getBuffer(); int32_t srcLen = u_strlen(src); //subtract null @@ -912,7 +912,7 @@ void TestIDNA::testErrorCases(const char* IDNToASCIIName, TestFunc IDNToASCII, ErrorCases errorCase = errorCases[i]; char16_t* src =nullptr; if(errorCase.ascii != nullptr){ - bufLen = (int32_t)strlen(errorCase.ascii); + bufLen = static_cast(strlen(errorCase.ascii)); u_charsToUChars(errorCase.ascii,buf, bufLen+1); }else{ bufLen = 1 ; @@ -1161,7 +1161,7 @@ void TestIDNA::testChaining(const char* toASCIIName, TestFunc toASCII, char16_t buf[MAX_DEST_SIZE]; for(i=0;i< UPRV_LENGTHOF(asciiIn); i++){ - u_charsToUChars(asciiIn[i],buf, (int32_t)(strlen(asciiIn[i])+1)); + u_charsToUChars(asciiIn[i], buf, static_cast(strlen(asciiIn[i]) + 1)); testChaining(buf,5,toUnicodeName, false, false, toUnicode); } for(i=0;i< UPRV_LENGTHOF(unicodeIn); i++){ @@ -1184,23 +1184,23 @@ void TestIDNA::testRootLabelSeparator(const char* testName, CompareFunc func, uni0.append(unicodeIn[0]); uni0.append(com); - uni0.append((char16_t)0x0000); + uni0.append(static_cast(0x0000)); uni1.append(unicodeIn[1]); uni1.append(com); - uni1.append((char16_t)0x0000); + uni1.append(static_cast(0x0000)); ascii0.append(asciiIn[0]); ascii0.append(com); - ascii0.append((char16_t)0x0000); + ascii0.append(static_cast(0x0000)); ascii1.append(asciiIn[1]); ascii1.append(com); - ascii1.append((char16_t)0x0000); + ascii1.append(static_cast(0x0000)); for(i=0;i< UPRV_LENGTHOF(unicodeIn); i++){ - u_charsToUChars(asciiIn[i],buf+4, (int32_t)(strlen(asciiIn[i])+1)); + u_charsToUChars(asciiIn[i], buf + 4, static_cast(strlen(asciiIn[i]) + 1)); u_strcat(buf,com); // for every entry in unicodeIn array @@ -1208,7 +1208,7 @@ void TestIDNA::testRootLabelSeparator(const char* testName, CompareFunc func, source.truncate(4); source.append(unicodeIn[i]); source.append(com); - source.append((char16_t)0x0000); + source.append(static_cast(0x0000)); const char16_t* src = source.getBuffer(); int32_t srcLen = u_strlen(src); //subtract null @@ -1248,7 +1248,7 @@ extern IntlTest *createUTS46Test(); void TestIDNA::runIndexedTest( int32_t index, UBool exec, const char* &name, char* par) { - if (exec) logln((UnicodeString)"TestSuite IDNA API "); + if (exec) logln(UnicodeString("TestSuite IDNA API ")); switch (index) { case 0: name = "TestToASCII"; if (exec) TestToASCII(); break; @@ -1335,13 +1335,13 @@ randul() static UBool initialized = false; if (!initialized) { - srand((unsigned)time(nullptr)); + srand(static_cast(time(nullptr))); initialized = true; } // Assume rand has at least 12 bits of precision uint32_t l = 0; for (uint32_t i=0; i> 4); + reinterpret_cast(&l)[i] = static_cast((rand() & 0x0FF0) >> 4); return l; } @@ -1351,7 +1351,7 @@ randul() */ static int32_t rand_uni() { - int32_t retVal = (int32_t)(randul()& 0x3FFFF); + int32_t retVal = static_cast(randul() & 0x3FFFF); if(retVal >= 0x30000){ retVal+=0xB0000; } @@ -1359,7 +1359,7 @@ static int32_t rand_uni() } static int32_t randi(int32_t n){ - return (int32_t) (randul() % (n+1)); + return static_cast(randul() % (n + 1)); } void getTestSource(UnicodeString& fillIn) { @@ -1370,7 +1370,7 @@ void getTestSource(UnicodeString& fillIn) { if(codepoint == 0x0000){ continue; } - fillIn.append((UChar32)codepoint); + fillIn.append(static_cast(codepoint)); i++; } @@ -1435,7 +1435,7 @@ UnicodeString TestIDNA::testCompareReferenceImpl(UnicodeString& src, void TestIDNA::testCompareReferenceImpl(const char16_t* src, int32_t srcLen){ UnicodeString label(src,srcLen); - label.append((char16_t)0x0000); + label.append(static_cast(0x0000)); //test idnaref_toASCII and idnare UnicodeString asciiLabel = testCompareReferenceImpl(label, @@ -1456,7 +1456,7 @@ void TestIDNA::testCompareReferenceImpl(const char16_t* src, int32_t srcLen){ UIDNA_USE_STD3_RULES | UIDNA_ALLOW_UNASSIGNED); if(asciiLabel.length()!=0){ - asciiLabel.append((char16_t)0x0000); + asciiLabel.append(static_cast(0x0000)); // test toUnciode testCompareReferenceImpl(asciiLabel, @@ -1497,7 +1497,7 @@ void TestIDNA::TestIDNAMonkeyTest(){ for(i=0; i(0x0000)); const char16_t* src = source.getBuffer(); testCompareReferenceImpl(src,source.length()-1); testCompareReferenceImpl(src,source.length()-1); @@ -1508,7 +1508,7 @@ void TestIDNA::TestIDNAMonkeyTest(){ source.truncate(0); source.append( UnicodeString(failures[i], -1, US_INV) ); source = source.unescape(); - source.append((char16_t)0x0000); + source.append(static_cast(0x0000)); const char16_t *src = source.getBuffer(); testCompareReferenceImpl(src,source.length()-1); //debug(source.getBuffer(),source.length(),UIDNA_ALLOW_UNASSIGNED); @@ -1525,7 +1525,7 @@ void TestIDNA::TestIDNAMonkeyTest(){ UnicodeString expected("\\u043f\\u043e\\u0447\\u0435\\u043c\\u0443\\u0436\\u0435\\u043e\\u043d\\u0438\\u043d\\u0435\\u0433\\u043e\\u0432\\u043e\\u0440\\u044f\\u0442\\u043f\\u043e\\u0440\\u0443\\u0441\\u0441\\u043a\\u0438\\u0000", -1, US_INV); expected = expected.unescape(); UnicodeString ascii("xn--b1abfaaepdrnnbgefbadotcwatmq2g4l"); - ascii.append((char16_t)0x0000); + ascii.append(static_cast(0x0000)); testAPI(source.getBuffer(),ascii.getBuffer(), "uidna_toASCII", false, U_ZERO_ERROR, true, true, uidna_toASCII); testAPI(source.getBuffer(),ascii.getBuffer(), "idnaref_toASCII", false, U_ZERO_ERROR, true, true, idnaref_toASCII); @@ -1563,7 +1563,7 @@ void TestIDNA::TestCompareReferenceImpl(){ src[1] = U16_TRAIL(i); srcLen =2; } else { - src[0] = (char16_t)i; + src[0] = static_cast(i); src[1] = 0; srcLen = 1; } diff --git a/icu4c/source/test/intltest/testutil.cpp b/icu4c/source/test/intltest/testutil.cpp index ee4785d4fab8..4e993b4b99fd 100644 --- a/icu4c/source/test/intltest/testutil.cpp +++ b/icu4c/source/test/intltest/testutil.cpp @@ -278,10 +278,10 @@ void TestUtility::checkEditsIter( std::reverse(destIndexes.begin(), destIndexes.end()); // Zig-zag across the indexes to stress next() <-> previous(). static const int32_t ZIG_ZAG[] = { 0, 1, 2, 3, 2, 1 }; - for (auto i = 0; i < (int32_t)srcIndexes.size(); ++i) { + for (auto i = 0; i < static_cast(srcIndexes.size()); ++i) { for (int32_t ij = 0; ij < UPRV_LENGTHOF(ZIG_ZAG); ++ij) { int32_t j = ZIG_ZAG[ij]; - if ((i + j) < (int32_t)srcIndexes.size()) { + if ((i + j) < static_cast(srcIndexes.size())) { int32_t si = srcIndexes[i + j]; test.assertEquals(name + u" destIndexFromSrc(" + si + u"):" + __LINE__, destIndexFromSrc(expected, expLength, srcLength, destLength, si), @@ -289,10 +289,10 @@ void TestUtility::checkEditsIter( } } } - for (auto i = 0; i < (int32_t)destIndexes.size(); ++i) { + for (auto i = 0; i < static_cast(destIndexes.size()); ++i) { for (int32_t ij = 0; ij < UPRV_LENGTHOF(ZIG_ZAG); ++ij) { int32_t j = ZIG_ZAG[ij]; - if ((i + j) < (int32_t)destIndexes.size()) { + if ((i + j) < static_cast(destIndexes.size())) { int32_t di = destIndexes[i + j]; test.assertEquals(name + u" srcIndexFromDest(" + di + u"):" + __LINE__, srcIndexFromDest(expected, expLength, srcLength, destLength, di), diff --git a/icu4c/source/test/intltest/textfile.cpp b/icu4c/source/test/intltest/textfile.cpp index 1bff5e0040f8..38efcfdb7271 100644 --- a/icu4c/source/test/intltest/textfile.cpp +++ b/icu4c/source/test/intltest/textfile.cpp @@ -44,15 +44,15 @@ TextFile::TextFile(const char* _name, const char* _encoding, UErrorCode& ec) : uprv_strcpy(name, _name); uprv_strcpy(encoding, _encoding); #else - name = (char*) _name; - encoding = (char*) _encoding; + name = const_cast(_name); + encoding = const_cast(_encoding); #endif const char* testDir = IntlTest::getSourceTestData(ec); if (U_FAILURE(ec)) { return; } - if (!ensureCapacity((int32_t)(uprv_strlen(testDir) + uprv_strlen(name) + 1))) { + if (!ensureCapacity(static_cast(uprv_strlen(testDir) + uprv_strlen(name) + 1))) { ec = U_MEMORY_ALLOCATION_ERROR; return; } @@ -167,7 +167,7 @@ UBool TextFile::ensureCapacity(int32_t mincapacity) { // Simple realloc() no good; contents not preserved // Note: 'buffer' may be 0 - char* newbuffer = (char*) uprv_malloc(mincapacity); + char* newbuffer = static_cast(uprv_malloc(mincapacity)); if (newbuffer == nullptr) { return false; } diff --git a/icu4c/source/test/intltest/tfsmalls.cpp b/icu4c/source/test/intltest/tfsmalls.cpp index dae2287ad236..5a8d9ea90895 100644 --- a/icu4c/source/test/intltest/tfsmalls.cpp +++ b/icu4c/source/test/intltest/tfsmalls.cpp @@ -251,7 +251,7 @@ void test_Formattable() { Formattable( 1.0, Formattable::kIsDate ), 2.0, - (int32_t)3, + static_cast(3), ucs, ucs_ptr }; @@ -260,7 +260,7 @@ void test_Formattable() UnicodeString temp; if ((ft_arr[0].getType() == Formattable::kDate) && (ft_arr[0].getDate() == 1.0) && (ft_arr[1].getType() == Formattable::kDouble) && (ft_arr[1].getDouble() == 2.0) - && (ft_arr[2].getType() == Formattable::kLong) && (ft_arr[2].getLong() == (int32_t)3) + && (ft_arr[2].getType() == Formattable::kLong) && (ft_arr[2].getLong() == static_cast(3)) && (ft_arr[3].getType() == Formattable::kString) && (ft_arr[3].getString(temp) == ucs) && (ft_arr[4].getType() == Formattable::kString) && (ft_arr[4].getString(temp) == *ucs_ptr) ) { it_logln("FT constr. for date, double, long, ustring, ustring* and array tested"); @@ -313,14 +313,14 @@ void test_Formattable() delete pf; } - const Formattable ftarr1[] = { Formattable( (int32_t)1 ), Formattable( (int32_t)2 ) }; - const Formattable ftarr2[] = { Formattable( (int32_t)3 ), Formattable( (int32_t)4 ) }; + const Formattable ftarr1[] = { Formattable(static_cast(1)), Formattable(static_cast(2)) }; + const Formattable ftarr2[] = { Formattable(static_cast(3)), Formattable(static_cast(4)) }; const int32_t ftarr1_cnt = UPRV_LENGTHOF(ftarr1); const int32_t ftarr2_cnt = UPRV_LENGTHOF(ftarr2); ft_arr.setArray( ftarr1, ftarr1_cnt ); - if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == (int32_t)1)) { + if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == static_cast(1))) { it_logln("FT setArray tested"); }else{ it_errln("*** FT setArray"); @@ -330,16 +330,16 @@ void test_Formattable() for (i = 0; i < ftarr2_cnt; i++ ) { ft_dynarr[i] = ftarr2[i]; } - if ((ft_dynarr[0].getType() == Formattable::kLong) && (ft_dynarr[0].getLong() == (int32_t)3) - && (ft_dynarr[1].getType() == Formattable::kLong) && (ft_dynarr[1].getLong() == (int32_t)4)) { + if ((ft_dynarr[0].getType() == Formattable::kLong) && (ft_dynarr[0].getLong() == static_cast(3)) + && (ft_dynarr[1].getType() == Formattable::kLong) && (ft_dynarr[1].getLong() == static_cast(4))) { it_logln("FT operator= and array operations tested"); }else{ it_errln("*** FT operator= or array operations"); } ft_arr.adoptArray( ft_dynarr, ftarr2_cnt ); - if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == (int32_t)3) - && (ft_arr[1].getType() == Formattable::kLong) && (ft_arr[1].getLong() == (int32_t)4)) { + if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == static_cast(3)) + && (ft_arr[1].getType() == Formattable::kLong) && (ft_arr[1].getLong() == static_cast(4))) { it_logln("FT adoptArray tested"); }else{ it_errln("*** FT adoptArray or operator[]"); diff --git a/icu4c/source/test/intltest/thcoll.cpp b/icu4c/source/test/intltest/thcoll.cpp index c3e45e7d0f00..5303cab562d2 100644 --- a/icu4c/source/test/intltest/thcoll.cpp +++ b/icu4c/source/test/intltest/thcoll.cpp @@ -104,7 +104,7 @@ void CollationThaiTest::TestNamesList() { ++wordCount; if (wordCount <= 8) { UnicodeString str; - logln((UnicodeString)"Word " + wordCount + ": " + IntlTest::prettify(word, str)); + logln(UnicodeString("Word ") + wordCount + ": " + IntlTest::prettify(word, str)); } if (lastWord.length() > 0) { @@ -116,7 +116,7 @@ void CollationThaiTest::TestNamesList() { assertSuccess("readLine", ec); - logln((UnicodeString)"Words checked: " + wordCount); + logln(UnicodeString("Words checked: ") + wordCount); } /** @@ -151,7 +151,7 @@ void CollationThaiTest::TestDictionary() { ++wordCount; if (wordCount <= 8) { UnicodeString str; - logln((UnicodeString)"Word " + wordCount + ": " + IntlTest::prettify(word, str)); + logln(UnicodeString("Word ") + wordCount + ": " + IntlTest::prettify(word, str)); } if (lastWord.length() > 0) { @@ -173,7 +173,7 @@ void CollationThaiTest::TestDictionary() { coll->getCollationKey(lastWord, k1, status); coll->getCollationKey(word, k2, status); if (U_FAILURE(status)) { - errln((UnicodeString)"Fail: getCollationKey returned " + u_errorName(status)); + errln(UnicodeString("Fail: getCollationKey returned ") + u_errorName(status)); return; } msg.append("key1: ").append(prettify(k1, str)).append("\n"); @@ -189,14 +189,14 @@ void CollationThaiTest::TestDictionary() { if (failed != 0) { if (failed > MAX_FAILURES_TO_SHOW) { - errln((UnicodeString)"Too many failures; only the first " + + errln(UnicodeString("Too many failures; only the first ") + MAX_FAILURES_TO_SHOW + " failures were shown"); } - errln((UnicodeString)"Summary: " + failed + " of " + (riwords.getLineNumber() - 1) + + errln(UnicodeString("Summary: ") + failed + " of " + (riwords.getLineNumber() - 1) + " comparisons failed"); } - logln((UnicodeString)"Words checked: " + wordCount); + logln(UnicodeString("Words checked: ") + wordCount); } /** @@ -268,7 +268,7 @@ void CollationThaiTest::compareArray(Collator& c, const char* tests[], expect = Collator::EQUAL; } else { // expect = Integer.decode(tests[i+1]).intValue(); - errln((UnicodeString)"Error: unknown operator " + tests[i+1]); + errln(UnicodeString("Error: unknown operator ") + tests[i + 1]); return; } diff --git a/icu4c/source/test/intltest/tmsgfmt.cpp b/icu4c/source/test/intltest/tmsgfmt.cpp index ad676d1c29d9..3f1b8ba9b428 100644 --- a/icu4c/source/test/intltest/tmsgfmt.cpp +++ b/icu4c/source/test/intltest/tmsgfmt.cpp @@ -170,7 +170,7 @@ void TestMessageFormat::testBug1() ChoiceFormat *cf = new ChoiceFormat(limit, formats, 3); FieldPosition status(FieldPosition::DONT_CARE); UnicodeString toAppendTo; - cf->format((int32_t)1, toAppendTo, status); + cf->format(static_cast(1), toAppendTo, status); if (toAppendTo != "1.0<=Arg<2.0") { errln("ChoiceFormat cmp in testBug1"); } @@ -254,8 +254,8 @@ operator<<( IntlTest& stream, void TestMessageFormat::PatternTest() { Formattable testArgs[] = { - Formattable(double(1)), Formattable(double(3456)), - Formattable("Disk"), Formattable(UDate((int32_t)1000000000L), Formattable::kIsDate) + Formattable(static_cast(1)), Formattable(static_cast(3456)), + Formattable("Disk"), Formattable(static_cast(static_cast(1000000000L)), Formattable::kIsDate) }; UnicodeString testCases[] = { "Quotes '', '{', 'a' {0} '{0}'", @@ -305,7 +305,7 @@ void TestMessageFormat::PatternTest() form.adoptInstead(new MessageFormat(testCases[i], Locale::getUS(), success)); if (U_FAILURE(success)) { dataerrln("MessageFormat creation failed.#1 - %s", u_errorName(success)); - logln(((UnicodeString)"MessageFormat for ") + testCases[i] + " creation failed.\n"); + logln(UnicodeString("MessageFormat for ") + testCases[i] + " creation failed.\n"); continue; } // ICU 4.8 returns the original pattern (testCases), @@ -317,9 +317,9 @@ void TestMessageFormat::PatternTest() // (Too much trouble...) errln(UnicodeString("TestMessageFormat::PatternTest failed test #2, i = ") + i); //form->toPattern(buffer); - errln(((UnicodeString)" Orig: ") + testCases[i]); - errln(((UnicodeString)" Exp: ") + testCases[i]); - errln(((UnicodeString)" Got: ") + buffer); + errln(UnicodeString(" Orig: ") + testCases[i]); + errln(UnicodeString(" Exp: ") + testCases[i]); + errln(UnicodeString(" Got: ") + buffer); } //it_out << "Pat out: " << form->toPattern(buffer)); @@ -398,8 +398,8 @@ void TestMessageFormat::testStaticFormat() { UErrorCode err = U_ZERO_ERROR; Formattable arguments[] = { - (int32_t)7, - Formattable(UDate(8.71068e+011), Formattable::kIsDate), + static_cast(7), + Formattable(static_cast(8.71068e+011), Formattable::kIsDate), "a disturbance in the Force" }; @@ -413,7 +413,7 @@ void TestMessageFormat::testStaticFormat() if (U_FAILURE(err)) { dataerrln("TestMessageFormat::testStaticFormat #1 - %s", u_errorName(err)); - logln(UnicodeString("TestMessageFormat::testStaticFormat failed test #1 with error code ")+(int32_t)err); + logln(UnicodeString("TestMessageFormat::testStaticFormat failed test #1 with error code ") + static_cast(err)); return; } @@ -434,8 +434,8 @@ void TestMessageFormat::TestTurkishCasing() Locale::setDefault( Locale("tr"), err ); Formattable arguments[] = { - (int32_t)7, - Formattable(UDate(8.71068e+011), Formattable::kIsDate), + static_cast(7), + Formattable(static_cast(8.71068e+011), Formattable::kIsDate), "a disturbance in the Force" }; @@ -468,9 +468,9 @@ void TestMessageFormat::testSimpleFormat(/* char* par */) UErrorCode err = U_ZERO_ERROR; - Formattable testArgs1[] = {(int32_t)0, "MyDisk"}; - Formattable testArgs2[] = {(int32_t)1, "MyDisk"}; - Formattable testArgs3[] = {(int32_t)12, "MyDisk"}; + Formattable testArgs1[] = {static_cast(0), "MyDisk"}; + Formattable testArgs2[] = {static_cast(1), "MyDisk"}; + Formattable testArgs3[] = {static_cast(12), "MyDisk"}; MessageFormat* form = new MessageFormat( "The disk \"{1}\" contains {0} file(s).", err); @@ -515,7 +515,7 @@ void TestMessageFormat::testMsgFormatChoice(/* char* par */) FieldPosition ignore(FieldPosition::DONT_CARE); UnicodeString string; - Formattable testArgs1[] = {(int32_t)0, "MyDisk"}; + Formattable testArgs1[] = {static_cast(0), "MyDisk"}; form->format(testArgs1, 2, string, ignore, err); if (string != "The disk \"MyDisk\" contains no files.") { errln("TestMessageFormat::testMsgFormatChoice failed on test #1"); @@ -523,7 +523,7 @@ void TestMessageFormat::testMsgFormatChoice(/* char* par */) ignore.setField(FieldPosition::DONT_CARE); string.remove(); - Formattable testArgs2[] = {(int32_t)1, "MyDisk"}; + Formattable testArgs2[] = {static_cast(1), "MyDisk"}; form->format(testArgs2, 2, string, ignore, err); if (string != "The disk \"MyDisk\" contains one file.") { errln("TestMessageFormat::testMsgFormatChoice failed on test #2"); @@ -531,7 +531,7 @@ void TestMessageFormat::testMsgFormatChoice(/* char* par */) ignore.setField(FieldPosition::DONT_CARE); string.remove(); - Formattable testArgs3[] = {(int32_t)1273, "MyDisk"}; + Formattable testArgs3[] = {static_cast(1273), "MyDisk"}; form->format(testArgs3, 2, string, ignore, err); if (string != "The disk \"MyDisk\" contains 1,273 files.") { dataerrln("TestMessageFormat::testMsgFormatChoice failed on test #3 - %s", u_errorName(err)); @@ -555,10 +555,10 @@ void TestMessageFormat::testMsgFormatPlural(/* char* par */) MessageFormat* mfNum = new MessageFormat(t1, Locale("fr"), err); if (U_FAILURE(err)) { dataerrln("TestMessageFormat::testMsgFormatPlural #1 - argumentIndex - %s", u_errorName(err)); - logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #1 with error code ")+(int32_t)err); + logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #1 with error code ") + static_cast(err)); return; } - Formattable testArgs1((int32_t)0); + Formattable testArgs1(static_cast(0)); FieldPosition ignore(FieldPosition::DONT_CARE); UnicodeString numResult1; mfNum->format(&testArgs1, 1, numResult1, ignore, err); @@ -569,7 +569,7 @@ void TestMessageFormat::testMsgFormatPlural(/* char* par */) mfAlpha->format(argName, &testArgs1, 1, argNameResult, err); if (U_FAILURE(err)) { dataerrln("TestMessageFormat::testMsgFormatPlural #1 - argumentName - %s", u_errorName(err)); - logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #1 with error code ")+(int32_t)err); + logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #1 with error code ") + static_cast(err)); delete mfNum; return; } @@ -588,7 +588,7 @@ void TestMessageFormat::testMsgFormatPlural(/* char* par */) MessageFormat* mfNum2 = new MessageFormat(t3, Locale("uk"), err); numResult1.remove(); - Formattable testArgs2((int32_t)4); + Formattable testArgs2(static_cast(4)); mfNum2->format(&testArgs2, 1, numResult1, ignore, err); MessageFormat* mfAlpha2 = new MessageFormat(t4, Locale("uk"), err); argNameResult.remove(); @@ -596,7 +596,7 @@ void TestMessageFormat::testMsgFormatPlural(/* char* par */) if (U_FAILURE(err)) { errln("TestMessageFormat::testMsgFormatPlural #2 - argumentName"); - logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #2 with error code ")+(int32_t)err); + logln(UnicodeString("TestMessageFormat::testMsgFormatPlural #2 with error code ") + static_cast(err)); delete mfNum2; return; } @@ -617,11 +617,11 @@ void TestMessageFormat::testMsgFormatPlural(/* char* par */) MessageFormat* msgFmt = new MessageFormat(t5, Locale("fr"), err); if (U_FAILURE(err)) { errln("TestMessageFormat::test nested PluralFormat with argumentName"); - logln(UnicodeString("TestMessageFormat::test nested PluralFormat with error code ")+(int32_t)err); + logln(UnicodeString("TestMessageFormat::test nested PluralFormat with error code ") + static_cast(err)); delete msgFmt; return; } - Formattable testArgs3((int32_t)0); + Formattable testArgs3(static_cast(0)); argNameResult.remove(); msgFmt->format(&testArgs3, 1, argNameResult, ignore, err); if (U_FAILURE(err)) { @@ -645,7 +645,7 @@ void TestMessageFormat::testApostropheInPluralAndSelect() { return; } UnicodeString expected = UNICODE_STRING_SIMPLE("abc_3#3{3'_def_sel}ect'_xyz"); - Formattable args[] = { (int32_t)3, UNICODE_STRING_SIMPLE("x") }; + Formattable args[] = { static_cast(3), UNICODE_STRING_SIMPLE("x") }; internalFormat( &msgFmt, args, 2, expected, "MessageFormat with apostrophes in plural/select arguments failed:\n"); @@ -679,7 +679,7 @@ MessageFormat* TestMessageFormat::internalCreate( LocalPointer msgFmt(new MessageFormat(pattern, locale, status)); if (U_FAILURE(status)) { dataerrln( "%s error while constructing with ErrorCode as %s" ,errMsg, u_errorName(status) ); - logln(UnicodeString("TestMessageFormat::testMsgFormatSelect #1 with error code ")+(int32_t)status); + logln(UnicodeString("TestMessageFormat::testMsgFormatSelect #1 with error code ") + static_cast(status)); return nullptr; } return msgFmt.orphan(); @@ -765,9 +765,9 @@ void TestMessageFormat::testMsgFormatSelect(/* char* par */) MessageFormat* msgFmt4 = internalCreate(t4.unescape(), Locale("fr"),err,(char*)"From TestMessageFormat::TestSelectFormat create t4"); if (!U_FAILURE(err)) { //Arguments - Formattable testArgs10[] = {"Kirti","female",(int32_t)6}; + Formattable testArgs10[] = {"Kirti", "female", static_cast(6)}; Formattable testArgs11[] = {"Kirti","female",100.100}; - Formattable testArgs12[] = {"Kirti","other",(int32_t)6}; + Formattable testArgs12[] = {"Kirti", "other", static_cast(6)}; Formattable* testArgs[] = {testArgs10,testArgs11,testArgs12}; UnicodeString exp[] = { "Kirti est 6 all\\u00E9e \\u00E0 Paris." , @@ -788,10 +788,10 @@ void TestMessageFormat::testMsgFormatSelect(/* char* par */) // with no data the above should fail but it seems to construct an invalid MessageFormat with no reported error. See #13079 if (!U_FAILURE(err)) { //Arguments - Formattable testArgs10[] = {"Kirti",(int32_t)6,"female"}; - Formattable testArgs11[] = {"Kirti",(int32_t)1,"female"}; - Formattable testArgs12[] = {"Ash",(int32_t)1,"other"}; - Formattable testArgs13[] = {"Ash",(int32_t)5,"other"}; + Formattable testArgs10[] = {"Kirti", static_cast(6), "female"}; + Formattable testArgs11[] = {"Kirti", static_cast(1), "female"}; + Formattable testArgs12[] = {"Ash", static_cast(1), "other"}; + Formattable testArgs13[] = {"Ash", static_cast(5), "other"}; Formattable* testArgs[] = {testArgs10,testArgs11,testArgs12,testArgs13}; UnicodeString exp[] = { "Kirti sont all\\u00E9es \\u00E0 Paris." , @@ -812,21 +812,21 @@ void TestMessageFormat::testMsgFormatSelect(/* char* par */) LocalPointer msgFmt6( internalCreate(t6, Locale("de"),err,(char*)"From TestMessageFormat::TestSelectFormat create t6")); if (!U_FAILURE(err)) { - //Arguments - Formattable testArgs10[] = {"Kirti","other",(int32_t)1,"other"}; - Formattable testArgs11[] = {"Kirti","other",(int32_t)6,"other"}; - Formattable testArgs12[] = {"Kirti","other",(int32_t)1,"female"}; - Formattable testArgs13[] = {"Kirti","other",(int32_t)3,"female"}; - Formattable testArgs14[] = {"Kirti","female",(int32_t)1,"female"}; - Formattable testArgs15[] = {"Kirti","female",(int32_t)5,"female"}; - Formattable testArgs16[] = {"Kirti","female",(int32_t)1,"other"}; - Formattable testArgs17[] = {"Kirti","female",(int32_t)5,"other"}; - Formattable testArgs18[] = {"Kirti","mixed",(int32_t)1,"mixed"}; - Formattable testArgs19[] = {"Kirti","mixed",(int32_t)1,"other"}; - Formattable testArgs20[] = {"Kirti","female",(int32_t)1,"mixed"}; - Formattable testArgs21[] = {"Kirti","mixed",(int32_t)5,"mixed"}; - Formattable testArgs22[] = {"Kirti","mixed",(int32_t)5,"other"}; - Formattable testArgs23[] = {"Kirti","female",(int32_t)5,"mixed"}; + //Arguments + Formattable testArgs10[] = {"Kirti", "other", static_cast(1), "other"}; + Formattable testArgs11[] = {"Kirti", "other", static_cast(6), "other"}; + Formattable testArgs12[] = {"Kirti", "other", static_cast(1), "female"}; + Formattable testArgs13[] = {"Kirti", "other", static_cast(3), "female"}; + Formattable testArgs14[] = {"Kirti", "female", static_cast(1), "female"}; + Formattable testArgs15[] = {"Kirti", "female", static_cast(5), "female"}; + Formattable testArgs16[] = {"Kirti", "female", static_cast(1), "other"}; + Formattable testArgs17[] = {"Kirti", "female", static_cast(5), "other"}; + Formattable testArgs18[] = {"Kirti", "mixed", static_cast(1), "mixed"}; + Formattable testArgs19[] = {"Kirti", "mixed", static_cast(1), "other"}; + Formattable testArgs20[] = {"Kirti", "female", static_cast(1), "mixed"}; + Formattable testArgs21[] = {"Kirti", "mixed", static_cast(5), "mixed"}; + Formattable testArgs22[] = {"Kirti", "mixed", static_cast(5), "other"}; + Formattable testArgs23[] = {"Kirti", "female", static_cast(5), "mixed"}; Formattable* testArgs[] = {testArgs10,testArgs11,testArgs12,testArgs13, testArgs14,testArgs15,testArgs16,testArgs17, testArgs18,testArgs19,testArgs20,testArgs21, @@ -983,7 +983,7 @@ void TestMessageFormat::testSetLocale() GregorianCalendar cal(err); Formattable arguments[] = { 456.83, - Formattable(UDate(8.71068e+011), Formattable::kIsDate), + Formattable(static_cast(8.71068e+011), Formattable::kIsDate), "deposit" }; @@ -995,14 +995,14 @@ void TestMessageFormat::testSetLocale() // Just use unlocalized currency symbol. //UnicodeString compareStrEng = "At