xref: /haiku/src/kits/locale/StringFormat.cpp (revision cbe0a0c436162d78cc3f92a305b64918c839d079)
1 /*
2  * Copyright 2014-2015 Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Adrien Destugues, pulkomandy@pulkomandy.tk
7  *		John Scipione, jscipione@gmail.com
8  */
9 
10 #include <unicode/uversion.h>
11 #include <StringFormat.h>
12 
13 #include <Autolock.h>
14 #include <FormattingConventionsPrivate.h>
15 #include <LanguagePrivate.h>
16 
17 #include <ICUWrapper.h>
18 
19 #include <unicode/msgfmt.h>
20 
21 
22 U_NAMESPACE_USE
23 
24 
25 BStringFormat::BStringFormat(const BLanguage& language, const BString pattern)
26 	: BFormat(language, BFormattingConventions())
27 {
28 	_Initialize(UnicodeString::fromUTF8(pattern.String()));
29 }
30 
31 
32 BStringFormat::BStringFormat(const BString pattern)
33 	: BFormat()
34 {
35 	_Initialize(UnicodeString::fromUTF8(pattern.String()));
36 }
37 
38 
39 BStringFormat::~BStringFormat()
40 {
41 	delete fFormatter;
42 }
43 
44 
45 status_t
46 BStringFormat::InitCheck()
47 {
48 	return fInitStatus;
49 }
50 
51 
52 status_t
53 BStringFormat::Format(BString& output, const int64 arg) const
54 {
55 	if (fInitStatus != B_OK)
56 		return fInitStatus;
57 
58 	UnicodeString buffer;
59 	UErrorCode error = U_ZERO_ERROR;
60 
61 	Formattable arguments[] = {
62 		(int64)arg
63 	};
64 
65 	FieldPosition pos;
66 	buffer = fFormatter->format(arguments, 1, buffer, pos, error);
67 	if (!U_SUCCESS(error))
68 		return B_ERROR;
69 
70 	BStringByteSink byteSink(&output);
71 	buffer.toUTF8(byteSink);
72 
73 	return B_OK;
74 }
75 
76 
77 status_t
78 BStringFormat::_Initialize(const UnicodeString& pattern)
79 {
80 	fInitStatus = B_OK;
81 	UErrorCode error = U_ZERO_ERROR;
82 	Locale* icuLocale
83 		= BLanguage::Private(&fLanguage).ICULocale();
84 
85 	fFormatter = new MessageFormat(pattern, *icuLocale, error);
86 
87 	if (fFormatter == NULL)
88 		fInitStatus = B_NO_MEMORY;
89 
90 	if (!U_SUCCESS(error)) {
91 		delete fFormatter;
92 		fInitStatus = B_ERROR;
93 		fFormatter = NULL;
94 	}
95 
96 	return fInitStatus;
97 }
98