use objc2::rc::{DefaultId, Id, Shared};
use objc2::runtime::Object;
use objc2::{msg_send, msg_send_id};
use crate::{
NSCopying, NSDictionary, NSMutableAttributedString, NSMutableCopying, NSObject, NSString,
};
extern_class! {
#[derive(Debug, PartialEq, Eq, Hash)]
unsafe pub struct NSAttributedString: NSObject;
}
unsafe impl Sync for NSAttributedString {}
unsafe impl Send for NSAttributedString {}
pub type NSAttributedStringKey = NSString;
impl NSAttributedString {
unsafe_def_fn! {
pub fn new -> Shared;
}
#[doc(alias = "initWithString:")]
pub fn new_with_attributes(
string: &NSString,
attributes: &NSDictionary<NSAttributedStringKey, Object>,
) -> Id<Self, Shared> {
unsafe {
let obj = msg_send_id![Self::class(), alloc];
msg_send_id![obj, initWithString: string, attributes: attributes].unwrap()
}
}
#[doc(alias = "initWithString:")]
pub fn from_nsstring(string: &NSString) -> Id<Self, Shared> {
unsafe {
let obj = msg_send_id![Self::class(), alloc];
msg_send_id![obj, initWithString: string].unwrap()
}
}
}
impl NSAttributedString {
pub fn string(&self) -> Id<NSString, Shared> {
unsafe { msg_send_id![self, string].unwrap() }
}
#[doc(alias = "length")]
#[allow(unused)]
fn len_utf16(&self) -> usize {
unsafe { msg_send![self, length] }
}
}
impl DefaultId for NSAttributedString {
type Ownership = Shared;
#[inline]
fn default_id() -> Id<Self, Self::Ownership> {
Self::new()
}
}
unsafe impl NSCopying for NSAttributedString {
type Ownership = Shared;
type Output = NSAttributedString;
}
unsafe impl NSMutableCopying for NSAttributedString {
type Output = NSMutableAttributedString;
}
impl alloc::borrow::ToOwned for NSAttributedString {
type Owned = Id<NSAttributedString, Shared>;
fn to_owned(&self) -> Self::Owned {
self.copy()
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use objc2::rc::autoreleasepool;
use super::*;
#[test]
fn test_new() {
let s = NSAttributedString::new();
assert_eq!(&s.string().to_string(), "");
}
#[test]
fn test_string_bound_to_attributed() {
let attr_s = {
let source = NSString::from_str("Hello world!");
NSAttributedString::from_nsstring(&source)
};
let s = autoreleasepool(|_| attr_s.string());
assert_eq!(s.len(), 12);
}
#[test]
fn test_from_nsstring() {
let s = NSAttributedString::from_nsstring(&NSString::from_str("abc"));
assert_eq!(&s.string().to_string(), "abc");
}
#[test]
fn test_copy() {
let s1 = NSAttributedString::from_nsstring(&NSString::from_str("abc"));
let s2 = s1.copy();
assert!(s2.is_kind_of(NSAttributedString::class()));
let s3 = s1.mutable_copy();
assert_ne!(Id::as_ptr(&s1), Id::as_ptr(&s3).cast());
assert!(s3.is_kind_of(NSMutableAttributedString::class()));
}
}