1/* 2 * (C) 1999 Lars Knoll (knoll@kde.org) 3 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. 4 * Copyright (C) 2007-2009 Torch Mobile, Inc. 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Library General Public 8 * License as published by the Free Software Foundation; either 9 * version 2 of the License, or (at your option) any later version. 10 * 11 * This library is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 * Library General Public License for more details. 15 * 16 * You should have received a copy of the GNU Library General Public License 17 * along with this library; see the file COPYING.LIB. If not, write to 18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA. 20 */ 21 22#include "config.h" 23#include "PlatformString.h" 24 25#include "SharedBuffer.h" 26#include "TextBreakIterator.h" 27#include <wtf/unicode/UTF8.h> 28#include <wtf/unicode/Unicode.h> 29 30using namespace WTF; 31using namespace WTF::Unicode; 32 33namespace WebCore { 34 35PassRefPtr<SharedBuffer> utf8Buffer(const String& string) 36{ 37 // Allocate a buffer big enough to hold all the characters. 38 const int length = string.length(); 39 Vector<char> buffer(length * 3); 40 41 // Convert to runs of 8-bit characters. 42 char* p = buffer.data(); 43 const UChar* d = string.characters(); 44 ConversionResult result = convertUTF16ToUTF8(&d, d + length, &p, p + buffer.size(), true); 45 if (result != conversionOK) 46 return 0; 47 48 buffer.shrink(p - buffer.data()); 49 return SharedBuffer::adoptVector(buffer); 50} 51 52unsigned numGraphemeClusters(const String& s) 53{ 54 TextBreakIterator* it = characterBreakIterator(s.characters(), s.length()); 55 if (!it) 56 return s.length(); 57 58 unsigned num = 0; 59 while (textBreakNext(it) != TextBreakDone) 60 ++num; 61 return num; 62} 63 64unsigned numCharactersInGraphemeClusters(const String& s, unsigned numGraphemeClusters) 65{ 66 TextBreakIterator* it = characterBreakIterator(s.characters(), s.length()); 67 if (!it) 68 return min(s.length(), numGraphemeClusters); 69 70 for (unsigned i = 0; i < numGraphemeClusters; ++i) { 71 if (textBreakNext(it) == TextBreakDone) 72 return s.length(); 73 } 74 return textBreakCurrent(it); 75} 76 77} // namespace WebCore 78