StringUtil.cpp (2610B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "base/string_util.h" 8 9 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. 10 // Use of this source code is governed by a BSD-style license that can be 11 // found in the LICENSE file. 12 13 #include "base/sys_string_conversions.h" 14 15 #include "base/string_piece.h" 16 #include "base/string_util.h" 17 18 // FIXME/cjones: these really only pertain to the linux sys string 19 // converters. 20 #ifdef XP_WIN 21 # define ICONV_WCHAR_T_ENCODING "UTF-16" 22 #else 23 # define ICONV_WCHAR_T_ENCODING "WCHAR_T" 24 #endif 25 26 // FIXME/cjones: BIG assumption here that std::string is a good 27 // container of UTF8-encoded strings. this is probably wrong, as its 28 // API doesn't really make sense for UTF8. 29 30 namespace base { 31 32 // FIXME/cjones: as its name implies, this function is a hack. 33 template <typename FromType, typename ToType> 34 ToType HackyStringConvert(const FromType& in) { 35 // FIXME/cjones: assumes no non-ASCII characters in |in| 36 ToType out; 37 out.resize(in.length()); 38 for (int i = 0; i < static_cast<int>(in.length()); ++i) 39 out[i] = static_cast<typename ToType::value_type>(in[i]); 40 return out; 41 } 42 43 } // namespace base 44 45 // Implement functions that were in the chromium ICU library, which 46 // we're not taking. 47 48 std::string WideToUTF8(const std::wstring& wide) { 49 return base::SysWideToUTF8(wide); 50 } 51 52 std::wstring UTF8ToWide(const StringPiece& utf8) { 53 return base::SysUTF8ToWide(utf8); 54 } 55 56 namespace base { 57 58 // FIXME/cjones: here we're entirely replacing the linux string 59 // converters, and implementing the one that doesn't exist for OS X 60 // and Windows. 61 62 #if !defined(XP_DARWIN) && !defined(XP_WIN) 63 std::string SysWideToUTF8(const std::wstring& wide) { 64 // FIXME/cjones: do this with iconv 65 return HackyStringConvert<std::wstring, std::string>(wide); 66 } 67 #endif 68 69 #if !defined(XP_DARWIN) && !defined(XP_WIN) 70 std::wstring SysUTF8ToWide(const StringPiece& utf8) { 71 // FIXME/cjones: do this with iconv 72 return HackyStringConvert<StringPiece, std::wstring>(utf8); 73 } 74 75 std::string SysWideToNativeMB(const std::wstring& wide) { 76 // TODO(evanm): we can't assume Linux is UTF-8. 77 return SysWideToUTF8(wide); 78 } 79 80 std::wstring SysNativeMBToWide(const StringPiece& native_mb) { 81 // TODO(evanm): we can't assume Linux is UTF-8. 82 return SysUTF8ToWide(native_mb); 83 } 84 #endif 85 86 } // namespace base