Virtual files

solidstate1991 laszloszeremi at outlook.com
Fri Dec 7 02:24:41 UTC 2018


On Thursday, 6 December 2018 at 16:11:55 UTC, H. S. Teoh wrote:
> There's no need for a separate overload.  All you need to do is:
>
> 	import std.stdio;
> 	auto myfunc(File = std.stdio.File, Args...)(File fp, Args args)
> 	{
> 		...
> 		fp.rawRead(...);
> 		...
> 		fp.rawWrite(...);
> 		... // etc
> 	}
>
> 	// uses std.stdio.File
> 	myfunc(File("realfile.txt", "r"), ...);
>
> 	struct InMemoryFile {
> 		...
> 		void[] rawRead(void[]) { ... }
> 		void rawWrite(void[]) { ... }
> 		...
> 	}
>
> 	// uses InMemoryFile
> 	myfunc(InMemoryFile(...), ...);
>
> As long as the type you pass in has the same API as 
> std.stdio.File (or a subset thereof, as long as that subset is 
> the only thing you use in the called function), the code will 
> work as-is with no additional work.
>
> Writing it this way also makes it easy to test your code 
> without having your unittests pollute the filesystem with 
> temporaries (and needing to clean up the mess afterwards).
>
> If you're concerned about template bloat, you could factor out 
> the common API into an interface, then write a wrapper for 
> std.stdio.File.
>
>
> T

Thanks! It's mostly done except for some testing, which I'll do 
tomorrow.

It has a few extra capabilities (such as reading and writing 
single elements with heap allocation), which I might try to put 
into std.stdio.File too through a pull request.


More information about the Digitalmars-d mailing list