1*d3cdf0f2SRahul Joshi //===- OptionStrCmp.cpp - Option String Comparison --------------*- C++ -*-===// 2*d3cdf0f2SRahul Joshi // 3*d3cdf0f2SRahul Joshi // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*d3cdf0f2SRahul Joshi // See https://llvm.org/LICENSE.txt for license information. 5*d3cdf0f2SRahul Joshi // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*d3cdf0f2SRahul Joshi // 7*d3cdf0f2SRahul Joshi //===----------------------------------------------------------------------===// 8*d3cdf0f2SRahul Joshi 9*d3cdf0f2SRahul Joshi #include "llvm/Support/OptionStrCmp.h" 10*d3cdf0f2SRahul Joshi #include "llvm/ADT/STLExtras.h" 11*d3cdf0f2SRahul Joshi 12*d3cdf0f2SRahul Joshi using namespace llvm; 13*d3cdf0f2SRahul Joshi 14*d3cdf0f2SRahul Joshi // Comparison function for Option strings (option names & prefixes). 15*d3cdf0f2SRahul Joshi // The ordering is *almost* case-insensitive lexicographic, with an exception. 16*d3cdf0f2SRahul Joshi // '\0' comes at the end of the alphabet instead of the beginning (thus options 17*d3cdf0f2SRahul Joshi // precede any other options which prefix them). Additionally, if two options 18*d3cdf0f2SRahul Joshi // are identical ignoring case, they are ordered according to case sensitive 19*d3cdf0f2SRahul Joshi // ordering if `FallbackCaseSensitive` is true. 20*d3cdf0f2SRahul Joshi int llvm::StrCmpOptionName(StringRef A, StringRef B, 21*d3cdf0f2SRahul Joshi bool FallbackCaseSensitive) { 22*d3cdf0f2SRahul Joshi size_t MinSize = std::min(A.size(), B.size()); 23*d3cdf0f2SRahul Joshi if (int Res = A.substr(0, MinSize).compare_insensitive(B.substr(0, MinSize))) 24*d3cdf0f2SRahul Joshi return Res; 25*d3cdf0f2SRahul Joshi 26*d3cdf0f2SRahul Joshi // If they are identical ignoring case, use case sensitive ordering. 27*d3cdf0f2SRahul Joshi if (A.size() == B.size()) 28*d3cdf0f2SRahul Joshi return FallbackCaseSensitive ? A.compare(B) : 0; 29*d3cdf0f2SRahul Joshi 30*d3cdf0f2SRahul Joshi return (A.size() == MinSize) ? 1 /* A is a prefix of B. */ 31*d3cdf0f2SRahul Joshi : -1 /* B is a prefix of A */; 32*d3cdf0f2SRahul Joshi } 33*d3cdf0f2SRahul Joshi 34*d3cdf0f2SRahul Joshi // Comparison function for Option prefixes. 35*d3cdf0f2SRahul Joshi int llvm::StrCmpOptionPrefixes(ArrayRef<StringRef> APrefixes, 36*d3cdf0f2SRahul Joshi ArrayRef<StringRef> BPrefixes) { 37*d3cdf0f2SRahul Joshi for (const auto &[APre, BPre] : zip(APrefixes, BPrefixes)) { 38*d3cdf0f2SRahul Joshi if (int Cmp = StrCmpOptionName(APre, BPre)) 39*d3cdf0f2SRahul Joshi return Cmp; 40*d3cdf0f2SRahul Joshi } 41*d3cdf0f2SRahul Joshi // Both prefixes are identical. 42*d3cdf0f2SRahul Joshi return 0; 43*d3cdf0f2SRahul Joshi } 44