blob: a0d38142819bad2e5984231f005e1098dec1257c [file] [log] [blame]
Davide Pesavento5ee8ec02018-09-01 19:06:12 -04001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2013-2018 Regents of the University of California.
4 *
5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6 *
7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8 * terms of the GNU Lesser General Public License as published by the Free Software
9 * Foundation, either version 3 of the License, or (at your option) any later version.
10 *
11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14 *
15 * You should have received copies of the GNU General Public License and GNU Lesser
16 * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17 * <http://www.gnu.org/licenses/>.
18 *
19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20 */
21
22#include "cf-string-osx.hpp"
23
24namespace ndn {
25namespace util {
26namespace cfstring {
27
28CFReleaser<CFStringRef>
29fromBuffer(const uint8_t* buf, size_t buflen)
30{
31 CFStringRef cfStr = CFStringCreateWithBytes(kCFAllocatorDefault, buf, buflen, kCFStringEncodingUTF8, false);
32 if (cfStr == nullptr) {
33 BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create CFString from buffer"));
34 }
35 return cfStr;
36}
37
38CFReleaser<CFStringRef>
39fromStdString(const std::string& str)
40{
41 CFStringRef cfStr = CFStringCreateWithCString(kCFAllocatorDefault, str.data(), kCFStringEncodingUTF8);
42 if (cfStr == nullptr) {
43 BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create CFString from std::string"));
44 }
45 return cfStr;
46}
47
48std::string
49toStdString(CFStringRef cfStr)
50{
51 const char* cStr = CFStringGetCStringPtr(cfStr, kCFStringEncodingUTF8);
52 if (cStr != nullptr) {
53 // fast path
54 return cStr;
55 }
56
57 // reserve space for the string + null terminator
58 std::string str(CFStringGetLength(cfStr) + 1, '\0');
59 // copy the CFString into the std::string buffer
60 if (!CFStringGetCString(cfStr, &str.front(), str.size(), kCFStringEncodingUTF8)) {
61 BOOST_THROW_EXCEPTION(std::runtime_error("CFString to std::string conversion failed"));
62 }
63 // drop the null terminator, std::string doesn't need it
64 str.pop_back();
65
66 return str;
67}
68
69} // namespace cfstring
70} // namespace util
71} // namespace ndn