| 1 |
package sixel |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"strings" |
| 7 |
) |
| 8 |
|
| 9 |
// ErrInvalidRaster is returned when Raster Attributes are invalid. |
| 10 |
var ErrInvalidRaster = fmt.Errorf("invalid raster attributes") |
| 11 |
|
| 12 |
// WriteRaster writes Raster attributes to a writer. If ph and pv are 0, they |
| 13 |
// are omitted. |
| 14 |
func WriteRaster(w io.Writer, pan, pad, ph, pv int) (n int, err error) { |
| 15 |
if pad == 0 { |
| 16 |
return WriteRaster(w, 1, 1, ph, pv) |
| 17 |
} |
| 18 |
|
| 19 |
if ph <= 0 && pv <= 0 { |
| 20 |
return fmt.Fprintf(w, "%c%d;%d", RasterAttribute, pan, pad) //nolint:wrapcheck |
| 21 |
} |
| 22 |
|
| 23 |
return fmt.Fprintf(w, "%c%d;%d;%d;%d", RasterAttribute, pan, pad, ph, pv) //nolint:wrapcheck |
| 24 |
} |
| 25 |
|
| 26 |
// Raster represents Sixel raster attributes. |
| 27 |
type Raster struct { |
| 28 |
Pan, Pad, Ph, Pv int |
| 29 |
} |
| 30 |
|
| 31 |
// WriteTo writes Raster attributes to a writer. |
| 32 |
func (r Raster) WriteTo(w io.Writer) (int64, error) { |
| 33 |
n, err := WriteRaster(w, r.Pan, r.Pad, r.Ph, r.Pv) |
| 34 |
return int64(n), err |
| 35 |
} |
| 36 |
|
| 37 |
// String returns the Raster as a string. |
| 38 |
func (r Raster) String() string { |
| 39 |
var b strings.Builder |
| 40 |
r.WriteTo(&b) //nolint:errcheck,gosec |
| 41 |
return b.String() |
| 42 |
} |
| 43 |
|
| 44 |
// DecodeRaster decodes a Raster from a byte slice. It returns the Raster and |
| 45 |
// the number of bytes read. |
| 46 |
func DecodeRaster(data []byte) (r Raster, n int) { |
| 47 |
if len(data) == 0 || data[0] != RasterAttribute { |
| 48 |
return r, n |
| 49 |
} |
| 50 |
|
| 51 |
ptr := &r.Pan |
| 52 |
for n = 1; n < len(data); n++ { |
| 53 |
if data[n] == ';' { //nolint:nestif |
| 54 |
if ptr == &r.Pan { |
| 55 |
ptr = &r.Pad |
| 56 |
} else if ptr == &r.Pad { |
| 57 |
ptr = &r.Ph |
| 58 |
} else if ptr == &r.Ph { |
| 59 |
ptr = &r.Pv |
| 60 |
} else { |
| 61 |
n++ |
| 62 |
break |
| 63 |
} |
| 64 |
} else if data[n] >= '0' && data[n] <= '9' { |
| 65 |
*ptr = (*ptr)*10 + int(data[n]-'0') |
| 66 |
} else { |
| 67 |
break |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
return r, n |
| 72 |
} |