-- ConvertUnsafeImpl.mesa, unsafe conversions to/from STRING
-- Russ Atkinson, October 5, 1982 11:21 am

DIRECTORY
ConvertUnsafe,
Inline USING [LongCOPY],
RefText USING [New],
Rope USING [Fetch, Size, ROPE, Text],
RopeInline USING [NewText];

ConvertUnsafeImpl: PROGRAM
IMPORTS Inline, RefText, Rope, RopeInline
EXPORTS ConvertUnsafe
SHARES Rope
= BEGIN OPEN ConvertUnsafe, Rope;

AppendRefText: PUBLIC PROC [to: LS, from: REF READONLY TEXT] = {
len: NAT ← to.length;
FOR i: NAT IN [0..from.length) DO
to[len] ← from[i];
len ← len + 1;
ENDLOOP;
to.length ← len;
};

AppendRope: PUBLIC PROC [to: LS, from: ROPE] = {
len: NAT ← to.length;
FOR i: INT IN [0..Rope.Size[from]) DO
to[len] ← Rope.Fetch[from,i];
len ← len + 1;
ENDLOOP;
to.length ← len;
};

ToRefText: PUBLIC PROC [from: LS] RETURNS [REF TEXT] = {
len: NATIF from = NIL THEN 0 ELSE from.length;
nw: NAT ← (len+1)/2;
rt: REF TEXT ← RefText.New[len];
rt.length ← len;
IF nw > 0 THEN
Inline.LongCOPY
[from: from+2, nwords: nw, to: LOOPHOLE[rt, LONG POINTER]+2];
RETURN [rt]};

ToRope: PUBLIC PROC [from: LS] RETURNS [Rope.Text] = {
len: NATIF from = NIL THEN 0 ELSE from.length;
nw: NAT ← (len+1)/2;
rt: Rope.Text ← RopeInline.NewText[len];
IF nw > 0 THEN
Inline.LongCOPY
[from: from+2, nwords: nw, to: LOOPHOLE[rt, LONG POINTER]+2];
RETURN [rt]};

END.