| 1 |
function SM = StreamMaker() |
| 2 |
% StreamMaker (Factory for fie/input/output Streams) |
| 3 |
% |
| 4 |
% A StreamMaker can make Stream PseudoObjects based on either |
| 5 |
% an "fid" or "filename" (and extra arguments for `fopen`). |
| 6 |
% The StreamMaker also contains a method `isStream` to validate whether |
| 7 |
% the value passed is a valid stream specifier. |
| 8 |
% |
| 9 |
% Usage |
| 10 |
% |
| 11 |
% SM = StreamMaker; |
| 12 |
% |
| 13 |
% Stream = SM.make(fid) |
| 14 |
% Stream = SM.make(filename, ...) |
| 15 |
% |
| 16 |
% This returns a PseudoObject Stream with the following properties: |
| 17 |
% - name: (file) name of the stream |
| 18 |
% - fid: handle (fid) of the stream |
| 19 |
% |
| 20 |
% and methods: |
| 21 |
% - print: prints to the stream, i.e. fprintf |
| 22 |
% - close: closes the stream, i.e. fclose |
| 23 |
% |
| 24 |
% It may also contain a field to automatically close the Stream when it goes |
| 25 |
% out of scope. |
| 26 |
% |
| 27 |
SM = PseudoObject('StreamMaker', ... |
| 28 |
'isStream', @isStream, ... |
| 29 |
'make', @constructStream); |
| 30 |
end |
| 31 |
|
| 32 |
function PseudoObj = PseudoObject(T, varargin) |
| 33 |
% construct a Pseudo-Object with type T (no other fields yet) |
| 34 |
PseudoObj = struct('Type', T, varargin{:}); |
| 35 |
end |
| 36 |
|
| 37 |
function bool = isStream(value) |
| 38 |
bool = ischar(value) || ismember(value, [1,2,fopen('all')]); |
| 39 |
%TODO: allow others kinds of streams |
| 40 |
% Stream -> clipboard (write on close) |
| 41 |
% Stream -> string variable |
| 42 |
% e.g. a quick-and-dirty way would be to write the file to `tempname` |
| 43 |
% putting a flag to read that file back upon completion. |
| 44 |
end |
| 45 |
|
| 46 |
function Stream = constructStream(streamSpecifier, varargin) |
| 47 |
% this is the actual constructor of a stream |
| 48 |
if ~isStream(streamSpecifier) |
| 49 |
error('StreamMaker:NotAStream', 'Invalid stream specifier "%s"', ... |
| 50 |
streamSpecifier); |
| 51 |
end |
| 52 |
|
| 53 |
Stream = PseudoObject('Stream'); |
| 54 |
closeAfterUse = false; |
| 55 |
if ischar(streamSpecifier) |
| 56 |
Stream.name = streamSpecifier; |
| 57 |
Stream.fid = fopen(Stream.name, varargin{:}); |
| 58 |
closeAfterUse = true; |
| 59 |
elseif isnumeric(streamSpecifier) |
| 60 |
Stream.fid = streamSpecifier; |
| 61 |
Stream.name = fopen(Stream.fid); |
| 62 |
end |
| 63 |
|
| 64 |
if Stream.fid == -1 |
| 65 |
error('Stream:InvalidStream', ... |
| 66 |
'Unable to create stream "%s"!', streamSpecifier); |
| 67 |
end |
| 68 |
|
| 69 |
Stream.print = @(varargin) fprintf(Stream.fid, varargin{:}); |
| 70 |
Stream.close = @() fclose(Stream.fid); |
| 71 |
if closeAfterUse |
| 72 |
Stream.closeAfterUse = onCleanup(Stream.close); |
| 73 |
end |
| 74 |
end |