blob: 7775fdcbd9d2d7fd4883b9e37dfe4946582e4ce0 [file] [log] [blame]
hjonaa32c3e2015-12-13 19:58:11 -08001/*
2 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090011#import "NSString+RTCStdString.h"
hjonaa32c3e2015-12-13 19:58:11 -080012
Ali Tofigh6364d082022-03-14 13:32:04 +010013#include "absl/strings/string_view.h"
14
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090015@implementation NSString (RTCStdString)
hjonaa32c3e2015-12-13 19:58:11 -080016
17- (std::string)stdString {
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090018 return [NSString rtc_stdStringForString:self];
hjonaa32c3e2015-12-13 19:58:11 -080019}
20
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090021+ (std::string)rtc_stdStringForString:(NSString *)nsString {
hjonaa32c3e2015-12-13 19:58:11 -080022 NSData *charData = [nsString dataUsingEncoding:NSUTF8StringEncoding];
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090023 return std::string(reinterpret_cast<const char *>(charData.bytes), charData.length);
hjonaa32c3e2015-12-13 19:58:11 -080024}
25
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090026+ (NSString *)rtc_stringForStdString:(const std::string &)stdString {
Jon Hjelle29d5e572016-01-06 11:49:11 -080027 // std::string may contain null termination character so we construct
28 // using length.
29 return [[NSString alloc] initWithBytes:stdString.data()
30 length:stdString.length()
31 encoding:NSUTF8StringEncoding];
32}
33
hjonaa32c3e2015-12-13 19:58:11 -080034@end
Ali Tofigh6364d082022-03-14 13:32:04 +010035
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090036@implementation NSString (RTCAbslStringView)
Ali Tofigh6364d082022-03-14 13:32:04 +010037
Byoungchan Lee181ea6e2022-05-13 19:02:07 +090038+ (NSString *)rtc_stringForAbslStringView:(const absl::string_view)abslStringView {
Ali Tofigh6364d082022-03-14 13:32:04 +010039 return [[NSString alloc] initWithBytes:abslStringView.data()
40 length:abslStringView.length()
41 encoding:NSUTF8StringEncoding];
42}
43
44@end