go-rfc8259/boolean/parse.go

72 lines
1.4 KiB
Go
Raw Normal View History

2023-11-03 23:21:12 +00:00
package rfc8259boolean
2023-11-03 21:29:39 +00:00
import (
"io"
"sourcecode.social/reiver/go-erorr"
2023-11-05 07:16:31 +00:00
"sourcecode.social/reiver/go-rfc8259/errors"
2023-11-03 21:29:39 +00:00
)
2023-11-03 23:21:12 +00:00
// Parse tries to parse a JSON boolean literal — i.e., either 'false' or 'true'.
2023-11-03 21:29:39 +00:00
// If it succeeds, then it return nil, and sets dst to the parsed value.
// If it failed, it returns an error.
//
// Example usage:
//
// var rs io.RuneScaner
//
// // ...
//
2023-11-03 23:29:38 +00:00
// var value rfc8259boolean.Boolean
2023-11-05 07:16:31 +00:00
// err := rfc8259.Parse(rs, &value)
2023-11-03 21:29:39 +00:00
//
// if nil != err {
// return err
// }
//
2023-11-03 23:31:06 +00:00
// fmt.Printf("value = %#v\n", value)
2023-11-03 23:21:12 +00:00
func Parse(runescanner io.RuneScanner, dst *Boolean) error {
2023-11-03 21:29:39 +00:00
if nil == runescanner {
2023-11-05 07:16:31 +00:00
return rfc8259errors.ErrNilRuneScanner
2023-11-03 21:29:39 +00:00
}
if nil == dst {
2023-11-05 07:16:31 +00:00
return rfc8259errors.ErrNilDestination
2023-11-03 21:29:39 +00:00
}
var r rune
{
var err error
r, _, err = runescanner.ReadRune()
if nil != err {
if io.EOF == err {
2023-11-05 07:16:31 +00:00
return rfc8259errors.ErrUnexpectedEndOfFile
2023-11-03 21:29:39 +00:00
}
2023-11-05 07:16:31 +00:00
return rfc8259errors.ErrProblemReadingRune(err)
2023-11-03 21:29:39 +00:00
}
if err := runescanner.UnreadRune(); nil != err {
2023-11-05 07:16:31 +00:00
return rfc8259errors.ErrProblemUnreadingRune(err, r)
2023-11-03 21:29:39 +00:00
}
}
switch r {
case 'f':
2023-11-05 07:16:31 +00:00
if err := parseFalse(runescanner); nil != err {
2023-11-03 21:29:39 +00:00
return err
}
2023-11-03 23:21:12 +00:00
*dst = False()
2023-11-03 21:29:39 +00:00
return nil
case 't':
2023-11-05 07:16:31 +00:00
if err := parseTrue(runescanner); nil != err {
2023-11-03 21:29:39 +00:00
return err
}
2023-11-03 23:21:12 +00:00
*dst = True()
2023-11-03 21:29:39 +00:00
return nil
default:
return erorr.Errorf("rfc8259: problem when trying to parse JSON boolean literal — expected either 'false' or 'true' but first character was %q (%U)", r, r)
}
}