WeixiangYan/CodeTransOcean huggingface dataset:
Task: GUI enabling_disabling of controls




Go: package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str string) (int64, bool) {
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid value",
        )
        dialog.Run()
        dialog.Destroy()
        return 0, false
    }
    return i, true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func processState(i int64, entry *gtk.Entry, ib, db *gtk.Button) {
    if i == 0 {
        entry.SetSensitive(true)
    } else {
        entry.SetSensitive(false)
    }
    if i < 10 {
        ib.SetSensitive(true)
    } else {
        ib.SetSensitive(false)
    }
    if i > 0 {
        db.SetSensitive(true)
    } else {
        db.SetSensitive(false)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create box:")
    box.SetBorderWidth(1)

    label, err := gtk.LabelNew("Value:")
    check(err, "Unable to create label:")

    entry, err := gtk.EntryNew()
    check(err, "Unable to create entry:")
    entry.SetText("0") 
    entry.SetSensitive(true)

    
    ib, err := gtk.ButtonNewWithLabel("Increment")
    check(err, "Unable to create increment button:")
    ib.SetSensitive(true)

    
    db, err := gtk.ButtonNewWithLabel("Decrement")
    check(err, "Unable to create decrement button:")
    db.SetSensitive(false)

    entry.Connect("activate", func() {
        
        str, _ := entry.GetText()
        i, ok := validateInput(window, str)
        if !ok {
            entry.SetText("0")
        }
        processState(i, entry, ib, db)
    })

    ib.Connect("clicked", func() {
        
        str, _ := entry.GetText()
        i, _ := validateInput(window, str)
        i++
        entry.SetText(strconv.FormatInt(i, 10))
        processState(i, entry, ib, db)
    })

    db.Connect("clicked", func() {
        
        str, _ := entry.GetText()
        i, _ := validateInput(window, str)
        i--
        entry.SetText(strconv.FormatInt(i, 10))
        processState(i, entry, ib, db)
    })

    box.PackStart(label, false, false, 2)
    box.PackStart(entry, false, false, 2)
    box.PackStart(ib, false, false, 2)
    box.PackStart(db, false, false, 2)
    window.Add(box)

    window.ShowAll()
    gtk.Main()
}
Task: Singly-linked list_Element insertion



C#: static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
    prev.Next = new Link() { Value = value, Next = prev.Next };
}









Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion

C: void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}











Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion


C++: template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};










Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion




Go: package main

import "fmt"

type Ele struct {
    Data interface{}
    Next *Ele
}

func (e *Ele) insert(data interface{}) {
    if e == nil {
        panic("attept to modify nil")
    }
    e.Next = &Ele{data, e.Next}
}

func (e *Ele) printList() {
    if e == nil {
        fmt.Println(nil)
        return
    }
    fmt.Printf("(%v", e.Data)
    for {
        e = e.Next
        if e == nil {
            fmt.Println(")")
            return
        }
        fmt.Print(" ", e.Data)
    }
}

func main() {
    h := &Ele{"A", &Ele{"B", nil}}
    h.printList()
    h.insert("C")
    h.printList()
}








Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion





Java: void insertNode(Node<T> anchor_node, Node<T> new_node)
{
    new_node.next = anchor_node.next;
    anchor_node.next = new_node;
}







Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion







Python: def chain_insert(lst, at, item):
    while lst is not None:
        if lst[0] == at:
            lst[1] = [item, lst[1]]
            return
        else:
            lst = lst[1]
    raise ValueError(str(at) + " not found")

chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain





Ada: with Ada.Unchecked_Deallocation;

procedure Singly_Linked is
   
   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);  

begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;
Task: Singly-linked list_Element insertion

C: void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}
Task: Singly-linked list_Element insertion



C#: static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
    prev.Next = new Link() { Value = value, Next = prev.Next };
}
Task: Singly-linked list_Element insertion


C++: template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};
Task: Singly-linked list_Element insertion





Java: void insertNode(Node<T> anchor_node, Node<T> new_node)
{
    new_node.next = anchor_node.next;
    anchor_node.next = new_node;
}
Task: Singly-linked list_Element insertion







Python: def chain_insert(lst, at, item):
    while lst is not None:
        if lst[0] == at:
            lst[1] = [item, lst[1]]
            return
        else:
            lst = lst[1]
    raise ValueError(str(at) + " not found")

chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain
Task: Singly-linked list_Element insertion




Go: package main

import "fmt"

type Ele struct {
    Data interface{}
    Next *Ele
}

func (e *Ele) insert(data interface{}) {
    if e == nil {
        panic("attept to modify nil")
    }
    e.Next = &Ele{data, e.Next}
}

func (e *Ele) printList() {
    if e == nil {
        fmt.Println(nil)
        return
    }
    fmt.Printf("(%v", e.Data)
    for {
        e = e.Next
        if e == nil {
            fmt.Println(")")
            return
        }
        fmt.Print(" ", e.Data)
    }
}

func main() {
    h := &Ele{"A", &Ele{"B", nil}}
    h.printList()
    h.insert("C")
    h.printList()
}
Task: Singly-linked list_Element insertion



C#: static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
    prev.Next = new Link() { Value = value, Next = prev.Next };
}








Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Singly-linked list_Element insertion


C++: template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};









Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Singly-linked list_Element insertion

C: void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}










Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Singly-linked list_Element insertion




Go: package main

import "fmt"

type Ele struct {
    Data interface{}
    Next *Ele
}

func (e *Ele) insert(data interface{}) {
    if e == nil {
        panic("attept to modify nil")
    }
    e.Next = &Ele{data, e.Next}
}

func (e *Ele) printList() {
    if e == nil {
        fmt.Println(nil)
        return
    }
    fmt.Printf("(%v", e.Data)
    for {
        e = e.Next
        if e == nil {
            fmt.Println(")")
            return
        }
        fmt.Print(" ", e.Data)
    }
}

func main() {
    h := &Ele{"A", &Ele{"B", nil}}
    h.printList()
    h.insert("C")
    h.printList()
}







Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Singly-linked list_Element insertion





Java: void insertNode(Node<T> anchor_node, Node<T> new_node)
{
    new_node.next = anchor_node.next;
    anchor_node.next = new_node;
}






Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Singly-linked list_Element insertion







Python: def chain_insert(lst, at, item):
    while lst is not None:
        if lst[0] == at:
            lst[1] = [item, lst[1]]
            return
        else:
            lst = lst[1]
    raise ValueError(str(at) + " not found")

chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain




Fortran: elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode
   
   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter
Task: Variable-length quantity




Go: package main

import (
    "fmt"
    "encoding/binary"
)

func main() {
    buf := make([]byte, binary.MaxVarintLen64)
    for _, x := range []int64{0x200000, 0x1fffff} {
        v := buf[:binary.PutVarint(buf, x)]
        fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v)
        x, _ = binary.Varint(v)
        fmt.Println(x, "decoded")
    }
}








Ada: with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Unchecked_Conversion;

procedure VLQ is

   package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);

   type Byte is mod 2**8;

   package Byte_IO is new Ada.Text_IO.Modular_IO (Byte);

   type Int7 is mod 2**7;

   package Int7_IO is new Ada.Text_IO.Modular_IO (Int7);

   type VLQ_Octet is record
      Value : Int7 := 0;
      Next  : Boolean := True;
   end record;
   pragma Pack (VLQ_Octet);
   for VLQ_Octet'Size use 8;

   function VLQ_To_Byte is new Ada.Unchecked_Conversion (VLQ_Octet, Byte);
   function Byte_To_VLQ is new Ada.Unchecked_Conversion (Byte, VLQ_Octet);

   package VLQ_Vectors is new Ada.Containers.Vectors (Natural, VLQ_Octet);

   procedure Hex_Print (Position : in VLQ_Vectors.Cursor) is
      Value : Byte := VLQ_To_Byte (VLQ_Vectors.Element (Position));
   begin
      Ada.Text_IO.Put (':');
      Byte_IO.Put (Item => Value, Width => 6, Base => 16);
   end Hex_Print;

   procedure Print (X : VLQ_Vectors.Vector) is
   begin
      X.Iterate (Hex_Print'Access);
      Ada.Text_IO.New_Line;
   end Print;

   function To_VLQ (From : Natural) return VLQ_Vectors.Vector is
      Result : VLQ_Vectors.Vector;
      Current : Natural := From;
      Element : VLQ_Octet;
   begin
      loop
         Element.Value := Int7 (Current mod 2**7);
         Result.Prepend (Element);
         Current := Current / 2**7;
         exit when Current = 0;
      end loop;
      Element := Result.Last_Element;
      Element.Next := False;
      VLQ_Vectors.Replace_Element (Result, Result.Last, Element);
      return Result;
   end To_VLQ;

   function To_Int (From : VLQ_Vectors.Vector) return Natural is
      use type VLQ_Vectors.Cursor;
      Result : Natural := 0;
      Iterator : VLQ_Vectors.Cursor := From.First;
   begin
      while Iterator /= VLQ_Vectors.No_Element loop
         Result := Result * 2**7;
         Result := Result + Natural(VLQ_Vectors.Element (Iterator).Value);
         VLQ_Vectors.Next (Iterator);
      end loop;
      return Result;
   end To_Int;

   Test : VLQ_Vectors.Vector;
begin
   Test := To_VLQ (16#7f#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
   Test := To_VLQ (16#4000#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
   Test := To_VLQ (16#0#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
   Test := To_VLQ (16#3FFFFE#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
   Test := To_VLQ (16#1FFFFF#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
   Test := To_VLQ (16#200000#);
   Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
   Print (Test);
end VLQ;
Task: Variable-length quantity

C: #include <stdio.h>
#include <stdint.h>

void to_seq(uint64_t x, uint8_t *out)
{
	int i, j;
	for (i = 9; i > 0; i--) {
		if (x & 127ULL << i * 7) break;
	}
	for (j = 0; j <= i; j++)
		out[j] = ((x >> ((i - j) * 7)) & 127) | 128;

	out[i] ^= 128;
}

uint64_t from_seq(uint8_t *in)
{
	uint64_t r = 0;

	do {
		r = (r << 7) | (uint64_t)(*in & 127);
	} while (*in++ & 128);

	return r;
}

int main()
{
	uint8_t s[10];
	uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};

	int i, j;
	for (j = 0; j < sizeof(x)/8; j++) {
		to_seq(x[j], s);
		printf("seq from %llx: [ ", x[j]);

		i = 0;
		do { printf("%02x ", s[i]); } while ((s[i++] & 128));
		printf("] back: %llx\n", from_seq(s));
	}

	return 0;
}
Task: Variable-length quantity



C#: namespace Vlq
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  public static class VarLenQuantity
  {
    public static ulong ToVlq(ulong integer)
    {
      var array = new byte[8];
      var buffer = ToVlqCollection(integer)
        .SkipWhile(b => b == 0)
        .Reverse()
        .ToArray();
      Array.Copy(buffer, array, buffer.Length);
      return BitConverter.ToUInt64(array, 0);
    }

    public static ulong FromVlq(ulong integer)
    {
      var collection = BitConverter.GetBytes(integer).Reverse();
      return FromVlqCollection(collection);
    }

    public static IEnumerable<byte> ToVlqCollection(ulong integer)
    {
      if (integer > Math.Pow(2, 56))
        throw new OverflowException("Integer exceeds max value.");

      var index = 7;
      var significantBitReached = false;
      var mask = 0x7fUL << (index * 7);
      while (index >= 0)
      {
        var buffer = (mask & integer);
        if (buffer > 0 || significantBitReached)
        {
          significantBitReached = true;
          buffer >>= index * 7;
          if (index > 0)
            buffer |= 0x80;
          yield return (byte)buffer;
        }
        mask >>= 7;
        index--;
      }
    }


    public static ulong FromVlqCollection(IEnumerable<byte> vlq)
    {
      ulong integer = 0;
      var significantBitReached = false;

      using (var enumerator = vlq.GetEnumerator())
      {
        int index = 0;
        while (enumerator.MoveNext())
        {
          var buffer = enumerator.Current;
          if (buffer > 0 || significantBitReached)
          {
            significantBitReached = true;
            integer <<= 7;
            integer |= (buffer & 0x7fUL);
          }

          if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
            break;
        }
      }
      return integer;
    }

    public static void Main()
    {
      var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };

      foreach (var original in integers)
      {
        Console.WriteLine("Original: 0x{0:X}", original);

        
        var seq = ToVlqCollection(original);
        Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));

        var decoded = FromVlqCollection(seq);
        Console.WriteLine("Decoded: 0x{0:X}", decoded);

        
        var encoded = ToVlq(original);
        Console.WriteLine("Encoded: 0x{0:X}", encoded);

        decoded = FromVlq(encoded);
        Console.WriteLine("Decoded: 0x{0:X}", decoded);

        Console.WriteLine();
      }
      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }
  }
}
Task: Variable-length quantity


C++: #include <iomanip>
#include <iostream>
#include <vector>

std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << "[ ";
    if (it != end) {
        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
        it = std::next(it);
    }
    while (it != end) {
        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;
        it = std::next(it);
    }
    return os << " ]";
}

std::vector<uint8_t> to_seq(uint64_t x) {
    int i;
    for (i = 9; i > 0; i--) {
        if (x & 127ULL << i * 7) {
            break;
        }
    }

    std::vector<uint8_t> out;
    for (int j = 0; j <= i; j++) {
        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);
    }
    out[i] ^= 128;
    return out;
}

uint64_t from_seq(const std::vector<uint8_t> &seq) {
    uint64_t r = 0;

    for (auto b : seq) {
        r = (r << 7) | (b & 127);
    }

    return r;
}

int main() {
    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };

    for (auto x : src) {
        auto s = to_seq(x);
        std::cout << std::hex;
        std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n';
        std::cout << std::dec;
    }

    return 0;
}
Task: Variable-length quantity





Java: public class VLQCode
{
  public static byte[] encode(long n)
  {
    int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);
    int numBytes = (numRelevantBits + 6) / 7;
    if (numBytes == 0)
      numBytes = 1;
    byte[] output = new byte[numBytes];
    for (int i = numBytes - 1; i >= 0; i--)
    {
      int curByte = (int)(n & 0x7F);
      if (i != (numBytes - 1))
        curByte |= 0x80;
      output[i] = (byte)curByte;
      n >>>= 7;
    }
    return output;
  }
  
  public static long decode(byte[] b)
  {
    long n = 0;
    for (int i = 0; i < b.length; i++)
    {
      int curByte = b[i] & 0xFF;
      n = (n << 7) | (curByte & 0x7F);
      if ((curByte & 0x80) == 0)
        break;
    }
    return n;
  }
  
  public static String byteArrayToString(byte[] b)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < b.length; i++)
    {
      if (i > 0)
        sb.append(", ");
      String s = Integer.toHexString(b[i] & 0xFF);
      if (s.length() < 2)
        s = "0" + s;
      sb.append(s);
    }
    return sb.toString();
  }
  
  public static void main(String[] args)
  {
    long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };
    for (long n : testNumbers)
    {
      byte[] encoded = encode(n);
      long decoded = decode(encoded);
      System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL"));
    }
  }
}