1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
// Copyright 2023 The rust-ggstd authors. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// //go:generate go run makeisprint.go -output isprint.go
use ;
use crateutf8;
const LOWERHEX: & = b"0123456789abcdef";
const UPPERHEX: & = b"0123456789ABCDEF";
// // contains reports whether the string contains the byte c.
// fn contains(s string, c byte) bool {
// return index(s, c) != -1
// }
// fn quoteRuneWith(r rune, quote char, ASCIIonly: bool, graphicOnly: bool) string {
// return string(appendQuotedRuneWith(nil, r, quote, ASCIIonly, graphicOnly))
// }
// fn appendQuotedRuneWith(buf []byte, r rune, quote char, ASCIIonly: bool, graphicOnly: bool) []byte {
// buf = append(buf, quote)
// if !utf8::ValidRune(r) {
// r = utf8::RUNE_ERROR
// }
// buf = appendEscapedRune(buf, r, quote, ASCIIonly, graphicOnly)
// buf = append(buf, quote)
// return buf
// }
/// quote returns a double-quoted Go string literal representing s. The
/// returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
/// control characters and non-printable characters as defined by
/// is_print.
/// quote_bytes_string is similar to Quote, but takes slice of bytes
/// instead of a string. This is useful in cases when replacing Go Quote
/// function when the Go string contains arbitrary data (in Go strings
/// can contain arbitrary data, in Rust they cannot).
/// append_quote appends a double-quoted Go string literal representing s,
/// as generated by Quote, to dst and returns the extended buffer.
/// quote_to_ascii returns a double-quoted Go string literal representing s.
/// The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
/// non-ASCII characters and non-printable characters as defined by is_print.
/// append_quote_to_ascii appends a double-quoted Go string literal representing s,
/// as generated by quote_to_ascii, to dst and returns the extended buffer.
/// quote_to_graphic returns a double-quoted Go string literal representing s.
/// The returned string leaves Unicode graphic characters, as defined by
/// is_graphic, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100)
/// for non-graphic characters.
///
/// ```
/// use ggstd::strconv::quote_to_graphic;
///
/// let s = quote_to_graphic("☺");
/// assert_eq!(s, "\"☺\"");
///
/// // This string literal contains a tab character.
/// let s = quote_to_graphic("This is a \u{263a} \u{000a}");
/// assert_eq!(s, r#""This is a ☺\t\n""#);
///
/// let s = quote_to_graphic(r#"" This is a ☺ \n ""#);
/// assert_eq!(s, r#""\" This is a ☺ \\n \"""#);
/// ```
/// append_quote_to_graphic appends a double-quoted Go string literal representing s,
/// as generated by quote_to_graphic, to dst and returns the extended buffer.
// // QuoteRune returns a single-quoted Go character literal representing the
// // rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100)
// // for control characters and non-printable characters as defined by is_print.
// // If r is not a valid Unicode code point, it is interpreted as the Unicode
// // replacement character U+FFFD.
// fn QuoteRune(r rune) string {
// return quoteRuneWith(r, '\'', false, false)
// }
// // AppendQuoteRune appends a single-quoted Go character literal representing the rune,
// // as generated by QuoteRune, to dst and returns the extended buffer.
// fn AppendQuoteRune(dst: &mut Vec<u8>, r rune) []byte {
// return appendQuotedRuneWith(dst, r, '\'', false, false)
// }
// // QuoteRuneToASCII returns a single-quoted Go character literal representing
// // the rune. The returned string uses Go escape sequences (\t, \n, \xFF,
// // \u0100) for non-ASCII characters and non-printable characters as defined
// // by is_print.
// // If r is not a valid Unicode code point, it is interpreted as the Unicode
// // replacement character U+FFFD.
// fn QuoteRuneToASCII(r rune) string {
// return quoteRuneWith(r, '\'', true, false)
// }
// // AppendQuoteRuneToASCII appends a single-quoted Go character literal representing the rune,
// // as generated by QuoteRuneToASCII, to dst and returns the extended buffer.
// fn AppendQuoteRuneToASCII(dst: &mut Vec<u8>, r rune) []byte {
// return appendQuotedRuneWith(dst, r, '\'', true, false)
// }
// // QuoteRuneToGraphic returns a single-quoted Go character literal representing
// // the rune. If the rune is not a Unicode graphic character,
// // as defined by is_graphic, the returned string will use a Go escape sequence
// // (\t, \n, \xFF, \u0100).
// // If r is not a valid Unicode code point, it is interpreted as the Unicode
// // replacement character U+FFFD.
// fn QuoteRuneToGraphic(r rune) string {
// return quoteRuneWith(r, '\'', false, true)
// }
// // AppendQuoteRuneToGraphic appends a single-quoted Go character literal representing the rune,
// // as generated by QuoteRuneToGraphic, to dst and returns the extended buffer.
// fn AppendQuoteRuneToGraphic(dst: &mut Vec<u8>, r rune) []byte {
// return appendQuotedRuneWith(dst, r, '\'', false, true)
// }
// // CanBackquote reports whether the string s can be represented
// // unchanged as a single-line backquoted string without control
// // characters other than tab.
// fn CanBackquote(s string) bool {
// for s.len() > 0 {
// r, wid := utf8::decode_rune_in_string(s)
// s = s[wid..]
// if wid > 1 {
// if r == '\ufeff' {
// return false // BOMs are invisible and should not be quoted.
// }
// continue // All other multibyte runes are correctly encoded and assumed printable.
// }
// if r == utf8::RUNE_ERROR {
// return false
// }
// if (r < ' ' && r != '\t') || r == '`' || r == '\u007F' {
// return false
// }
// }
// return true
// }
// fn unhex(b byte) (v rune, ok bool) {
// c := rune(b)
// switch {
// case '0' <= c && c <= '9':
// return c - '0', true
// case 'a' <= c && c <= 'f':
// return c - 'a' + 10, true
// case 'A' <= c && c <= 'F':
// return c - 'A' + 10, true
// }
// return
// }
// // UnquoteChar decodes the first character or byte in the escaped string
// // or character literal represented by the string s.
// // It returns four values:
// //
// // 1. value, the decoded Unicode code point or byte value;
// // 2. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
// // 3. tail, the remainder of the string after the character; and
// // 4. an error that will be nil if the character is syntactically valid.
// //
// // The second argument, quote, specifies the type of literal being parsed
// // and therefore which escaped quote character is permitted.
// // If set to a single quote, it permits the sequence \' and disallows unescaped '.
// // If set to a double quote, it permits \" and disallows unescaped ".
// // If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.
// fn UnquoteChar(s string, quote char) (value rune, multibyte bool, tail string, err error) {
// // easy cases
// if s.len() == 0 {
// err = ErrSyntax
// return
// }
// switch c := s[0]; {
// case c == quote && (quote == '\'' || quote == '"'):
// err = ErrSyntax
// return
// case c >= utf8::RUNE_SELF:
// r, size := utf8::decode_rune_in_string(s)
// return r, true, s[size..], nil
// case c != '\\':
// return rune(s[0]), false, s[1..], nil
// }
// // hard case: c is backslash
// if s.len() <= 1 {
// err = ErrSyntax
// return
// }
// c := s[1]
// s = s[2..]
// switch c {
// case 'a':
// value = '\a'
// case 'b':
// value = '\b'
// case 'f':
// value = '\f'
// case 'n':
// value = '\n'
// case 'r':
// value = '\r'
// case 't':
// value = '\t'
// case 'v':
// value = '\v'
// case 'x', 'u', 'U':
// n := 0
// switch c {
// case 'x':
// n = 2
// case 'u':
// n = 4
// case 'U':
// n = 8
// }
// var v rune
// if s.len() < n {
// err = ErrSyntax
// return
// }
// for j := 0; j < n; j++ {
// x, ok := unhex(s[j])
// if !ok {
// err = ErrSyntax
// return
// }
// v = v<<4 | x
// }
// s = s[n..]
// if c == 'x' {
// // single-byte string, possibly not UTF-8
// value = v
// break
// }
// if !utf8::ValidRune(v) {
// err = ErrSyntax
// return
// }
// value = v
// multibyte = true
// case '0', '1', '2', '3', '4', '5', '6', '7':
// v := rune(c) - '0'
// if s.len() < 2 {
// err = ErrSyntax
// return
// }
// for j := 0; j < 2; j++ { // one digit already; two more
// x := rune(s[j]) - '0'
// if x < 0 || x > 7 {
// err = ErrSyntax
// return
// }
// v = (v << 3) | x
// }
// s = s[2..]
// if v > 255 {
// err = ErrSyntax
// return
// }
// value = v
// case '\\':
// value = '\\'
// case '\'', '"':
// if c != quote {
// err = ErrSyntax
// return
// }
// value = rune(c)
// default:
// err = ErrSyntax
// return
// }
// tail = s
// return
// }
// // QuotedPrefix returns the quoted string (as understood by Unquote) at the prefix of s.
// // If s does not start with a valid quoted string, QuotedPrefix returns an error.
// fn QuotedPrefix(s string) (string, error) {
// out, _, err := unquote(s, false)
// return out, err
// }
// // Unquote interprets s as a single-quoted, double-quoted,
// // or backquoted Go string literal, returning the string value
// // that s quotes. (If s is single-quoted, it would be a Go
// // character literal; Unquote returns the corresponding
// // one-character string.)
// fn Unquote(s string) (string, error) {
// out, rem, err := unquote(s, true)
// if len(rem) > 0 {
// return "", ErrSyntax
// }
// return out, err
// }
// // unquote parses a quoted string at the start of the input,
// // returning the parsed prefix, the remaining suffix, and any parse errors.
// // If unescape is true, the parsed prefix is unescaped,
// // otherwise the input prefix is provided verbatim.
// fn unquote(in string, unescape bool) (out, rem string, err error) {
// // Determine the quote form and optimistically find the terminating quote.
// if len(in) < 2 {
// return "", in, ErrSyntax
// }
// quote := in[0]
// end := index(in[1..], quote)
// if end < 0 {
// return "", in, ErrSyntax
// }
// end += 2 // position after terminating quote; may be wrong if escape sequences are present
// switch quote {
// case '`':
// switch {
// case !unescape:
// out = in[:end] // include quotes
// case !contains(in[:end], '\r'):
// out = in[len("`") : end-len("`")] // exclude quotes
// default:
// // Carriage return characters ('\r') inside raw string literals
// // are discarded from the raw string value.
// buf := make([]byte, 0, end-len("`")-len("\r")-len("`"))
// for i := len("`"); i < end-len("`"); i++ {
// if in[i] != '\r' {
// buf = append(buf, in[i])
// }
// }
// out = string(buf)
// }
// // NOTE: Prior implementations did not verify that raw strings consist
// // of valid UTF-8 characters and we continue to not verify it as such.
// // The Go specification does not explicitly require valid UTF-8,
// // but only mention that it is implicitly valid for Go source code
// // (which must be valid UTF-8).
// return out, in[end..], nil
// case '"', '\'':
// // Handle quoted strings without any escape sequences.
// if !contains(in[:end], '\\') && !contains(in[:end], '\n') {
// var valid bool
// switch quote {
// case '"':
// valid = utf8::ValidString(in[len(`"`) : end-len(`"`)])
// case '\'':
// r, n := utf8::decode_rune_in_string(in[len("'") : end-len("'")])
// valid = len("'")+n+len("'") == end && (r != utf8::RUNE_ERROR || n != 1)
// }
// if valid {
// out = in[:end]
// if unescape {
// out = out[1 : end-1] // exclude quotes
// }
// return out, in[end..], nil
// }
// }
// // Handle quoted strings with escape sequences.
// var buf []byte
// in0 := in
// in = in[1..] // skip starting quote
// if unescape {
// buf = make([]byte, 0, 3*end/2) // try to avoid more allocations
// }
// for len(in) > 0 && in[0] != quote {
// // Process the next character,
// // rejecting any unescaped newline characters which are invalid.
// r, multibyte, rem, err := UnquoteChar(in, quote)
// if in[0] == '\n' || err != nil {
// return "", in0, ErrSyntax
// }
// in = rem
// // Append the character if unescaping the input.
// if unescape {
// if r < utf8::RUNE_SELF || !multibyte {
// buf = append(buf, byte(r))
// } else {
// var arr [utf8::UTFMAX]byte
// n := utf8::encode_rune(arr[..], r)
// buf = append(buf, arr[:n]...)
// }
// }
// // Single quoted strings must be a single character.
// if quote == '\'' {
// break
// }
// }
// // Verify that the string ends with a terminating quote.
// if !(len(in) > 0 && in[0] == quote) {
// return "", in0, ErrSyntax
// }
// in = in[1..] // skip terminating quote
// if unescape {
// return string(buf), in, nil
// }
// return in0[:len(in0)-len(in)], in, nil
// default:
// return "", in, ErrSyntax
// }
// }
/// bsearch16 returns the smallest i such that a[i] >= x.
/// If there is no such i, bsearch16 returns a.len().
/// bsearch32 returns the smallest i such that a[i] >= x.
/// If there is no such i, bsearch32 returns a.len().
// // TODO: is_print is a local implementation of unicode.is_print, verified by the tests
// // to give the same answer. It allows this package not to depend on unicode,
// // and therefore not pull in all the Unicode tables. If the linker were better
// // at tossing unused tables, we could get rid of this implementation.
// // That would be nice.
/// is_print reports whether the rune is defined as printable by Go, with
/// the same definition as unicode.is_print: letters, numbers, punctuation,
/// symbols and ASCII space.
/// is_graphic reports whether the rune is defined as a Graphic by Unicode. Such
/// characters include letters, marks, numbers, punctuation, symbols, and
/// spaces, from categories L, M, N, P, S, and Zs.
/// is_in_graphic_list reports whether the rune is in the IS_GRAPHIC list. This separation
/// from is_graphic allows quote_with to avoid two calls to is_print.
/// Should be called only if is_print fails.