3
$\begingroup$

Denoting the two special bytes as FLAG and ESC, and any other as X, where FLAG denotes the start and end of the message and ESC is used to escape any flags within the original message, if the original message was for example,

X FLAG ESC FLAG FLAG ESC ESC FLAG X X

this can be byte stuffed as,

FLAG X ESC FLAG ESC ESC FLAG ESC FLAG ESC ESC ESC FLAG X X FLAG

where the added bytes are in bold. I don't think it is necessary to escape the escapes. In the receiving side, only FLAG comming after ESC together will be changed to FLAG and when any other bytes come after ESC, that ESC will be ESC as is. For example, if you see the ESC byte at the 5th byte of the received message, since ESC comes after ESC, the 5th ESC will be interpreted as ESC and nothing more. I thought about this, and I think it also works this way. But every resources I can find including my networks book says that an escape should be escaped as well as the flags when originally contained in the message. Why so?

$\endgroup$

1 Answer 1

4
$\begingroup$

Think of a message (ending in) FLAG. You need to escape it, of course, so your message looks like: FLAG (rest) ESC escaped-FLAG FLAG

Now think of a message (ending in) ESC. If you do not escape it, your message looks like this: FLAG (rest) ESC FLAG

Now, “ESC FLAG” and “ESC escaped-FLAG” are undistinguishable. So, that last ESC needs to be escaped.

Now you can go backwards, again and again, until you find that, if one ESC has to be escaped, they all need to be escaped, from the first one.

$\endgroup$
2
  • $\begingroup$ Wouldn't it be enough to take a sequence ending with ESC FLAG as something where ESC is part of data and FLAG is the frame control FLAG. I guess this is the only corner case. $\endgroup$ Commented Jun 29, 2022 at 17:13
  • $\begingroup$ @user2277550 you always need to escape the escape character if it occurs within the data; you can construct escaping schemes any way you want, but if you don’t do that you get ambiguity in at least one of multiple ways; the only other option is to use a different encoding scheme (something like base128 or so) that changes all characters, or to use an escape char that cannot be present in input data (like \xFF in UTF-8), but you have to check that. $\endgroup$
    – mirabilos
    Commented Jul 3, 2022 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.