I'm attempting to build a sort of HTTP web server as a learning exercise and I'm having trouble trying to make one of my types iterable using a for loop (by implementing IntoIterator).
So far
I've created a data structure whereby I have a Response object (meant to model a HTTP response), and that contains a Headers object (meant to model the HTTP response headers), and that contains a HashMap<String, String>, representing the actual header values:
use std::collections::HashMap;
struct Headers {
headers: HashMap<String, String>,
}
impl Headers {
pub fn new(headers: HashMap<String, String>) -> Self {
Self { headers }
}
}
struct Response {
headers: Headers,
}
impl Response {
pub fn new(headers: Headers) -> Self {
Self { headers }
}
pub fn headers(&self) -> &Headers {
&self.headers
}
}
Note: The headers method returns an immutable reference because I just want to read the values. I ideally don't want to copy/clone the headers just so that they can be read.
Aim
What I want to be able to do is something like this:
fn main() {
// just creating an example here
let mut headers = HashMap::new();
headers.insert("foo".to_string(), "one".to_string());
headers.insert("bar".to_string(), "two".to_string());
let response = Response::new(Headers::new(headers));
// this is what I'm aiming for:
for (key, value) in response.headers() {
println!("{}: {}", key, value);
}
}
What I've tried
I've tried a whole bunch of things to get this working, but I've so far failed. The closest I've come so far is to implement IntoIterator for &Headers and then call into_iter() on the hash map:
impl IntoIterator for &Headers {
type Item = (String, String);
type IntoIter = IntoIter<String, String>;
fn into_iter(self) -> Self::IntoIter {
self.headers.into_iter()
}
}
However, this results in an error:
cannot move out of self.headers which is behind a shared reference
I've tried searching around and found numerous StackOverflow questions that are similar, but none of them seem to answer my exact question.
Thanks.
What you're doing right now is delegating to the IntoIterator implementation of HashMap<String, String>. But you need to delegate to the IntoIterator implementation of &HashMap<String, String> because you can't get at an owned version of self.headers when self is a reference.
This is an easy fix though, thankfully:
// Just giving this type a concise name so we can reference it easyily later
type HeaderMap = HashMap<String, String>;
impl<'h> IntoIterator for &'h Headers {
// Here we just tell Rust to use the types we're delegating to.
// This is just (&'h String, &'h String)
type Item = <&'h HeaderMap as IntoIterator>::Item;
type IntoIter = <&'h HeaderMap as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
// Now just call `into_iter` on the correct thing
(&self.headers).into_iter()
// self.headers.iter() would work just as well here
}
}
Related
I have a struct that has a field that is a BTreeMap whose value is another struct that implements From<&[u8]>
MyStruct {
...
btree: BTreeMap<String, MyOtherStruct>
...
}
MyOtherStruct implements From<&[u8]> because i'm recovering it from a file.
impl From<&[u8]> for OtherMyStruct {
fn from(stream: &[u8]) -> Self {
...
}
}
I read the file that has a list of MyOtherStruct, and I have a function that parses the stream and returns an array of streams, which represents the streams of each struct MyOtherStruct
fn read_file(path: &PathBuf) -> Vec<u8> {
....
}
fn find_streams(stream: &[u8]) -> Vec<&[u8]> {
....
}
Then to build MyStruct, I take the array of streams and for each stream I create MyOtherStruct from the stream
fn main() {
let file_content = read_file(PathBuf::from("path"));
let streams = find_streams(&file_content);
let mut my_other_structs = BTreeMap::<String, MyOtherStruct>::new();
// here is where i collect my items
streams.iter().for_each(|s| {
let item = MyOtherStruct::from(*s);
my_other_structs.insert(String::from("some key"), item);
});
....
....
}
The question is in the part where I collect my items. Before using a for_each I used a map but the compiler gave me an error that said the trait 'FromIterator<IndexEntry>' is not implemented for 'BTreeMap<std::string::String, IndexEntry>'.
Of course I understand what the compiler error refers to, so I copied the signature of the trait I needed, pasted it into the editor and implemented it.
impl FromIterator<MyOtherStruct> for BTreeMap<String, MyOtherStruct> {
fn from_iter<T: IntoIterator<Item = MyOtherStruct>>(iter: T) -> Self {
let mut btree = BTreeMap::new();
iter.into_iter().for_each(|e| {
btree.insert(String::from("some key"), e);
});
btree
}
}
so, then instead of doing it this way
let mut my_other_structs = BTreeMap::<String, MyOtherStruct>::new();
streams.iter().for_each(|s| {
let item = MyOtherStruct::from(*s);
my_other_structs.insert(String::from("some key"), item);
});
it looked something like this
let my_other_structs = streams.iter()
.map(|s| MyOtherStruct::from(*s) )
.collect();
My question is, beyond cosmetics, is there any significant difference in the way things look on the back end? When assembling my BTreeMap one way or the other.
I mean I love how it looks when I do it with the FromIterator and just use a .map where I need it, but internally I do a for_each and it's the same thing I'm doing the other way without augmenting a .map on top of it.
so is there any relevant difference in this case?
map().collect() is more idiomatic for a couple of reasons. For one a simple for loop is recommended over the use of for_each by it's own documentation unless it makes the code possible or more readable.
The second and more important reason is .collect() can and will use size hints of the iterator where it can and preallocate the storage needed, so it will perform as good or better than for_each(insert).
Your FromIterator<MyOtherStruct> implementation could also be streamlined using the existing impl<K, V> FromIterator<(K, V)> for HashMap<K, V> like this:
impl FromIterator<MyOtherStruct> for BTreeMap<String, MyOtherStruct> {
fn from_iter<T: IntoIterator<Item = MyOtherStruct>>(iter: T) -> Self {
iter.into_iter()
.map(|e| (String::from("some key"), e))
.collect()
}
}
Or depending on your actual uses just do that directly instead of implementing FromIterator in the first place.
I'm trying to access an api, where I can specify what kind of fields I want included in the result. (for example "basic", "advanced", "irrelevant"
the Rust Struct to represent that would look something like
Values {
a: Option<String>;
b: Option<String>;
c: Option<String>;
d: Option<String>;
}
or probably better:
Values {
a: Option<Basic>; // With field a
b: Option<Advanced>; // With fields b,c
c: Option<Irrelevant>; // With field d
}
Using this is possible, but I'd love to reduce the handling of Option for the caller.
Is it possible to leverage the type system to simplify the usage? (Or any other way I'm not realizing?)
My idea was something in this direction, but I think that might not be possible with rust (at least without macros):
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=093bdf1853978af61443d547082576ca
struct Values {
a: Option<&'static str>,
b: Option<&'static str>,
c: Option<&'static str>,
}
trait ValueTraits{}
impl ValueTraits for dyn Basic{}
impl ValueTraits for dyn Advanced{}
impl ValueTraits for Values{}
trait Basic {
fn a(&self) -> &'static str;
}
trait Advanced {
fn b(&self) -> &'static str;
fn c(&self) -> &'static str;
}
impl Basic for Values {
fn a(&self) -> &'static str {
self.a.unwrap()
}
}
impl Advanced for Values {
fn b(&self) -> &'static str {
self.b.unwrap()
}
fn c(&self) -> &'static str {
self.c.unwrap()
}
}
//Something like this is probably not possible, as far as I understand Rust
fn get_values<T1, T2>() -> T1 + T2{
Values {
a: "A",
b: "B",
c: "C"
}
}
fn main() {
let values = get_values::<Basic, Advanced>();
println!("{}, {}, {}", values.a(), values.b(), values.c());
}
Clarifications (Edit)
The Values struct contains deserialized json data from the api I called. I can request groups of fields to be included in the response(1-n requested fields groups), the fields are of different types.
If I knew beforehand, which of those fields are returned, I wouldn't need them to be Option, but as the caller decides which fields are returned, the fields needs to be Option (either directly, or grouped by the field groups)
There are too many possible combinations to create a struct for each of those.
I fully realize that this cannot work, it was just "peudorust":
fn get_values<T1, T2>() -> T1 + T2{
Values {
a: "A",
b: "B",
c: "C"
}
}
But my thought process was:
In theory, I could request the field groups via generics, so I could create a "dynamic" type, that implements these traits, because I know which traits are requested.
The Traits are supposed to act like a "view" into the actual struct, because if they are requested beforehand, I know I should request them from the api to include them in the Struct.
My knowledge of generics and traits isn't enough to confidently say "this isn't possible at all" and I couldn't find a conclusive answer before I asked here.
Sorry for the initial question not being clear of what the actual issue was, I hope the clarification helps with that.
I can't quite gauge whether or not you want to be able to request and return fields of multiple different types from the question. But if all the information being returned is of a single type you could try using a HashMap:
use std::collections::HashMap;
fn get_values(fields: &[&'static str]) -> HashMap<&'static str, &'static str> {
let mut selected = HashMap::new();
for field in fields {
let val = match *field {
"a" => "Value of a",
"b" => "Value of b",
"c" => "Value of c",
// Skip requested fields that don't exist.
_ => continue,
};
selected.insert(*field, val);
}
selected
}
fn main() {
let fields = ["a","c"];
let values = get_values(&fields);
for (field, value) in values.iter() {
println!("`{}` = `{}`", field, value);
}
}
Additionally you've given me the impression that you haven't quite been able to form a relationship between generics and traits yet. I highly recommend reading over the book's "Generic Types, Traits, and Lifetimes" section.
The gist of it is that generics exist to generalize a function, struct, enum, or even a trait to any type, and traits are used to assign behaviour to a type. Traits cannot be passed as a generic parameter, because traits are not types, they are behaviours. Which is why doing: get_values::<Basic, Advanced>(); doesn't work. Basic and Advanced are both traits, not types.
If you want practice with generics try generalizing get_values so that it can accept any type which can be converted into an iterator that yields &'static strs.
Edit:
The clarification is appreciated. The approach you have in mind is possible, but I wouldn't recommend it because it's implementing it is extremely verbose and will panic the moment the format of the json you're parsing changes. Though if you really need to use traits for some reason you could try something like this:
// One possible construct returned to you.
struct All {
a: Option<i32>,
b: Option<i32>,
c: Option<i32>,
}
// A variation that only returned b and c
struct Bc {
b: Option<i32>,
c: Option<i32>,
}
// impl Advanced + Basic + Default for All {...}
// impl Advanced + Default for Bc {...}
fn get_bc<T: Advanced + Default>() -> T {
// Here you would set the fields on T.
Default::default()
}
fn get_all<T: Basic + Advanced + Default>() -> T {
Default::default()
}
fn main() {
// This isn't really useful unless you want to create multiple structs that
// are supposed to hold b and c but otherwise have different fields.
let bc = get_bc::<Bc>();
let all = get_all::<All>();
// Could also do something like:
let bc = get_bc::<All>();
// but that could get confusing.
}
I think the above is how you're looking to solve your problem. Though if you can, I would still recommend using a HashMap with a trait object like this:
use std::collections::HashMap;
use std::fmt::Debug;
// Here define the behaviour you need to interact with the data. In this case
// it's just ability to print to console.
trait Value: Debug {}
impl Value for &'static str {}
impl Value for i32 {}
impl<T: Debug> Value for Vec<T> {}
fn get_values(fields: &[&'static str]) -> HashMap<&'static str, Box<dyn Value>> {
let mut selected = HashMap::new();
for field in fields {
let val = match *field {
"a" => Box::new("Value of a") as Box<dyn Value>,
"b" => Box::new(2) as Box<dyn Value>,
"c" => Box::new(vec![1,3,5,7]) as Box<dyn Value>,
// Skip requested fields that don't exist.
_ => continue,
};
selected.insert(*field, val);
}
selected
}
fn main() {
let fields = ["a","c"];
let values = get_values(&fields);
for (field, value) in values.iter() {
println!("`{}` = `{:?}`", field, value);
}
}
This question is written for Yew v0.19
Asynchronous foreign JavaScript functions can be used in Rust through Closures, as the function to pass-in:
#[wasm_bindgen]
extern "C" {
fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
}
// ...
let cb = Closure::new(|| {
log("interval elapsed!");
});
let interval_id = setInterval(&cb, 1_000);
This is nice for a pedantic examples, but Closures have a critical requirement - the function applied needs to have a 'static lifetime. Likewise, with Yew applications, a perfect mechanism for spontaneous response is the Message enum, and having it update() the Model. However, the link() mechanism in Context (which issues messages) does not have a static lifetime.
In an ideal world, the value submitted to the closure could just be applied as a Yew component message:
struct Model {
thing: Option<JsValue>,
}
enum Msg {
GotThing(JsValue),
}
#[wasm_bindgen]
extern "C" {
fn createThing(closure: &Closure<dyn FnMut(JsValue) -> ());
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Model {
thing: None, // initial value
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::GotThing(x) => { // handle the message
self.thing = Some(x);
true
},
}
}
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
if first_render {
let cb: Box<dyn FnMut(JsValue) -> ()> = Box::new(|x| {
// try and issue the message
ctx.link().send_message(Msg::GotThing(x));
// ^ doesn't have a `'static` lifetime! Won't compile
});
createThing(Closure::wrap(&cb));
}
}
// fn view() ... omitted, not relevant
}
I'm wondering if there's a way to convert a Callback into a Closure, or if there's a better, more canonical way to do this, to please correct me.
Another idea I had would use some kind of queue defined statically (which wouldn't be safe as it's a mutable static variable), but then it could be used as an intermediary data type between the Closure passed to createThing, and messages could be dispatched within the component.
Maybe there's an external way to interact with a Yew component that I'm overlooking? I'm not sure how to resolve this issue. What would be the most correct way to achieve this goal?
I'm new to rust and am currently rewriting some of my old java code in it. It's my first time not programming in OOP so this is strange and new to me.
I'm having some problems understanding how to implement a different method (with the same name) to each instance of a struct. In essence I'm trying to achieve behavior similar to abstract Class, extends, #override in Java.
Perhaps this example is better at explaining what exactly I'm trying to do. In it I try to implement different execute() logic to each instance of AbstractNode.
Create a struct called "AbstractNode" that holds some data and has 3 methods associated with it (validate(), log(), execute())
struct AbstractNode {
pub data: //data here
pub validate: bool,
pub log: String,
}
trait NodeFunctions {
fn validate(&self)->bool{false}
fn log(&self){println!("/")}
fn execute(&self){}
}
impl NodeFunctions for AbstractNode{
fn validate(&self)->bool{
self.validate
}
fn log(&self){
println!("{}/", self.log);
}
fn execute(&self){
//--this function is the problem, because I don't want its behavior to be
//shared between all instances of Abstract node--
}
}
I then instantiate several nodes. If possible I would also like to define the body of the execute() somewhere in here.
let node1 = AbstractNode{
data: //data
validate: false,
log: "node1".to_string(),
};
let node2 = AbstractNode{
data: //data
validate: 1>0,
log: "node2".to_string(),
};
let node3 = AbstractNode{
data: //data
validate: true,
log: "node3".to_string(),
};
//...
It is called from main like so. If the condition in validate() is true first the log() method is executed, which is the same for all nodes. Then the execute() which is not the same for all nodes.
fn main(){
let mut node_tree = vec![
node1,
node2,
node3
//...
];
for node in node_tree.iter() {
if node.validate(){
node.log();
node.execute(); //<--
break;
}
};
}
Each node should be able to hold different logic under the execute() method and I don't know how I could define this specific behavior.
I hope this question is clear enough. If you don't understand what I'm traying to achieve, please ask additional questions.
Ty in advance.
You could somewhat replicate it using closures. However, you'll still end up with parts that can't be generic per Node if you also want to be able to mutate it within the closure.
I've renamed and removed some parts, to simplify the examples.
First, you'll need a NodeData type, which holds your data. I'm assuming you want to be able to mutate it within the "execute" method. Then you'll need a Node type, which holds the data, along with the boxed closure for that Node instance.
struct NodeData {}
struct Node {
data: NodeData,
f: Box<dyn Fn(&mut NodeData)>,
}
Then we'll implement a method for creating a Node instance, along with the execute method that calls the closure.
This is where the limitation of using closures appears. You cannot pass it a mutable reference to the Node itself. Because the Node becomes borrowed when you access self.f to call the closure.
impl Node {
fn with<F>(f: F) -> Self
where
F: Fn(&mut NodeData) + 'static,
{
Self {
data: NodeData {},
f: Box::new(f),
}
}
fn execute(&mut self) {
(self.f)(&mut self.data);
}
}
An example of using it would then look like this:
let mut nodes: Vec<Node> = vec![];
nodes.push(Node::with(|_node_data| {
println!("I'm a node");
}));
nodes.push(Node::with(|_node_data| {
println!("I'm another node");
}));
nodes.push(Node::with(|_node_data| {
println!("I'm also a node");
}));
for node in &mut nodes {
node.execute();
}
Now, again this works. But NodeData cannot be generic, as then modifying the data in the closure becomes increasingly difficult.
Of course you could defer to having the NodeData be a HashMap, and that way you can store anything with a String key and some enum value.
While you didn't want to have separate types. This does somewhat make it easier, as all node types can have different kinds of data.
Because now we can have a single trait Node which has the execute method.
trait Node {
fn execute(&mut self);
}
Now define multiple types and implement Node for each of them. Again, the two good things of using a trait instead of closure is:
Every node you define, can contain any kind of data you'd like
In this case execute will actually be able to modify Self, which the closure solution cannot.
struct NodeA {}
struct NodeB {}
struct NodeC {}
impl Node for NodeA {
fn execute(&mut self) {
println!("I'm a node");
}
}
impl Node for NodeB {
fn execute(&mut self) {
println!("I'm another node");
}
}
impl Node for NodeC {
fn execute(&mut self) {
println!("I'm also a node");
}
}
You can still have a single Vec of nodes as the traits can easily be boxed.
let mut nodes: Vec<Box<dyn Node>> = vec![];
nodes.push(Box::new(NodeA {}));
nodes.push(Box::new(NodeB {}));
nodes.push(Box::new(NodeC {}));
for node in &mut nodes {
node.execute();
}
You could have AbstractNode store a closure that takes a reference to Self:
struct AbstractNode {
pub validate: bool,
pub log: String,
pub executor: Box<dyn Fn(&Self)>
}
The NodeFunctions implementation for AbstractNode would simply call the executor closure:
impl NodeFunctions for AbstractNode {
fn execute(&self) {
(self.executor)(&self)
}
// ...
}
Now, everytime you create a new instance of an AbstractNode, you can have a custom executor function. The executor takes a reference to self and can therefore access the node's data:
let node1 = AbstractNode {
validate: false,
log: "node1".to_string(),
executor: Box::new(|n| println!("Executing node #1. Is Valid? {}", n.validate))
};
// => Executing node #1. Is Valid? true
I have a struct Folder. I have a method called contents. I want that method to return an object that supports IntoIterator so that the caller can just go
for x in folder.contents(){
...
}
The Item type is (since this is what the hashmap iterator returns - see a little lower)
(&OsString, &FileOrFolder)
where FileOrFolder is an enum
enum FileOrFolder{
File(File),
Folder(Folder)
}
The iterator itself needs to first enumerate a HashMap<OSString, FileOrFolder> owned by the folder and then second, enumerate a Vec<File>. The Vec of files is created on the fly by the contents fn or by the IntoIterator call, whatever works. I tried simply using chain but quickly realized that wasn't going to work. So my rough sketch of what I am trying to do is this:
// the iterator
pub struct FFIter {
files: Vec<FileOrFolder>,
files_iter:Box<dyn Iterator<Item=FileOrFolder>>,
dirs: Box<dyn Iterator<Item = (&OsString, &FileOrFolder)>>,
dirs_done:bool
}
// the thing returned by the contents fn
struct FolderContents{
folder:&Folder
}
// make it iterable
impl IntoIterator for FolderContents {
type Item =(&OsString, &FileOrFolder);
type IntoIter = FFIter;
fn into_iter(self) -> Self::IntoIter {
let files = self.folder.make_the_files()
FFIter {
files: files, // to keep files 'alive'
files_iter: files.iter(),
dirs: Box::new(self.hashmap.iter()),
dirs_done:false
}
}
}
impl Iterator for FFIter {
type Item = (&OsString, &FileOrFolder);
fn next(&mut self) -> Option<(&OsString, &FileOrFolder)> {
None // return empty, lets just get the skeleton built
}
}
impl Folder{
pub fn contents(&self) -> FolderContents{
FolderContents{folder:&self}
}
}
I know this is full of errors, but I need to know if this is doable at all. As you can see I am not even trying to write the code that returns anything. I am just trying to get the basic outline to compile.
I started arm wrestling with the lifetime system and got to the point where I had this
error[E0658]: generic associated types are unstable
--> src\state\files\file_or_folder.rs:46:5
|
46 | type Item<'a> =(&'a OsString, &'a FileOrFolder);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: see issue #44265 <https://github.com/rust-lang/rust/issues/44265> for more information
Which kinda sucked as that is what the compiler said I should do.
I am happy to keep ploughing away at this following the suggestions from the compiler / reading / ... But in the past I have posted a question along these lines and been told - 'of course it can't be done'. So should I be able to make this work?
The Folder type is not Copy and expensive to clone. The File type is simple (string and i64), Copy and Clone
I know I could simply make the caller call two different iterations and merge them, but I am trying to write a transparent replacement module to drop into a large existing codebase.
If somebody says that chain() should work that's great, I will have another go at that.
EDIT Jmp said chain should work,
heres what I tried
pub fn contents(&self) -> Box<dyn Iterator<Item = (&OsString, &FileOrFolder)> + '_> {
let mut files = vec![];
if self.load_done {
for entry in WalkDir::new(&self.full_path)
.max_depth(1)
.skip_hidden(false)
.follow_links(false)
.into_iter()
{
let ent = entry.unwrap();
if ent.file_type().is_file() {
if let Some(name) = ent.path().file_name() {
files.push((
name.to_os_string(),
FileOrFolder::File(File {
name: name.to_os_string(),
size: ent.metadata().unwrap().len() as u128,
}),
));
}
}
}
};
Box::new(
self.contents
.iter()
.map(|(k, v)| (k, v))
.chain(files.iter().map(|x| (&x.0, &x.1))),
)
}
but the compiler complains, correctly, that 'files' get destroyed at the end of the call. What I need is for the vec to be held by the iterator and then dropped at the end of the iteration. Folder itself cannot hold the files - the whole point here is to populate files on the fly, its too expensive, memory wise to hold them.
You claim that files is populated on the fly, but that's precisely what your code is not doing: your code precomputes files before attempting to return it. The solution is to really compute files on the fly, something like this:
pub fn contents(&self) -> Box<dyn Iterator<Item = (&OsString, &FileOrFolder)> + '_> {
let files = WalkDir::new(&self.full_path)
.max_depth(1)
.skip_hidden(false)
.follow_links(false)
.into_iter()
.filter_map (|entry| {
let ent = entry.unwrap;
if ent.file_type().is_file() {
if let Some(name) = ent.path().file_name() {
Some((
name.to_os_string(),
FileOrFolder::File(File {
name: name.to_os_string(),
size: ent.metadata().unwrap().len() as u128,
}),
))
} else None
} else None
});
self.contents
.iter()
.chain (files)
}
Since you haven't given us an MRE, I haven't tested the above, but I think it will fail because self.contents.iter() returns references, whereas files returns owned values. Fixing this requires changing the prototype of the function to return some form of owned values since files cannot be made to return references. I see two ways to do this:
Easiest is to make FileOrFolder clonable and get rid of the references in the prototype:
pub fn contents(&self) -> Box<dyn Iterator<Item = (OsString, FileOrFolder)> + '_> {
let files = ...;
self.contents
.iter()
.cloned()
.chain (files)
Or you can make a wrapper type similar to Cow than can hold either a reference or an owned value:
enum OwnedOrRef<'a, T> {
Owned (T),
Ref (&'a T),
}
pub fn contents(&self) -> Box<dyn Iterator<Item = (OwnedOrRef::<OsString>, OwnedOrRef::<FileOrFolder>)> + '_> {
let files = ...;
self.contents
.iter()
.map (|(k, v)| (OwnedOrRef::Ref (k), OwnedOrRef::Ref (v))
.chain (files
.map (|(k, v)| (OwnedOrRef::Owned (k),
OwnedOrRef::Owned (v)))
}
You can even use Cow if FileOrFolder can implement ToOwned.