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
|
# File 'lib/punycode.rb', line 453
def main(argv)
case_flags = [0] * UNICODE_MAX_LENGTH
usage(argv) if argv.size != 2
usage(argv) if /\A-[de]\z/ !~ argv[1]
if argv[1][1] == ?e
input = [0] * UNICODE_MAX_LENGTH
output = [0] * (ACE_MAX_LENGTH+1)
input_length = 0
STDIN.read.scan(/([uU]\+)([0-9a-fA-F]+)/) do |uplus, codept|
codept = codept.hex
if uplus[1] != ?+ || codept > Punycode::MAXINT
fail(INVALID_INPUT)
end
fail(TOO_BIG) if input_length == UNICODE_MAX_LENGTH
if uplus[0] == ?u
case_flags[input_length] = false
elsif uplus[0] == ?U
case_flags[input_length] = true
else
fail(INVALID_INPUT)
end
input[input_length] = codept
input_length+=1
end
output_length = [ACE_MAX_LENGTH]
begin
status = Punycode.punycode_encode(input_length, input, case_flags,
output_length, output)
rescue Punycode::Status::PunycodeBadInput
fail(INVALID_INPUT)
rescue Punycode::Status::PunycodeBigOutput
fail(TOO_BIG)
rescue Punycode::Status::PunycodeOverflow
fail(OVERFLOW)
end
if status != Punycode::Status::PunycodeSuccess
fail("assertion error: unknown status")
end
outlen = output_length[0]
outlen.times do |j|
c = output[j]
raise "assertion error: invalid output char" unless c >= 0 && c <= 127
unless PRINT_ASCII[c]
fail(INVALID_INPUT)
end
output[j] = PRINT_ASCII[c]
end
output = output[0..outlen].map{|x|x.chr}.join('').sub(/\0+\z/, '')
puts(output)
exit(true)
end
if argv[1][1] == ?d
output = []
input = STDIN.gets.split(//)[0,ACE_MAX_LENGTH*2]
fail(TOO_BIG) if input[-1] != "\n"
input = input[0...-1]
input.each_with_index do |c, i|
print_ascii_index = PRINT_ASCII.index(c)
fail(INVALID_INPUT) unless print_ascii_index
input[i] = print_ascii_index
end
output_length = [UNICODE_MAX_LENGTH]
begin
status = Punycode.punycode_decode(input.length, input, output_length,
output, case_flags)
rescue Punycode::Status::PunycodeBadInput
fail(INVALID_INPUT)
rescue Punycode::Status::PunycodeBigOutput
fail(TOO_BIG)
rescue Punycode::Status::PunycodeOverflow
fail(OVERFLOW)
end
if status != Punycode::Status::PunycodeSuccess
fail("assertion error: unknown status")
end
output_length[0].times do |j|
printf("%s+%04X\n", case_flags[j] ? "U" : "u", output[j])
end
exit(true)
end
usage(argv)
raise "not reached"
end
|