utf_string_conversions.h revision 3345a6884c488ff3a535c2c9acdd33d74b37e311
1// Copyright (c) 2009 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef BASE_UTF_STRING_CONVERSIONS_H_ 6#define BASE_UTF_STRING_CONVERSIONS_H_ 7#pragma once 8 9#include <string> 10 11#include "base/string16.h" 12 13namespace base { 14class StringPiece; 15} 16 17// These convert between UTF-8, -16, and -32 strings. They are potentially slow, 18// so avoid unnecessary conversions. The low-level versions return a boolean 19// indicating whether the conversion was 100% valid. In this case, it will still 20// do the best it can and put the result in the output buffer. The versions that 21// return strings ignore this error and just return the best conversion 22// possible. 23bool WideToUTF8(const wchar_t* src, size_t src_len, std::string* output); 24std::string WideToUTF8(const std::wstring& wide); 25bool UTF8ToWide(const char* src, size_t src_len, std::wstring* output); 26std::wstring UTF8ToWide(const base::StringPiece& utf8); 27 28bool WideToUTF16(const wchar_t* src, size_t src_len, string16* output); 29string16 WideToUTF16(const std::wstring& wide); 30bool UTF16ToWide(const char16* src, size_t src_len, std::wstring* output); 31std::wstring UTF16ToWide(const string16& utf16); 32 33bool UTF8ToUTF16(const char* src, size_t src_len, string16* output); 34string16 UTF8ToUTF16(const std::string& utf8); 35bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output); 36std::string UTF16ToUTF8(const string16& utf16); 37 38// We are trying to get rid of wstring as much as possible, but it's too big 39// a mess to do it all at once. These conversions should be used when we 40// really should just be passing a string16 around, but we haven't finished 41// porting whatever module uses wstring and the conversion is being used as a 42// stopcock. This makes it easy to grep for the ones that should be removed. 43#if defined(OS_WIN) 44# define WideToUTF16Hack 45# define UTF16ToWideHack 46#else 47# define WideToUTF16Hack WideToUTF16 48# define UTF16ToWideHack UTF16ToWide 49#endif 50 51// These convert an ASCII string, typically a hardcoded constant, to a 52// UTF16/Wide string. 53// 54// Note that this doesn't use StringPiece because it's very common to need 55// ASCIIToUTF16("foo"), and either we have to include it in this file, or 56// forward declare it and force all callers to include string_piece.h. Given 57// that string_piece brings in complicated stuff like <algorithm>, it's 58// easier to just duplicate these very simple definitions for the two calling 59// cases we actually use. 60std::wstring ASCIIToWide(const char* ascii); 61std::wstring ASCIIToWide(const std::string& ascii); 62string16 ASCIIToUTF16(const char* ascii); 63string16 ASCIIToUTF16(const std::string& ascii); 64 65#endif // BASE_UTF_STRING_CONVERSIONS_H_ 66