Debian Codegraph @

value.go

raw symbols SCIP
1 /* Go IPP - IPP core protocol implementation in pure Go
2 *
3 * Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
4 * See LICENSE for license terms and conditions
5 *
6 * Values for message attributes
7 */
8
9 package goipp
10
11 import (
12 "bytes"
13 "encoding/binary"
14 "errors"
15 "fmt"
16 "math"
17 "time"
18 )
19
20 // Values represents a slice of Attribute values with tags
21 type Values []struct {
22 T Tag // The tag
23 V Value // The value
24 }
25
26 // Add value to Values
27 func (values *Values) Add(t Tag, v Value) {
28 *values = append(*values, struct {
29 T Tag
30 V Value
31 }{t, v})
32 }
33
34 // String() converts Values to string
35 func (values Values) String() string {
36 if len(values) == 1 {
37 return values[0].V.String()
38 }
39
40 var buf bytes.Buffer
41 buf.Write([]byte("["))
42 for i, v := range values {
43 if i != 0 {
44 buf.Write([]byte(","))
45 }
46 buf.Write([]byte(v.V.String()))
47 }
48 buf.Write([]byte("]"))
49
50 return buf.String()
51 }
52
53 // Equal checks that two Values are equal
54 func (values Values) Equal(values2 Values) bool {
55 if len(values) != len(values2) {
56 return false
57 }
58
59 for i, v := range values {
60 v2 := values2[i]
61 if v.T != v2.T || !ValueEqual(v.V, v2.V) {
62 return false
63 }
64 }
65
66 return true
67 }
68
69 // Value represents an attribute value
70 type Value interface {
71 String() string
72 Type() Type
73 encode() ([]byte, error)
74 decode([]byte) (Value, error)
75 }
76
77 // ValueEqual checks if two values are equal
78 func ValueEqual(v1, v2 Value) bool {
79 if v1.Type() != v2.Type() {
80 return false
81 }
82
83 switch v1.Type() {
84 case TypeDateTime:
85 return v1.(Time).Equal(v2.(Time).Time)
86 case TypeBinary:
87 return bytes.Equal(v1.(Binary), v2.(Binary))
88 case TypeCollection:
89 c1 := Attributes(v1.(Collection))
90 c2 := Attributes(v2.(Collection))
91 return c1.Equal(c2)
92 }
93
94 return v1 == v2
95 }
96
97 // Void represents "no value"
98 //
99 // Use with: TagUnsupportedValue, TagDefault, TagUnknown,
100 // TagNotSettable, TagDeleteAttr, TagAdminDefine
101 type Void struct{}
102
103 // String() converts Void Value to string
104 func (Void) String() string { return "" }
105
106 // Type returns type of Value
107 func (Void) Type() Type { return TypeVoid }
108
109 // Encode Void Value into wire format
110 func (v Void) encode() ([]byte, error) {
111 return []byte{}, nil
112 }
113
114 // Decode Void Value from wire format
115 func (Void) decode([]byte) (Value, error) {
116 return Void{}, nil
117 }
118
119 // Integer represents an Integer Value
120 //
121 // Use with: TagInteger, TagEnum
122 type Integer int32
123
124 // String() converts Integer value to string
125 func (v Integer) String() string { return fmt.Sprintf("%d", int32(v)) }
126
127 // Type returns type of Value
128 func (Integer) Type() Type { return TypeInteger }
129
130 // Encode Integer Value into wire format
131 func (v Integer) encode() ([]byte, error) {
132 return []byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)}, nil
133 }
134
135 // Decode Integer Value from wire format
136 func (Integer) decode(data []byte) (Value, error) {
137 if len(data) != 4 {
138 return nil, errors.New("value must be 4 bytes")
139 }
140
141 return Integer(binary.BigEndian.Uint32(data)), nil
142 }
143
144 // Boolean represents a boolean Value
145 //
146 // Use with: TagBoolean
147 type Boolean bool
148
149 // String() converts Boolean value to string
150 func (v Boolean) String() string { return fmt.Sprintf("%t", bool(v)) }
151
152 // Type returns type of Value
153 func (Boolean) Type() Type { return TypeBoolean }
154
155 // Encode Boolean Value into wire format
156 func (v Boolean) encode() ([]byte, error) {
157 if v {
158 return []byte{1}, nil
159 }
160 return []byte{0}, nil
161 }
162
163 // Decode Boolean Value from wire format
164 func (Boolean) decode(data []byte) (Value, error) {
165 if len(data) != 1 {
166 return nil, errors.New("value must be 1 byte")
167 }
168
169 return Boolean(data[0] != 0), nil
170 }
171
172 // String represents a string Value
173 //
174 // Use with: TagText, TagName, TagReservedString, TagKeyword, TagURI,
175 // TagURIScheme, TagCharset, TagLanguage, TagMimeType, TagMemberName
176 type String string
177
178 // String() converts String value to string
179 func (v String) String() string { return string(v) }
180
181 // Type returns type of Value
182 func (String) Type() Type { return TypeString }
183
184 // Encode String Value into wire format
185 func (v String) encode() ([]byte, error) {
186 return []byte(v), nil
187 }
188
189 // Decode String Value from wire format
190 func (String) decode(data []byte) (Value, error) {
191 return String(data), nil
192 }
193
194 // Time represents a DateTime Value
195 //
196 // Use with: TagTime
197 type Time struct{ time.Time }
198
199 // String() converts Time value to string
200 func (v Time) String() string { return v.Time.Format(time.RFC3339) }
201
202 // Type returns type of Value
203 func (Time) Type() Type { return TypeDateTime }
204
205 // Encode Time Value into wire format
206 func (v Time) encode() ([]byte, error) {
207 // From RFC2579:
208 //
209 // field octets contents range
210 // ----- ------ -------- -----
211 // 1 1-2 year* 0..65536
212 // 2 3 month 1..12
213 // 3 4 day 1..31
214 // 4 5 hour 0..23
215 // 5 6 minutes 0..59
216 // 6 7 seconds 0..60
217 // (use 60 for leap-second)
218 // 7 8 deci-seconds 0..9
219 // 8 9 direction from UTC '+' / '-'
220 // 9 10 hours from UTC* 0..13
221 // 10 11 minutes from UTC 0..59
222 //
223 // * Notes:
224 // - the value of year is in network-byte order
225 // - daylight saving time in New Zealand is +13
226
227 year := v.Year()
228 _, zone := v.Zone()
229 dir := byte('+')
230 if zone < 0 {
231 zone = -zone
232 dir = '-'
233 }
234
235 return []byte{
236 byte(year >> 8), byte(year),
237 byte(v.Month()),
238 byte(v.Day()),
239 byte(v.Hour()),
240 byte(v.Minute()),
241 byte(v.Second()),
242 byte(v.Nanosecond() / 100000000),
243 dir,
244 byte(zone / 3600),
245 byte((zone / 60) % 60),
246 }, nil
247 }
248
249 // Decode Time Value from wire format
250 func (Time) decode(data []byte) (Value, error) {
251 // Check size
252 if len(data) != 9 && len(data) != 11 {
253 return nil, errors.New("value must be 9 or 11 bytes")
254 }
255
256 // Decode time zone
257 var l *time.Location
258 switch {
259 case len(data) == 9:
260 l = time.UTC
261 case data[8] == '+', data[8] == '-':
262 name := fmt.Sprintf("UTC%c%d", data[8], data[9])
263 if data[10] != 0 {
264 name += fmt.Sprintf(":%d", data[10])
265 }
266
267 off := 3600*int(data[9]) + 60*int(data[10])
268 if data[8] == '-' {
269 off = -off
270 }
271
272 l = time.FixedZone(name, off)
273
274 default:
275 return nil, errors.New("invalid data format")
276 }
277
278 // Decode time
279 t := time.Date(
280 int(binary.BigEndian.Uint16(data[0:2])), // year
281 time.Month(data[2]), // month
282 int(data[3]), // day
283 int(data[4]), // hour
284 int(data[5]), // min
285 int(data[6]), // sec
286 int(data[7])*100000000, // nsec
287 l, // time zone
288 )
289
290 return Time{t}, nil
291 }
292
293 // Resolution represents a resolution Value
294 //
295 // Use with: TagResolution
296 type Resolution struct {
297 Xres, Yres int // X/Y resolutions
298 Units Units // Resolution units
299 }
300
301 // String() converts Resolution value to string
302 func (v Resolution) String() string {
303 return fmt.Sprintf("%dx%d%s", v.Xres, v.Yres, v.Units)
304 }
305
306 // Type returns type of Value
307 func (Resolution) Type() Type { return TypeResolution }
308
309 // Encode Resolution Value into wire format
310 func (v Resolution) encode() ([]byte, error) {
311 // Wire format
312 // 4 bytes: Xres
313 // 4 bytes: Yres
314 // 1 byte: Units
315
316 x, y := v.Xres, v.Yres
317
318 return []byte{
319 byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x),
320 byte(y >> 24), byte(y >> 16), byte(y >> 8), byte(y),
321 byte(v.Units),
322 }, nil
323 }
324
325 // Decode Resolution Value from wire format
326 func (Resolution) decode(data []byte) (Value, error) {
327 if len(data) != 9 {
328 return nil, errors.New("value must be 9 bytes")
329 }
330
331 return Resolution{
332 Xres: int(binary.BigEndian.Uint32(data[0:4])),
333 Yres: int(binary.BigEndian.Uint32(data[4:8])),
334 Units: Units(data[8]),
335 }, nil
336
337 }
338
339 // Units represents resolution units
340 type Units uint8
341
342 const (
343 UnitsDpi Units = 3 // Dots per inch
344 UnitsDpcm Units = 4 // Dots per cm
345 )
346
347 // String() converts Units to string
348 func (u Units) String() string {
349 switch u {
350 case UnitsDpi:
351 return "dpi"
352 case UnitsDpcm:
353 return "dpcm"
354 default:
355 return fmt.Sprintf("0x%2.2x", uint8(u))
356 }
357 }
358
359 // Range represents a range of integers Value
360 //
361 // Use with: TagRange
362 type Range struct {
363 Lower, Upper int // Lower/upper bounds
364 }
365
366 // String() converts Range value to string
367 func (v Range) String() string {
368 return fmt.Sprintf("%d-%d", v.Lower, v.Upper)
369 }
370
371 // Type returns type of Value
372 func (Range) Type() Type { return TypeRange }
373
374 // Encode Range Value into wire format
375 func (v Range) encode() ([]byte, error) {
376 // Wire format
377 // 4 bytes: Lower
378 // 4 bytes: Upper
379
380 l, u := v.Lower, v.Upper
381
382 return []byte{
383 byte(l >> 24), byte(l >> 16), byte(l >> 8), byte(l),
384 byte(u >> 24), byte(u >> 16), byte(u >> 8), byte(u),
385 }, nil
386 }
387
388 // Decode Range Value from wire format
389 func (Range) decode(data []byte) (Value, error) {
390 if len(data) != 8 {
391 return nil, errors.New("value must be 9 bytes")
392 }
393
394 return Range{
395 Lower: int(binary.BigEndian.Uint32(data[0:4])),
396 Upper: int(binary.BigEndian.Uint32(data[4:8])),
397 }, nil
398 }
399
400 // TextWithLang represents a combination of two strings:
401 // one is a name of natural language and second is a text
402 // on this language
403 //
404 // Use with: TagTextLang, TagNameLang
405 type TextWithLang struct {
406 Lang, Text string // Language and text
407 }
408
409 // String() converts TextWithLang value to string
410 func (v TextWithLang) String() string { return v.Text + " [" + v.Lang + "]" }
411
412 // Type returns type of Value
413 func (TextWithLang) Type() Type { return TypeTextWithLang }
414
415 // Encode TextWithLang Value into wire format
416 func (v TextWithLang) encode() ([]byte, error) {
417 // Wire format
418 // 2 bytes: len(Lang)
419 // variable: Lang
420 // 2 bytes: len(Text)
421 // variable: Text
422
423 lang := []byte(v.Lang)
424 text := []byte(v.Text)
425
426 if len(lang) > math.MaxUint16 {
427 return nil, fmt.Errorf("Lang exceeds %d bytes", math.MaxUint16)
428 }
429
430 if len(text) > math.MaxUint16 {
431 return nil, fmt.Errorf("Text exceeds %d bytes", math.MaxUint16)
432 }
433
434 data := make([]byte, 2+2+len(lang)+len(text))
435 binary.BigEndian.PutUint16(data, uint16(len(lang)))
436 copy(data[2:], []byte(lang))
437
438 data2 := data[2+len(lang):]
439 binary.BigEndian.PutUint16(data2, uint16(len(text)))
440 copy(data2[2:], []byte(text))
441
442 return data, nil
443 }
444
445 // Decode TextWithLang Value from wire format
446 func (TextWithLang) decode(data []byte) (Value, error) {
447 var langLen, textLen int
448 var lang, text string
449
450 // Unpack language length
451 if len(data) < 2 {
452 goto ERROR
453 }
454
455 langLen = int(binary.BigEndian.Uint16(data[0:2]))
456 data = data[2:]
457
458 // Unpack language value
459 if len(data) < langLen {
460 goto ERROR
461 }
462
463 lang = string(data[:langLen])
464 data = data[langLen:]
465
466 // Unpack text length
467 if len(data) < 2 {
468 goto ERROR
469 }
470
471 textLen = int(binary.BigEndian.Uint16(data[0:2]))
472 data = data[2:]
473
474 // Unpack text value
475 if len(data) < textLen {
476 goto ERROR
477 }
478
479 text = string(data[:textLen])
480 data = data[textLen:]
481
482 // We must have consumed all bytes at this point
483 if len(data) != 0 {
484 goto ERROR
485 }
486
487 // Return a value
488 return TextWithLang{Lang: lang, Text: text}, nil
489
490 ERROR:
491 return nil, errors.New("invalid data format")
492 }
493
494 // Binary represents a raw binary Value
495 type Binary []byte
496
497 // String() converts Range value to string
498 func (v Binary) String() string {
499 return fmt.Sprintf("%x", []byte(v))
500 }
501
502 // Type returns type of Value
503 func (Binary) Type() Type { return TypeBinary }
504
505 // Encode TextWithLang Value into wire format
506 func (v Binary) encode() ([]byte, error) {
507 return []byte(v), nil
508 }
509
510 // Decode Binary Value from wire format
511 func (Binary) decode(data []byte) (Value, error) {
512 return Binary(data), nil
513 }
514
515 // Collection represents a collection of attributes
516 //
517 // Use with: TagBeginCollection
518 type Collection Attributes
519
520 // Add Attribute to Attributes
521 func (collection *Collection) Add(attr Attribute) {
522 *collection = append(*collection, attr)
523 }
524
525 // Equal checks that two collections are equal
526 func (c1 Collection) Equal(c2 Attributes) bool {
527 return Attributes(c1).Equal(Attributes(c2))
528 }
529
530 // String() converts Collection to string
531 func (v Collection) String() string {
532 var buf bytes.Buffer
533 buf.Write([]byte("{"))
534 for i, attr := range v {
535 if i > 0 {
536 buf.Write([]byte(" "))
537 }
538 fmt.Fprintf(&buf, "%s=%s", attr.Name, attr.Values)
539 }
540 buf.Write([]byte("}"))
541
542 return buf.String()
543 }
544
545 // Type returns type of Value
546 func (Collection) Type() Type { return TypeCollection }
547
548 // Encode Collection Value into wire format
549 func (v Collection) encode() ([]byte, error) {
550 // Note, TagBeginCollection attribute contains
551 // no data, collection itself handled the different way
552 return []byte{}, nil
553 }
554
555 // Decode Collection Value from wire format
556 func (Collection) decode(data []byte) (Value, error) {
557 panic("internal error")
558 }