1// Copyright 2016 The Chromium Authors 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include <CoreFoundation/CoreFoundation.h> 6 7#include <ostream> 8#include <string> 9#include <string_view> 10 11#include "base/apple/scoped_cftyperef.h" 12#include "base/check.h" 13#include "base/numerics/safe_conversions.h" 14#include "base/strings/sys_string_conversions.h" 15#include "net/base/net_string_util.h" 16 17namespace net { 18 19namespace { 20 21bool CharsetToCFStringEncoding(const char* charset, 22 CFStringEncoding* encoding) { 23 if (charset == kCharsetLatin1 || strcmp(charset, kCharsetLatin1) == 0) { 24 *encoding = kCFStringEncodingISOLatin1; 25 return true; 26 } 27 // TODO(mattm): handle other charsets? See 28 // https://developer.apple.com/reference/corefoundation/cfstringbuiltinencodings?language=objc 29 // for list of standard CFStringEncodings. 30 31 return false; 32} 33 34} // namespace 35 36// This constant cannot be defined as const char[] because it is initialized 37// by base::kCodepageLatin1 (which is const char[]) in net_string_util_icu.cc. 38const char* const kCharsetLatin1 = "ISO-8859-1"; 39 40bool ConvertToUtf8(std::string_view text, 41 const char* charset, 42 std::string* output) { 43 CFStringEncoding encoding; 44 if (!CharsetToCFStringEncoding(charset, &encoding)) 45 return false; 46 47 base::apple::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytes( 48 kCFAllocatorDefault, reinterpret_cast<const UInt8*>(text.data()), 49 base::checked_cast<CFIndex>(text.length()), encoding, 50 /*isExternalRepresentation=*/false)); 51 if (!cfstring) { 52 return false; 53 } 54 *output = base::SysCFStringRefToUTF8(cfstring.get()); 55 return true; 56} 57 58bool ConvertToUtf8AndNormalize(std::string_view text, 59 const char* charset, 60 std::string* output) { 61 DCHECK(false) << "Not implemented yet."; 62 return false; 63} 64 65bool ConvertToUTF16(std::string_view text, 66 const char* charset, 67 std::u16string* output) { 68 DCHECK(false) << "Not implemented yet."; 69 return false; 70} 71 72bool ConvertToUTF16WithSubstitutions(std::string_view text, 73 const char* charset, 74 std::u16string* output) { 75 DCHECK(false) << "Not implemented yet."; 76 return false; 77} 78 79bool ToUpper(std::u16string_view str, std::u16string* output) { 80 base::apple::ScopedCFTypeRef<CFStringRef> cfstring = 81 base::SysUTF16ToCFStringRef(str); 82 base::apple::ScopedCFTypeRef<CFMutableStringRef> mutable_cfstring( 83 CFStringCreateMutableCopy(kCFAllocatorDefault, /*maxLength=*/0, 84 cfstring.get())); 85 CFStringUppercase(mutable_cfstring.get(), /*locale=*/nullptr); 86 *output = base::SysCFStringRefToUTF16(mutable_cfstring.get()); 87 return true; 88} 89 90} // namespace net 91