
use utils

+ fn sanitize(code: String) String {
    return sanitize_with_options(code, null)
}

+ class SanitizeOptions {
    + escape_lt: bool (true)
    + escape_gt: bool (true)
    + escape_double_quote: bool (true)
    + escape_single_quote: bool (true)
    + escape_ampersand: bool (false)
}

+ fn sanitize_with_options(code: String, options: ?SanitizeOptions (null)) String {
    let buf = utils:ByteBuffer.new()
    let len = code.length

    let escape_lt = true
    let escape_gt = true
    let escape_double_quote = true
    let escape_single_quote = true
    let escape_ampersand = false

    if isset(options) {
        escape_lt = options.escape_lt
        escape_gt = options.escape_gt
        escape_double_quote = options.escape_double_quote
        escape_single_quote = options.escape_single_quote
        escape_ampersand = options.escape_ampersand
    }

    let i = 0
    while i < len {
        let ch = code.get(i++)
        if ch == '<' && escape_lt  {
            buf.append_str("&lt;")
        } else if ch == '>' && escape_gt  {
            buf.append_str("&gt;")
        } else if ch == '"' && escape_double_quote  {
            buf.append_str("&quot;")
        } else if ch == '\'' && escape_single_quote  {
            buf.append_str("&#39;")
        } else if ch == '&' && escape_ampersand {
            buf.append_str("&amp;")
        } else {
            buf.append_byte(ch)
        }
    }
    return buf
}
