@@ -54,6 +54,21 @@ impl ODataId {
5454 pub fn service_root ( ) -> Self {
5555 Self ( "/redfish/v1" . into ( ) )
5656 }
57+
58+ /// Last segment of `ODataId`.
59+ ///
60+ /// "/redfish/v1/Systems/1" -> Some("1")
61+ /// "/redfish/v1/Systems/1/" -> Some("1")
62+ /// "redfish" -> Some("redfish")
63+ /// "" -> None
64+ /// "/" -> None
65+ #[ must_use]
66+ pub fn last_segment ( & self ) -> Option < & str > {
67+ let path = self . 0 . trim_end_matches ( '/' ) ;
68+ path. rsplit_once ( '/' )
69+ . map ( |( _, v) | v)
70+ . or_else ( || ( !path. is_empty ( ) ) . then_some ( path) )
71+ }
5772}
5873
5974impl From < String > for ODataId {
@@ -109,3 +124,67 @@ impl ODataType<'_> {
109124 } )
110125 }
111126}
127+
128+ #[ cfg( test) ]
129+ mod tests {
130+ use super :: ODataId ;
131+
132+ #[ test]
133+ fn last_segment_returns_last_path_segment ( ) {
134+ let id = ODataId ( "/redfish/v1/Systems/1" . into ( ) ) ;
135+ assert_eq ! ( id. last_segment( ) , Some ( "1" ) ) ;
136+ }
137+
138+ #[ test]
139+ fn last_segment_ignores_trailing_slash ( ) {
140+ let id = ODataId ( "/redfish/v1/Systems/1/" . into ( ) ) ;
141+ assert_eq ! ( id. last_segment( ) , Some ( "1" ) ) ;
142+ }
143+
144+ #[ test]
145+ fn last_segment_handles_multiple_trailing_slashes ( ) {
146+ let id = ODataId ( "/redfish/v1/Systems/1///" . into ( ) ) ;
147+ assert_eq ! ( id. last_segment( ) , Some ( "1" ) ) ;
148+ }
149+
150+ #[ test]
151+ fn last_segment_returns_none_for_empty_string ( ) {
152+ let id = ODataId ( "" . into ( ) ) ;
153+ assert_eq ! ( id. last_segment( ) , None ) ;
154+ }
155+
156+ #[ test]
157+ fn last_segment_returns_none_for_root_path ( ) {
158+ let id = ODataId ( "/" . into ( ) ) ;
159+ assert_eq ! ( id. last_segment( ) , None ) ;
160+ }
161+
162+ #[ test]
163+ fn last_segment_returns_none_for_multiple_root_slashes ( ) {
164+ let id = ODataId ( "///" . into ( ) ) ;
165+ assert_eq ! ( id. last_segment( ) , None ) ;
166+ }
167+
168+ #[ test]
169+ fn last_segment_returns_segment_for_single_component_relative_path ( ) {
170+ let id = ODataId ( "redfish" . into ( ) ) ;
171+ assert_eq ! ( id. last_segment( ) , Some ( "redfish" ) ) ;
172+ }
173+
174+ #[ test]
175+ fn last_segment_returns_last_segment_for_relative_path ( ) {
176+ let id = ODataId ( "redfish/v1/Systems/1" . into ( ) ) ;
177+ assert_eq ! ( id. last_segment( ) , Some ( "1" ) ) ;
178+ }
179+
180+ #[ test]
181+ fn last_segment_handles_leading_slash_before_single_segment ( ) {
182+ let id = ODataId ( "/redfish" . into ( ) ) ;
183+ assert_eq ! ( id. last_segment( ) , Some ( "redfish" ) ) ;
184+ }
185+
186+ #[ test]
187+ fn service_root_last_segment_is_v1 ( ) {
188+ assert_eq ! ( ODataId :: service_root( ) . last_segment( ) , Some ( "v1" ) ) ;
189+ }
190+ }
0 commit comments