11use alloc:: collections:: BTreeMap ;
22use alloc:: sync:: { Arc , Weak } ;
33use alloc:: { string:: String , vec:: Vec } ;
4-
4+ use crate :: alloc :: string :: ToString ;
55use axfs_vfs:: { VfsDirEntry , VfsNodeAttr , VfsNodeOps , VfsNodeRef , VfsNodeType } ;
66use axfs_vfs:: { VfsError , VfsResult } ;
77use spin:: RwLock ;
@@ -14,7 +14,9 @@ use crate::file::FileNode;
1414pub struct DirNode {
1515 this : Weak < DirNode > ,
1616 parent : RwLock < Weak < dyn VfsNodeOps > > ,
17- children : RwLock < BTreeMap < String , VfsNodeRef > > ,
17+ children : RwLock < BTreeMap < String , VfsNodeRef > > , //目录项表
18+ // ↑文件名 ↑文件实体(相当于inode的抽象
19+ //BTreeMap数据结构相当于一个map 存键值对 但是将键值对插到平衡二叉树 内部是有序的并且迭代的时候按照键的顺序
1820}
1921
2022impl DirNode {
@@ -67,6 +69,27 @@ impl DirNode {
6769 children. remove ( name) ;
6870 Ok ( ( ) )
6971 }
72+ fn rename_in_same_dir ( & self , old_name : & str , new_name : & str ) -> VfsResult {
73+ log:: error!( "[dir] call rename_in_same_dir oldname:{},newname:{}" , old_name, new_name) ;
74+ let mut children = self . children . write ( ) ; // Rwlock是读写锁 通过.write() 获取写锁
75+ //可以有多个读锁(共享) 或者有一个写锁(独占) 但不能同时有读锁和写锁
76+ // 现在可以安全地修改 children...
77+ log:: error!( "[dir] getting node" ) ;
78+ let node=children. get ( old_name) . ok_or ( VfsError :: NotFound ) ?. clone ( ) ; //找到old_name对应inode
79+ //get是通过键查找值 返回option ok_or(E)将option<T>转化为Result<T,E>
80+ // ?操作符可以跟在option或者result后面 成功了就解包 失败了就提前返回
81+ // 检查目标是否已存在
82+ if children. contains_key ( new_name) {
83+ return Err ( VfsError :: AlreadyExists ) ;
84+ }
85+ // 关键操作:修改名称映射,不复制数据!
86+ children. remove ( old_name) ;
87+ children. insert ( new_name. to_string ( ) , node) ; // 同一个 node 对象!
88+
89+ log:: error!( "[dir] complete rename in same dir!" ) ;
90+ // VfsResult的定义 等价于:type VfsResult<T> = Result<T, VfsError>;
91+ Ok ( ( ) )
92+ }
7093}
7194
7295impl VfsNodeOps for DirNode {
@@ -164,11 +187,22 @@ impl VfsNodeOps for DirNode {
164187 self . remove_node ( name)
165188 }
166189 }
167-
168- axfs_vfs:: impl_vfs_dir_default! { }
190+
191+ fn rename ( & self , src_path : & str , dst_path : & str ) ->VfsResult {
192+ log:: error!( "[dir] call rename" ) ;
193+ //现在先实现只支持在同一目录下重命名
194+ let ( src_name, src_rest) = split_path ( src_path) ;
195+ let ( dst_dir, dst_rest) =split_path ( dst_path) ;
196+ let dst_rest=dst_rest. unwrap ( ) ;
197+ //
198+
199+ self . rename_in_same_dir ( src_name, dst_rest)
200+ }
201+ axfs_vfs:: impl_vfs_dir_default! { } //提供了其他方法的默认实现
202+ //经过查cargo.lock 发现axfs_vfs是外部依赖
169203}
170204
171- fn split_path ( path : & str ) -> ( & str , Option < & str > ) {
205+ fn split_path ( path : & str ) -> ( & str , Option < & str > ) { //去掉开头的/ 再以中间的第一个/进行切分
172206 let trimmed_path = path. trim_start_matches ( '/' ) ;
173207 trimmed_path. find ( '/' ) . map_or ( ( trimmed_path, None ) , |n| {
174208 ( & trimmed_path[ ..n] , Some ( & trimmed_path[ n + 1 ..] ) )
0 commit comments