[M3devel] heap vs. stack? (sort of)

Tony Hosking hosking at cs.purdue.edu
Mon Jan 28 17:55:24 CET 2008


I actually find this idiom for avoiding heap allocation (assuming it  
really is expensive in the first place) particularly elegant.

In any case, what's wrong with defining a generic procedure:

PROCEDURE Apply (p: PROCEDURE(nm: ARRAY OF CHAR); nm: TEXT): T =
   VAR len := Text.Length(nm);  buf: ARRAY [0..255] OF CHAR;
   BEGIN
     IF len <= NUMBER(buf)
       THEN RETURN p(SUBARRAY(buf, 0, len));
       ELSE RETURN p(NEW(REF ARRAY OF CHAR, len)^);
     END;
   END Apply;

and then use Apply to apply a nested procedure to the appropriate  
text at each place you need it?


On Jan 28, 2008, at 4:48 AM, Jay wrote:

> Is it possible to have this pattern in Modula-3:
>
> PROCEDURE Parse (nm: TEXT;  host: BOOLEAN): T =
>   VAR len := Text.Length (nm);   buf: ARRAY [0..255] OF CHAR;
>   BEGIN
>     IF (len <= NUMBER (buf))
>       THEN RETURN DoParse (nm, SUBARRAY (buf, 0, len), host);
>       ELSE RETURN DoParse (nm, NEW (REF ARRAY OF CHAR, len)^, host);
>     END;
>   END Parse;
>
> PROCEDURE DoParse (nm_txt: TEXT;  VAR nm: ARRAY OF CHAR;  host:  
> BOOLEAN): T =
>
> without the extra function?
>
> There are places in M3Path.m3 that duplicate code otherwise, one  
> branch acting on a local stack allocated array, the other acting on  
> a heap allocated array when the stack array is too small, but  
> otherwise identical code.
>
> So far I have not figured out how. Local variables cannot be open  
> array. SUBARRAY returns an ARRAY and not a REF ARRAY... It seems  
> that parameters can be open arrays but local variables cannot, and  
> that seems wrong.. parameters and locals so often share  
> characteristics...
>
>  - Jay
>
>
>
>
> Need to know the score, the latest news, or you need your Hotmail®- 
> get your "fix". Check it out.




More information about the M3devel mailing list