1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef META_API_OBJECT_NAME_H
16 #define META_API_OBJECT_NAME_H
17
18 #include <meta/base/interface_traits.h>
19 #include <meta/interface/intf_attach.h>
20 #include <meta/interface/intf_container.h>
21 #include <meta/interface/intf_named.h>
22 #include <meta/interface/intf_object.h>
23
META_BEGIN_NAMESPACE()24 META_BEGIN_NAMESPACE()
25
26 template<typename Interface, typename = BASE_NS::enable_if<IsKindOfPointer_v<Interface>>>
27 BASE_NS::string GetName(const Interface& obj)
28 {
29 if (auto o = interface_pointer_cast<IObject>(obj)) {
30 return o->GetName();
31 }
32 // in case we are not an object but implement INamed
33 if (auto named = interface_pointer_cast<INamed>(obj)) {
34 return META_NS::GetValue(named->Name());
35 }
36 return "";
37 }
38
GetObjectNameAttachment(const IAttach::ConstPtr & att)39 inline IObjectName::Ptr GetObjectNameAttachment(const IAttach::ConstPtr& att)
40 {
41 if (auto cont = att->GetAttachmentContainer(false)) {
42 auto res = cont->FindAny({ "", TraversalType::NO_HIERARCHY, { IObjectName::UID }, false });
43 if (auto oname = interface_pointer_cast<IObjectName>(res)) {
44 return oname;
45 }
46 }
47 return nullptr;
48 }
49
50 template<typename Interface, typename = BASE_NS::enable_if<IsKindOfPointer_v<Interface>>>
SetName(const Interface & obj,BASE_NS::string_view name)51 bool SetName(const Interface& obj, BASE_NS::string_view name)
52 {
53 if (auto named = interface_pointer_cast<INamed>(obj)) {
54 META_NS::SetValue(named->Name(), BASE_NS::string(name));
55 return true;
56 }
57 if (auto att = interface_pointer_cast<IAttach>(obj)) {
58 if (auto oname = GetObjectNameAttachment(att)) {
59 return oname->SetName(name);
60 } else {
61 oname = GetObjectRegistry().Create<IObjectName>(ClassId::ObjectName);
62 if (oname && oname->SetName(name)) {
63 return att->Attach(oname);
64 }
65 }
66 }
67 return false;
68 }
69
70 META_END_NAMESPACE()
71
72 #endif
73