text:
SUMMARY = "WPE WebKit port pairs the WebKit engine with the Wayland display protocol, \
           allowing embedders to create simple and performant systems based on Web platform technologies. \
           It is designed with hardware acceleration in mind, relying on EGL, the Wayland EGL platform, and OpenGL ES."
HOMEPAGE = "http://www.webkitforwayland.org/"
LICENSE = "BSD & LGPLv2+"
LIC_FILES_CHKSUM = "file://Source/WebCore/LICENSE-LGPL-2.1;md5=a778a33ef338abbaf8b8a7c36b6eec80 "

DEPENDS += " \
    wpebackend \
    bison-native gperf-native harfbuzz-native libxml2-native ruby-native ninja-native chrpath-replacement-native \
    cairo fontconfig freetype glib-2.0 gnutls harfbuzz icu jpeg pcre sqlite3 zlib \
    libpng libsoup-2.4 libwebp libxml2 libxslt \
    virtual/egl virtual/libgles2 \
"

PV = "1.20170926"
SRCREV = "60a107da98ed8484705966e63f5467ac673dd743"

SRC_URI = " git://github.com/WebPlatformForEmbedded/WPEWebKit.git;protocol=https;branch=master \
            file://0001-WebKitMacros-Append-to-I-and-not-to-isystem.patch \
            file://0001-WPE-Some-event-handlers-not-working.patch \
            file://revert_image_decoders-198781.patch \
            file://fix_JSStringRef_type_conversion.patch \
            file://fix_WKString_type_conversion.patch \
            file://fix_API_JSStringRef_type_conversion.patch \
            file://fix_WebEventFactory.patch \
          "

S = "${WORKDIR}/git"

inherit cmake pkgconfig perlnative pythonnative

TOOLCHAIN = "gcc"

PACKAGECONFIG ?= "deviceorientation fullscreenapi fetchapi gamepad geolocation indexeddb libinput mediasource notifications sampling-profiler shadowdom subtitle subtlecrypto udev video webaudio wayland touch gst_gl"

# Mesa only offscreen target support for Westeros backend
# FIXME Needs to be moved to mesa backend
PACKAGECONFIG[westeros-mesa] = "-DUSE_WPEWEBKIT_BACKEND_WESTEROS_MESA=ON,,"

# WPE Platform specific switches
PACKAGECONFIG[intelce] = "-DUSE_WPEWEBKIT_PLATFORM_INTEL_CE=ON -DUSE_HOLE_PUNCH_GSTREAMER=ON,,"
PACKAGECONFIG[nexus] = "-DUSE_WPEWEBKIT_PLATFORM_BCM_NEXUS=ON -DUSE_HOLE_PUNCH_GSTREAMER=ON,,"
PACKAGECONFIG[imx6] = "-DUSE_WPEWEBKIT_PLATFORM_VIV_IMX6=ON -DUSE_HOLE_PUNCH_GSTREAMER=ON,,"
PACKAGECONFIG[westeros] = "-DUSE_WPEWEBKIT_PLATFORM_WESTEROS=ON -DUSE_HOLE_PUNCH_GSTREAMER=ON -DUSE_WESTEROS_SINK=ON,,westeros"

PACKAGECONFIG[wayland] = "-DUSE_WPEWEBKIT_BACKEND_WAYLAND_EGL=ON,,"

# WPE features
PACKAGECONFIG[2dcanvas] = "-DENABLE_ACCELERATED_2D_CANVAS=ON,-DENABLE_ACCELERATED_2D_CANVAS=OFF,"
PACKAGECONFIG[deviceorientation] = "-DENABLE_DEVICE_ORIENTATION=ON,-DENABLE_DEVICE_ORIENTATION=OFF,"
PACKAGECONFIG[encryptedmedia] = "-DENABLE_LEGACY_ENCRYPTED_MEDIA=ON,-DENABLE_LEGACY_ENCRYPTED_MEDIA=OFF,libgcrypt"
PACKAGECONFIG[encryptedmediav1] = "-DENABLE_LEGACY_ENCRYPTED_MEDIA_V1=ON,-DENABLE_LEGACY_ENCRYPTED_MEDIA_V1=OFF,libgcrypt"
PACKAGECONFIG[fetchapi] = "-DENABLE_FETCH_API=ON,-DENABLE_FETCH_API=OFF,"
PACKAGECONFIG[fullscreenapi] = "-DENABLE_FULLSCREEN_API=ON,-DENABLE_FULLSCREEN_API=OFF,"
PACKAGECONFIG[fusion] = "-DUSE_FUSION_API_GSTREAMER=ON,-DUSE_FUSION_API_GSTREAMER=OFF,"
PACKAGECONFIG[gamepad] = "-DENABLE_GAMEPAD=ON,-DENABLE_GAMEPAD=OFF,"
PACKAGECONFIG[geolocation] = "-DENABLE_GEOLOCATION=ON,-DENABLE_GEOLOCATION=OFF,"
PACKAGECONFIG[indexeddb] = "-DENABLE_DATABASE_PROCESS=ON -DENABLE_INDEXED_DATABASE=ON,-DENABLE_DATABASE_PROCESS=OFF -DENABLE_INDEXED_DATABASE=OFF,"
PACKAGECONFIG[libinput] = "-DUSE_WPEWEBKIT_INPUT_LIBINPUT=ON,-DUSE_WPEWEBKIT_INPUT_LIBINPUT=OFF,libinput"
PACKAGECONFIG[mediasource] = "-DENABLE_MEDIA_SOURCE=ON,-DENABLE_MEDIA_SOURCE=OFF,gstreamer1.0 gstreamer1.0-plugins-good"
PACKAGECONFIG[mediastream] = "-DENABLE_MEDIA_STREAM=ON,-DENABLE_MEDIA_STREAM=OFF,openwebrtc"
PACKAGECONFIG[nativevideo] = "-DENABLE_NATIVE_VIDEO=ON,-DENABLE_NATIVE_VIDEO=OFF,"
PACKAGECONFIG[notifications] = "-DENABLE_NOTIFICATIONS=ON,-DENABLE_NOTIFICATIONS=OFF,"
PACKAGECONFIG[sampling-profiler] = "-DENABLE_SAMPLING_PROFILER=ON,-DENABLE_SAMPLING_PROFILER=OFF,"
PACKAGECONFIG[shadowdom] = "-DENABLE_SHADOW_DOM=ON,-DENABLE_SHADOW_DOM=OFF,"
PACKAGECONFIG[subtlecrypto] = "-DENABLE_SUBTLE_CRYPTO=ON,-DENABLE_SUBTLE_CRYPTO=OFF,"
PACKAGECONFIG[subtitle] = "-DENABLE_TEXT_SINK=ON,-DENABLE_TEXT_SINK=OFF,"
PACKAGECONFIG[touch] = "-DENABLE_TOUCH_EVENTS=ON,-DENABLE_TOUCH_EVENTS=OFF,"
PACKAGECONFIG[udev] = "-DUSE_WPEWEBKIT_INPUT_UDEV=ON,-DUSE_WPEWEBKIT_INPUT_UDEV=OFF,udev"
PACKAGECONFIG[video] = "-DENABLE_VIDEO=ON -DENABLE_VIDEO_TRACK=ON,-DENABLE_VIDEO=OFF -DENABLE_VIDEO_TRACK=OFF,gstreamer1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad"
PACKAGECONFIG[webaudio] = "-DENABLE_WEB_AUDIO=ON,-DENABLE_WEB_AUDIO=OFF,gstreamer1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good"

# This enables fatal, error and channel logs. Useful when you want to see some logs on a Release build.
# Use WEBKIT_DEBUG env var to check specific log channel. Check the channel names at Source/WebCore/platform/Logging.h
# Use WEBKIT_DEBUG=all to enable all channels.
PACKAGECONFIG[logs] ="-DENABLE_LOGS=ON,-DENABLE_LOGS=OFF,"

# DRM
PACKAGECONFIG[opencdm] = "-DENABLE_OCDM=ON,-DENABLE_OCDM=OFF,opencdm"
PACKAGECONFIG[playready] = "-DENABLE_PLAYREADY=ON,-DENABLE_PLAYREADY=OFF,playready"
PACKAGECONFIG[provisioning] = "-DENABLE_PROVISIONING=ON,-DENABLE_PROVISIONING=OFF,libprovision,libprovision"

# GStreamer
PACKAGECONFIG[gst_gl] = "-DUSE_GSTREAMER_GL=ON,-DUSE_GSTREAMER_GL=OFF,gstreamer1.0-plugins-bad"
PACKAGECONFIG[gst_httpsrc] = "-DUSE_GSTREAMER_WEBKIT_HTTP_SRC=ON,,"
PACKAGECONFIG[gst_holepunch] = "-DUSE_HOLE_PUNCH_GSTREAMER=ON,,"

EXTRA_OECMAKE += " \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_COLOR_MAKEFILE=OFF -DBUILD_SHARED_LIBS=ON -DPORT=WPE \
    -G Ninja \
"
EXTRANATIVEPATH += "chrpath-native"

# don't build debug
FULL_OPTIMIZATION_remove = "-g"

# WPEWebProcess crashes when built with ARM mode on RPi
ARM_INSTRUCTION_SET_armv7a = "thumb"
ARM_INSTRUCTION_SET_armv7r = "thumb"
ARM_INSTRUCTION_SET_armv7m = "thumb"
ARM_INSTRUCTION_SET_armv7ve = "thumb"

do_compile() {
    ${STAGING_BINDIR_NATIVE}/ninja ${PARALLEL_MAKE} libWPEWebKit.so libWPEWebInspectorResources.so WPEWebProcess WPENetworkProcess WPEDatabaseProcess
}
do_compile[progress] = "outof:^\[(\d+)/(\d+)\]\s+"

do_install() {
    DESTDIR=${D} cmake -DCOMPONENT=Development -P ${B}/Source/WebKit2/cmake_install.cmake
    DESTDIR=${D} cmake -DCOMPONENT=Development -P ${B}/Source/JavaScriptCore/cmake_install.cmake

    install -d ${D}${libdir}
    cp -av --no-preserve=ownership ${B}/lib/libWPE* ${D}${libdir}/
    install -m 0755 ${B}/lib/libWPEWebInspectorResources.so ${D}${libdir}/
    # Hack: Remove the RPATH embedded in libWPEWebKit.so
    chrpath --delete ${D}${libdir}/libWPE*

    install -d ${D}${bindir}
    install -m755 ${B}/bin/WPEWebProcess ${D}${bindir}/
    install -m755 ${B}/bin/WPENetworkProcess ${D}${bindir}/
    install -m755 ${B}/bin/WPEDatabaseProcess ${D}${bindir}/

    # Hack: Remove RPATHs embedded in apps
    chrpath --delete ${D}${bindir}/WPEWebProcess
    chrpath --delete ${D}${bindir}/WPENetworkProcess
    chrpath --delete ${D}${bindir}/WPEDatabaseProcess
}

LEAD_SONAME = "libWPEWebKit.so"

PACKAGES =+ "${PN}-web-inspector-plugin"

FILES_${PN}-web-inspector-plugin += "${libdir}/libWPEWebInspectorResources.so"
INSANE_SKIP_${PN}-web-inspector-plugin = "dev-so"

PACKAGES =+ "${PN}-platform-plugin"

RDEPS_MEDIASOURCE = " \
    gstreamer1.0-plugins-good-isomp4 \
"

RDEPS_VIDEO = " \
    gstreamer1.0-plugins-base-app \
    gstreamer1.0-plugins-base-playback \
    gstreamer1.0-plugins-good-souphttpsrc \
"

RDEPS_WEBAUDIO = " \
    gstreamer1.0-plugins-good-wavparse \
"

# plugins-bad config option 'dash' -> gstreamer1.0-plugins-bad-dashdemux
# plugins-bad config option 'videoparsers' -> gstreamer1.0-plugins-bad-videoparsersbad

RDEPS_EXTRA = " \
    gstreamer1.0-plugins-base-audioconvert \
    gstreamer1.0-plugins-base-audioresample \
    gstreamer1.0-plugins-base-gio \
    gstreamer1.0-plugins-base-videoconvert \
    gstreamer1.0-plugins-base-videoscale \
    gstreamer1.0-plugins-base-volume \
    gstreamer1.0-plugins-base-typefindfunctions \
    gstreamer1.0-plugins-good-audiofx \
    gstreamer1.0-plugins-good-audioparsers \
    gstreamer1.0-plugins-good-autodetect \
    gstreamer1.0-plugins-good-avi \
    gstreamer1.0-plugins-good-deinterlace \
    gstreamer1.0-plugins-good-interleave \
    gstreamer1.0-plugins-bad-dashdemux \
    gstreamer1.0-plugins-bad-mpegtsdemux \
    gstreamer1.0-plugins-bad-smoothstreaming \
    gstreamer1.0-plugins-bad-videoparsersbad \
"

RDEPS_VIDEOGL = " \
    gstreamer1.0-omx \
    gstreamer1.0-plugins-bad-opengl \
"
#fixme
#    gstreamer1.0-plugins-bad-faad (videogl=> aac)
#    gstreamer1.0-plugins-bad-hls
#    gstreamer1.0-plugins-ugly-mpg123

RDEPS_MEDIASOURCE += "${RDEPS_EXTRA}"
RDEPS_VIDEO += "${RDEPS_EXTRA}"
RDEPS_WEBAUDIO += "${RDEPS_EXTRA}"

RRECOMMENDS_${PN} += " \
    ca-certificates \
    shared-mime-info \
    ttf-bitstream-vera \
    ${PN}-platform-plugin \
"
# FIXME: add this conditionally based on selected pkconfig entries
RDEPENDS_${PN} = " ${RDEPS_MEDIASOURCE} ${RDEPS_VIDEO} ${RDEPS_VIDEOGL} ${RDEPS_WEBAUDIO} ${RDEPS_EXTRA} "

repository: psaavedra/meta-webkit

repo_name: psaavedra/meta-webkit

extension: bb


text:
#include <bits/stdc++.h>

using namespace std;

int main() {
  int n;
  cin >> n;
  map<int, int> left;
  map<int, int> right;

  for (int i=0; i<n; i++) {
    int x, a;
    cin >> x;
    cin >> a;
    if (x>0) {
      right[x] = a;
    } else {
      left[-x] = a;
    }
  }

  int ls = left.size();
  int rs = right.size();
  int lower = min(ls, rs);

  map<int,int>::iterator itr = right.begin();
  map<int,int>::iterator itl = left.begin();
  int total = 0;
  for (int i=0; i<lower; i++) {
    total += itl++->second;
    total += itr++->second;
  }
  if (ls>rs) {
    total += itl++->second;
  } else if (rs>ls) {
    total += itr++->second;
  }
  cout << total << endl;
}

license: MIT

repository: shioju/codeforces

license_type: permissive

repo_name: shioju/codeforces

branch_name: refs/heads/master

extension: cpp


text:
/*	Copyright  (c)	Günter Woigk 1994 - 2021
					mailto:kio@little-bat.de

	This file is free software.

	Permission to use, copy, modify, distribute, and sell this software
	and its documentation for any purpose is hereby granted without fee,
	provided that the above copyright notice appears in all copies and
	that both that copyright notice, this permission notice and the
	following disclaimer appear in supporting documentation.

	THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY,
	NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
	A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE COPYRIGHT HOLDER
	BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE OF THIS SOFTWARE,
	TO THE EXTENT PERMITTED BY APPLICABLE LAW.
*/

#include "Z80/goodies/z80_opcodes.h"
#include "Z80Assembler.h"

static cValue N2(2);

static bool lceq(cptr w, cptr s)
{
	// compare word w with string literal s
	// s must be lower case
	// w may be mixed case

	assert(s && w);
	while (*s)
	{
		if ((*w++ | 0x20) != *s++) return false;
	}
	return *w == 0;
}

void Z80Assembler::storeEDopcode(int n)
{
	if (target_z80_or_z180) return store(PFX_ED, n);
	throw SyntaxError(
		syntax_8080 ? "no i8080 opcode (use option --asm8080 and --z80)" : "no i8080 opcode (option --8080)");
}

void Z80Assembler::storeIXopcode(int n)
{
	if (target_z80_or_z180) return store(PFX_IX, n);
	throw SyntaxError(
		syntax_8080 ? "no i8080 opcode (use option --asm8080 and --z80)" : "no i8080 opcode (option --8080)");
}

void Z80Assembler::storeIYopcode(int n)
{
	if (target_z80_or_z180) return store(PFX_IY, n);
	throw SyntaxError(
		syntax_8080 ? "no i8080 opcode (use option --asm8080 and --z80)" : "no i8080 opcode (option --8080)");
}

enum // enumeration of Z80 identifiers
{
	// clang-format off

	NIX,	// end of line

	// conditions:
	NZ,		Z,		NC,		CY,		PO,		PE,		P,		M,	// <-- DO NOT REORDER!

	// 8-bit registers:
	RB,		RC,		RD,		RE,		RH,		RL,		XHL,	RA,	// <-- DO NOT REORDER!
	XH,		XL,		YH,		YL,									// <-- DO NOT REORDER!
	RI,		RR,

	// 16-bit registers:
	BC,		DE,		HL,		SP,			// <-- DO NOT REORDER!
	IX,		IY,		AF,					// <-- DO NOT REORDER!

	// others:
	XBC,	XDE,	XC,		XSP,	XIX,	XIY,
	XNN,	NN,
	XMMBC, XMMDE, XMMHL, XBCPP, XDEPP, XHLPP,	// (hl++) etc. for compound opcodes

	// clang-format on
};

int Z80Assembler::getCondition(SourceLine& q, bool expect_comma)
{
	// test and skip over condition
	// returns NIX or enum [Z, NZ .. P]
	// expect_comma
	//   must be set if cond must be followed by a comma --> jr, jp and call
	//   and must be cleared for --> ret

	cptr p = q.p;
	cstr w = q.nextWord();
	if (w[0] == 0) return NIX;
	if (expect_comma && !q.testComma())
	{
		q.p = p;
		return NIX;
	}

	char c1 = *w++ | 0x20;
	char c2 = *w++ | 0x20;

	if (c2 == 0x20) // strlen = 1
	{
		if (c1 == 'z') return Z;
		if (c1 == 'c') return CY;
		if (c1 == 'p') return P;
		if (c1 == 'm') return M;
		if (c1 == 's') return M; // source seen ...
	}
	else if (*w == 0) // strlen = 2
	{
		if (c1 == 'n')
		{
			if (c2 == 'z') return NZ;
			if (c2 == 'c') return NC;
		}
		if (c1 == 'p')
		{
			if (c2 == 'o') return PO;
			if (c2 == 'e') return PE;
		}
	}
	throw SyntaxError("illegal condition");
}

int Z80Assembler::getRegister(SourceLine& q, Value& n, bool with_qreg)
{
	// test and skip over register or value
	// returns register enum:
	//   normal register:     n and v are void (not modified)
	//   NN, XNN, XIX or XIY: n and v are set
	//   does not return i, r, (c), ix, iy or related if target_8080
	// throws on error
	// throws at end of line

	cptr p = q.p;
	cstr w = q.nextWord();

	char c1 = *w++ | 0x20;
	if (c1 == 0x20) throw SyntaxError("unexpected end of line");
	char c2 = *w++ | 0x20;

	if (c2 == 0x20) // strlen=1
	{
		switch (c1)
		{
		case 'a': return RA;
		case 'b': return RB;
		case 'c': return RC;
		case 'd': return RD;
		case 'e': return RE;
		case 'h': return RH;
		case 'l': return RL;
		case 'i':
			if (target_z80_or_z180)
				return RI;
			else
				goto no_8080;
		case 'r':
			if (target_z80_or_z180)
				return RR;
			else
				goto no_8080;

		case '(':
		{
			int r;
			if (q.testWord("hl"))
			{
				r = XHL;
				if (*q == '+' && *(q.p + 1) == '+')
				{
					q += 2;
					r = XHLPP;
				}
				q.expect(')');
				return r;
			}
			if (q.testWord("de"))
			{
				r = XDE;
				if (*q == '+' && *(q.p + 1) == '+')
				{
					q += 2;
					r = XDEPP;
				}
				q.expect(')');
				return r;
			}
			if (q.testWord("bc"))
			{
				r = XBC;
				if (*q == '+' && *(q.p + 1) == '+')
				{
					q += 2;
					r = XBCPP;
				}
				q.expect(')');
				return r;
			}
			if (q.testWord("sp"))
			{
				q.expect(')');
				return XSP;
			}

			if (*q == '-' && *(q.p + 1) == '-')
			{
				p = q.p;
				q.p += 2;
				if (q.testWord("hl"))
				{
					q.expect(')');
					return XMMHL;
				}
				if (q.testWord("de"))
				{
					q.expect(')');
					return XMMDE;
				}
				if (q.testWord("bc"))
				{
					q.expect(')');
					return XMMBC;
				}
				q.p = p;
			}

			r = XNN;
			n = 0;

			if (q.testWord("ix"))
			{
				if (target_8080) goto no_8080;
				r = XIX;
				if (q.testChar(')')) return r;
			}
			if (q.testWord("iy"))
			{
				if (target_8080) goto no_8080;
				r = XIY;
				if (q.testChar(')')) return r;
			}
			if (q.testWord("c"))
			{
				if (target_8080) goto no_8080;
				q.expect(')');
				return XC;
			}

			n = value(q);
			if (r != XNN && n.value != int8(n) && n.is_valid()) throw SyntaxError("offset out of range");
			q.expectClose();
			return r;
		}
		}
	}
	else if (*w == 0) // strlen=2
	{
		switch (c1)
		{
		case 'a':
			if (c2 == 'f')
				return AF;
			else
				break;
		case 'b':
			if (c2 == 'c')
				return BC;
			else
				break;
		case 'd':
			if (c2 == 'e')
				return DE;
			else
				break;
		case 'h':
			if (c2 == 'l')
				return HL;
			else
				break;
		case 's':
			if (c2 == 'p')
				return SP;
			else
				break;
		case 'i':
			if (c2 == 'x')
			{
				if (target_z80_or_z180)
					return IX;
				else
					goto no_8080;
			}
			if (c2 == 'y')
			{
				if (target_z80_or_z180)
					return IY;
				else
					goto no_8080;
			}
			else
				break;
		case 'x':
			if (c2 == 'h')
			{
				if (target_z80)
					return XH;
				else
					goto z80_only;
			}
			if (c2 == 'l')
			{
				if (target_z80)
					return XL;
				else
					goto z80_only;
			}
			else
				break;
		case 'y':
			if (c2 == 'h')
			{
				if (target_z80)
					return YH;
				else
					goto z80_only;
			}
			if (c2 == 'l')
			{
				if (target_z80)
					return YL;
				else
					goto z80_only;
			}
			else
				break;
		}
	}
	else // ≥3 letters
	{
		char c3 = *w++ | 0x20;
		char c4 = *w++ | 0x20;

		if (c4 == 0x20) // strlen=3
		{
			// target_z80:  test for ixh, ixl, iyh, iyl:					2016-10-01
			// target_8080: no test: ixh, ixl, iyh, iyl are valid label names (not rejected in asmLabel())
			// target_z180: no test: ixh, ixl, iyh, iyl are valid label names (not rejected in asmLabel())
			if (target_z80 && c1 == 'i')
			{
				int rval = c2 == 'x' ? c3 == 'h' ? XH :
									   c3 == 'l' ? XL :
												   0 :
						   c2 == 'y' ? c3 == 'h' ? YH :
									   c3 == 'l' ? YL :
												   0 :
									   0;
				if (rval) return rval;
			}
		}
		else if (*w == 0) // strlen=4
		{
			if (with_qreg && c2 != c4) // detect quad_regs, e.g. 'DEHL', but not 2x same reg, e.g. 'HLHL'
			{
				static const char hi[] = "bdhsii";
				static const char lo[] = "celpxy";
				cptr			  p2   = strchr(lo, c2);
				cptr			  p4   = strchr(lo, c4);
				if (p2 && p4 && c1 == hi[p2 - lo] && c3 == hi[p4 - lo])
				{
					if (target_8080 && (c1 == 'i' || c3 == 'i')) goto no_8080; // IX, IY
					return 256 * (BC + int(p2 - lo)) + BC + int(p4 - lo);	   // "DEHL" -> DE*256 + HL
				}
			}
		}
	}

	// not a register: evaluate expression:
	q.p = p;
	n	= value(q);
	if (target_8080 || !q.testChar('(')) return NN;

	// SDASZ80 syntax: n(IX)
	if (n.value != int8(n) && n.is_valid()) throw SyntaxError("offset out of range");
	if (q.testWord("ix"))
	{
		q.expectClose();
		return XIX;
	}
	if (q.testWord("iy"))
	{
		q.expectClose();
		return XIY;
	}
	throw SyntaxError("syntax error");

z80_only:
	if (target_z180) throw SyntaxError("illegal register: the Z180 traps illegal instructions");
no_8080:
	throw SyntaxError("no 8080 register");
}

void Z80Assembler::asmZ80Instr(SourceLine& q, cstr w)
{
	// Assemble Z80 opcode

	// remember: *ALWAYS* evaluate _all_ values _before_ storing the first opcode byte: wg. '$'

	int	  r, r2;
	Value n, n2;
	int32 instr;
	cptr  depp = nullptr; // dest error position ptr: for instructions where
						  // source is parsed before dest can be checked
	assert(current_segment_ptr);

	// strlen-Verteiler:

	switch (strlen(w))
	{
	case 0: return; // end of line
	case 1: goto misc;
	case 2: instr = peek2X(w); break;
	case 3: instr = int32(peek3X(w)); break;
	case 4: instr = int32(peek4X(w)); break;
	case 5: goto wlen5;
	default: goto misc;
	}

	switch (instr | 0x20202020)
	{
	case ' jmp':
	case ' mov': throw SyntaxError("no Z80 assembler opcode (use option --asm8080)");

	case ' nop': return store(NOP);
	case '  ei': return store(EI);
	case '  di': return store(DI);
	case ' scf': return store(SCF);
	case ' ccf': return store(CCF);
	case ' cpl': return store(CPL);
	case ' daa': return store(DAA);
	case ' rra': return store(RRA);
	case ' rla': return store(RLA);
	case 'rlca': return store(RLCA);
	case 'rrca': return store(RRCA);
	case 'halt': return store(HALT);
	case ' exx':
		if (target_8080) goto ill_8080;
		return store(EXX);

	case 'djnz':
		// djnz nn
		if (target_8080) goto ill_8080;
		instr = DJNZ;
		goto jr;

	case '  jr':
		// jr nn
		// jr cc,nn
		if (target_8080) goto ill_8080;
		r2 = getCondition(q, yes);
		if (r2 > CY) throw SyntaxError("illegal condition");
		instr = r2 == NIX ? JR : JR_NZ + (r2 - NZ) * 8;
		goto jr;

	jr:
		r = getRegister(q, n);
		if (r != NN) goto ill_dest;
		store(instr);
		return storeOffset(n - dollar() - N2);

	case '  jp':
		// jp NN
		// jp rr	hl ix iy
		// jp (rr)	hl ix iy
		r2 = getCondition(q, yes);
		r  = getRegister(q, n);
		if (r == NN)
		{
			store(r2 == NIX ? JP : JP_NZ + (r2 - NZ) * 8);
			storeWord(n);
			return;
		}
		if (r == HL || r == XHL)
		{
			store(JP_HL);
			return;
		}
		// note: getRegister() returns XIX|XIY and n=0 for jp (ix|iy):
		// validity test not required: 'jp (ix+dis) will fail when 'dis' becomes valid.
		if (r == IX || (r == XIX && n.value == 0))
		{
			store(PFX_IX, JP_HL);
			return;
		}
		if (r == IY || (r == XIY && n.value == 0))
		{
			store(PFX_IY, JP_HL);
			return;
		}
		goto ill_dest;

	case ' ret':
		// ret
		// ret cc
		r = getCondition(q, no);
		return store(r == NIX ? RET : RET_NZ + (r - NZ) * 8);

	case 'call':
		// call nn
		// call cc,nn
		r2 = getCondition(q, yes);
		r  = getRegister(q, n);
		if (r == NN)
		{
			store(r2 == NIX ? CALL : CALL_NZ + (r2 - NZ) * 8);
			storeWord(n);
			return;
		}
		goto ill_dest;

	case ' rst':
		// rst n		0 .. 7  or  0*8 .. 7*8
		n = value(q);
		if (n.value % 8 == 0) n.value >>= 3;
		if (n.is_valid() && n.value >> 3)
			throw SyntaxError("illegal vector number");
		else
			return store(RST00 + n.value * 8);

	case 'push': instr = PUSH_HL; goto pop;
	case ' pop':
		instr = POP_HL;
		goto pop;

		// pop rr		bc de hl af ix iy
		// pop rrrr		bcde bchl bcix bciy debc ...
	pop:
		r = getRegister(q, n, yes); // with qreg

		if (r > 256) // qreg
		{
			if (instr == PUSH_HL)
			{
				r2 = r >> 8;
				r  = r & 0xff;
			}
			else
			{
				r2 = r & 0xff;
				r  = r >> 8;
			}

			if (r2 >= BC && r2 <= HL)
				store(instr + (r2 - HL) * 16);
			else if (r2 == AF)
				store(instr + 16);
			else if (r2 == IX)
				store(PFX_IX, instr);
			else if (r2 == IY)
				store(PFX_IY, instr);
			else if (instr == POP_HL)
				goto ill_target;
			else
				goto ill_source;
		}

		if (r >= BC && r <= HL) return store(instr + (r - HL) * 16);
		if (r == AF) return store(instr + 16);
		if (r == IX) return store(PFX_IX, instr);
		if (r == IY) return store(PFX_IY, instr);
		if (instr == POP_HL)
			goto ill_target;
		else
			goto ill_source;

	case ' dec': r2 = 1; goto inc;
	case ' inc':
		r2 = 0;
		goto inc;

		// inc r	a b c d e h l (hl) (ix+d)
		// inc xh
		// inc rr	bc de hl sp ix iy
	inc:
		r = getRegister(q, n);

		instr = INC_xHL + r2; // inc (hl)  or  dec (hl)
		if (r <= RA)
		{
			store(instr + (r - XHL) * 8);
			return;
		}
		if (r == XIX)
		{
			store(PFX_IX, instr, n.value);
			return;
		} // note: offset tested by getRegister()
		if (r == XIY)
		{
			store(PFX_IY, instr, n.value);
			return;
		} // ""
		if (r <= XL)
		{
			store(PFX_IX, instr + (r + RH - XH - XHL) * 8);
			return;
		}
		if (r <= YL)
		{
			store(PFX_IY, instr + (r + RH - YH - XHL) * 8);
			return;
		}

		if (r == XMMHL) return store(DEC_HL, instr);
		if (r == XHLPP) return store(instr, INC_HL);

		instr = INC_HL + r2 * 8; // inc hl or dec hl
		if (r >= BC && r <= SP) return store(instr + (r - HL) * 16);
		if (r == IX) return store(PFX_IX, instr);
		if (r == IY) return store(PFX_IY, instr);
		goto ill_target;

	case '  ex':
		// ex af,af'
		// ex hl,de		(or vice versa)
		// ex hl,(sp)
		// ex ix,(sp)	valid illegal. 2006-09-13 kio
		// ex ix,de		does not work: swaps de and hl only. 2006-09-13 kio
		r	 = getRegister(q, n);
		depp = q.p;
		q.expectComma();
		r2 = getRegister(q, n2);

		if (r == AF)
		{
			if (target_8080) goto ill_8080;
			q.test_char('\'');
			if (r2 == AF)
				return store(EX_AF_AF);
			else
				goto ill_source;
		}
		if (r == HL)
		{
			if (r2 == DE) return store(EX_DE_HL);
			if (r2 == XSP) return store(EX_HL_xSP);
			goto ill_source;
		}
		if (r == DE)
		{
			if (r2 == HL) return store(EX_DE_HL);
			goto ill_source;
		}
		if (r == IX)
		{
			if (r2 == XSP) return store(PFX_IX, EX_HL_xSP);
			goto ill_source;
		}
		if (r == IY)
		{
			if (r2 == XSP) return store(PFX_IY, EX_HL_xSP);
			goto ill_source;
		}
		if (r == XSP)
		{
			if (r2 == HL) return store(EX_HL_xSP);
			if (r2 == IX) return store(PFX_IX, EX_HL_xSP);
			if (r2 == IY)
				return store(PFX_IY, EX_HL_xSP);
			else
				goto ill_source;
		}
		goto ill_target;

	case ' add':
		//	add	a,xxx
		//	add hl,rr	bc de hl sp
		//	add ix,rr	bc de ix sp
		r = getRegister(q, n);
		if (r == RA || q.testEol())
		{
			instr = ADD_B;
			goto cp_a;
		}
		depp = q.p;
		q.expectComma();
		r2 = getRegister(q, n2);

		if (r2 < BC || (r2 > SP && r2 != r)) goto ill_source;
		if (r == HL)
		{
		addhl:
			return store(ADD_HL_BC + (r2 - BC) * 16);
		}
		if (r == IX)
		{
			if (r2 == HL) goto ill_source;
			if (r2 == r) r2 = HL;
			store(PFX_IX);
			goto addhl;
		}
		if (r == IY)
		{
			if (r2 == HL) goto ill_source;
			if (r2 == r) r2 = HL;
			store(PFX_IY);
			goto addhl;
		}
		goto ill_target;

	case ' sbc':
		//	sbc	a,xxx
		//	sbc hl,rr	bc de hl sp
		r = getRegister(q, n);
		if (r == RA || q.testEol())
		{
			instr = SBC_B;
			goto cp_a;
		}
		instr = SBC_HL_BC;
		goto adc;

	case ' adc':
		//	adc	a,xxx
		//	adc hl,rr	bc de hl sp
		r = getRegister(q, n);
		if (r == RA || q.testEol())
		{
			instr = ADC_B;
			goto cp_a;
		}
		instr = ADC_HL_BC;
		goto adc;

	adc:
		if (r != HL) goto ill_target;
		q.expectComma();
		r2 = getRegister(q, n2);
		if (r2 >= BC && r2 <= SP) return storeEDopcode(instr + (r2 - BC) * 16);
		goto ill_source;

	case ' and': instr = AND_B; goto cp;
	case ' xor': instr = XOR_B; goto cp;
	case ' sub': instr = SUB_B; goto cp;
	case '  or': instr = OR_B; goto cp;
	case '  cp':
		instr = CP_B;
		goto cp;

		// cp a,N			first argument (the 'a' register) may be omitted
		// cp a,r			a b c d e h l (hl)
		// cp a,xh
		// cp a,(ix+dis)

		// common handler for
		// add adc sub sbc and or xor cp

	cp:
		r = getRegister(q, n);
	cp_a:
		depp = q.p;
		if (q.testComma())
		{
			if (r != RA)
				goto ill_target;
			else
				r = getRegister(q, n);
		}

		if (r <= RA)
		{
			store(instr + r - RB);
			return;
		}
		if (r == NN)
		{
			store(instr + CP_N - CP_B);
			storeByte(n);
			return;
		}
		if (r == XIX)
		{
			store(PFX_IX, instr + XHL - RB, n.value);
			return;
		}
		if (r == XIY)
		{
			store(PFX_IY, instr + XHL - RB, n.value);
			return;
		}
		if (r <= XL)
		{
			store(PFX_IX, instr + r + RH - XH - RB);
			return;
		}
		if (r <= YL)
		{
			store(PFX_IY, instr + r + RH - YH - RB);
			return;
		}
		if (r == XHLPP)
		{
			store(instr + XHL - RB, INC_HL);
			return;
		}
		if (r == XMMHL)
		{
			store(DEC_HL, instr + XHL - RB);
			return;
		}
		goto ill_source;

	case '  ld':
		r	 = getRegister(q, n, yes); // allow quad reg
		depp = q.p;
		q.expectComma();
		r2 = getRegister(q, n2, r == XNN); // allow quad reg if dest = '(NN)'
		assert(r >= RB);
		assert(r2 >= RB);

		switch (r)
		{
		case RI:
			// ld i,a
			if (r2 == RA) return storeEDopcode(LD_I_A);
			goto ill_source;

		case RR:
			// ld r,a
			if (r2 == RA) return storeEDopcode(LD_R_A);
			goto ill_source;

		case IX:
			// ld ix,rr		bc de			Goodie
			// ld ix,(NN)
			// ld ix,NN
			instr = PFX_IX;
			goto ld_iy;

		case IY:
			// ld iy,rr		bc de			Goodie
			// ld iy,(NN)
			// ld iy,NN
			instr = PFX_IY;
		ld_iy:
			if (r2 == NN)
			{
				store(instr, LD_HL_NN);
				storeWord(n2);
				return;
			}
			if (r2 == XNN)
			{
				store(instr, LD_HL_xNN);
				storeWord(n2);
				return;
			}
			if (r2 == BC)
			{
				if (target_z180) goto ill_opcode;
				return store(instr, LD_H_B, instr, LD_L_C);
			}
			if (r2 == DE)
			{
				if (target_z180) goto ill_opcode;
				return store(instr, LD_H_D, instr, LD_L_E);
			}
			goto ill_source;

		case HL:
			// ld hl,rr		bc de			Goodie
			// ld hl,(ix+d)					Goodie
			// ld hl,(NN)
			// ld hl,NN
			if (r2 == BC)
			{
				store(LD_H_B, LD_L_C);
				return;
			}
			if (r2 == DE)
			{
				store(LD_H_D, LD_L_E);
				return;
			}
			if (r2 == NN)
			{
				store(LD_HL_NN);
				storeWord(n2);
				return;
			}
			if (r2 == XNN)
			{
				store(LD_HL_xNN);
				storeWord(n2);
				return;
			}
			if (r2 == XIX)
			{
				store(PFX_IX, LD_L_xHL, n2.value);
				store(PFX_IX, LD_H_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			if (r2 == XIY)
			{
				store(PFX_IY, LD_L_xHL, n2.value);
				store(PFX_IY, LD_H_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			goto ill_source;

		case BC:
			// ld bc,NN
			// ld bc,(NN)
			// ld bc,rr		de hl ix iy		Goodie
			// ld bc,(hl)					Goodie
			// ld bc,(ix+d)					Goodie
			// ld bc,(hl++)					Goodie
			if (r2 == NN)
			{
				store(LD_BC_NN);
				storeWord(n2);
				return;
			}
			if (r2 == XNN)
			{
				storeEDopcode(LD_BC_xNN);
				storeWord(n2);
				return;
			}
			if (r2 == DE)
			{
				store(LD_B_D, LD_C_E);
				return;
			}
			if (r2 == HL)
			{
				store(LD_B_H, LD_C_L);
				return;
			}
			if (r2 == IX)
			{
				if (target_z180) goto ill_opcode;
				store(PFX_IX, LD_B_H, PFX_IX, LD_C_L);
				return;
			}
			if (r2 == IY)
			{
				if (target_z180) goto ill_opcode;
				store(PFX_IY, LD_B_H, PFX_IY, LD_C_L);
				return;
			}
			if (r2 == XHL)
			{
				store(LD_C_xHL, INC_HL, LD_B_xHL, DEC_HL);
				return;
			}
			if (r2 == XIX)
			{
				store(PFX_IX, LD_C_xHL, n2.value);
				store(PFX_IX, LD_B_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			if (r2 == XIY)
			{
				store(PFX_IY, LD_C_xHL, n2.value);
				store(PFX_IY, LD_B_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			if (r2 == XHLPP)
			{
				store(LD_C_xHL, INC_HL, LD_B_xHL, INC_HL);
				return;
			}
			if (r2 == XMMHL)
			{
				store(DEC_HL, LD_B_xHL, DEC_HL, LD_C_xHL);
				return;
			}
			goto ill_source;

		case DE:
			// ld de,NN
			// ld de,(NN)
			// ld de,rr		bc hl ix iy		Goodie
			// ld de,(hl)					Goodie
			// ld de,(ix+d)					Goodie
			// ld de,(hl++)					Goodie
			if (r2 == NN)
			{
				store(LD_DE_NN);
				storeWord(n2);
				return;
			}
			if (r2 == XNN)
			{
				storeEDopcode(LD_DE_xNN);
				storeWord(n2);
				return;
			}
			if (r2 == BC)
			{
				store(LD_D_B, LD_E_C);
				return;
			}
			if (r2 == HL)
			{
				store(LD_D_H, LD_E_L);
				return;
			}
			if (r2 == IX)
			{
				if (target_z180) goto ill_opcode;
				store(PFX_IX, LD_D_H, PFX_IX, LD_E_L);
				return;
			}
			if (r2 == IY)
			{
				if (target_z180) goto ill_opcode;
				store(PFX_IY, LD_D_H, PFX_IY, LD_E_L);
				return;
			}
			if (r2 == XHL)
			{
				store(LD_E_xHL, INC_HL, LD_D_xHL, DEC_HL);
				return;
			}
			if (r2 == XIX)
			{
				store(PFX_IX, LD_E_xHL, n2.value);
				store(PFX_IX, LD_D_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			if (r2 == XIY)
			{
				store(PFX_IY, LD_E_xHL, n2.value);
				store(PFX_IY, LD_D_xHL, n2.value + 1);
				return;
			} // ignored: n2+1 may wrap!
			if (r2 == XHLPP)
			{
				store(LD_E_xHL, INC_HL, LD_D_xHL, INC_HL);
				return;
			}
			if (r2 == XMMHL)
			{
				store(DEC_HL, LD_D_xHL, DEC_HL, LD_E_xHL);
				return;
			}
			goto ill_source;

		case SP:
			// ld sp,rr		hl ix iy
			// ld sp,NN
			// ld sp,(NN)
			if (r2 == HL)
			{
				store(LD_SP_HL);
				return;
			}
			if (r2 == IX)
			{
				store(PFX_IX, LD_SP_HL);
				return;
			}
			if (r2 == IY)
			{
				store(PFX_IY, LD_SP_HL);
				return;
			}
			if (r2 == NN)
			{
				store(LD_SP_NN);
				storeWord(n2);
				return;
			}
			if (r2 == XNN)
			{
				storeEDopcode(LD_SP_xNN);
				storeWord(n2);
				return;
			}
			goto ill_source;

		case XIX:
			// ld (ix+d),r		a b c d e h l a
			// ld (ix+d),n
			// ld (ix+d),rr		bc de hl		Goodie
			instr = PFX_IX;
			goto ld_xiy;

		case XIY:
			// ld (iy+d),r		a b c d e h l a
			// ld (iy+d),n
			// ld (iy+d),rr		bc de hl		Goodie
			instr = PFX_IY;
		ld_xiy:
			if (r2 <= RA && r2 != XHL)
			{
				store(instr, LD_xHL_B + r2 - RB, n.value);
				return;
			}
			if (r2 == NN)
			{
				store(instr, LD_xHL_N, n.value);
				storeByte(n2);
				return;
			}
			if (r2 == HL)
			{
				store(instr, LD_xHL_L, n.value);
				store(instr, LD_xHL_H, n.value + 1);
				return;
			} // ignored: n+1 may wrap!
			if (r2 == DE)
			{
				store(instr, LD_xHL_E, n.value);
				store(instr, LD_xHL_D, n.value + 1);
				return;
			} // ignored: n+1 may wrap!
			if (r2 == BC)
			{
				store(instr, LD_xHL_C, n.value);
				store(instr, LD_xHL_B, n.value + 1);
				return;
			} // ignored: n+1 may wrap!
			goto ill_source;

		case XHL:
			// ld (hl),r		a b c d e h l a
			// ld (hl),n
			// ld (hl),rr		bc de			Goodie
			if (r2 <= RA && r2 != XHL)
			{
				store(LD_xHL_B + r2 - RB);
				return;
			}
			if (r2 == NN)
			{
				store(LD_xHL_N);
				storeByte(n2);
				return;
			}
			if (r2 == BC)
			{
				store(LD_xHL_C, INC_HL, LD_xHL_B, DEC_HL);
				return;
			}
			if (r2 == DE)
			{
				store(LD_xHL_E, INC_HL, LD_xHL_D, DEC_HL);
				return;
			}
			goto ill_source;

		case XNN:
			// ld (NN),a
			// ld (NN),hl	hl ix iy
			// ld (NN),rr	bc de sp
			// ld (NN),rrrr	dehl, ...			Goodie

			for (;;)
			{
				if (int8(r2) == RA) { store(LD_xNN_A); }
				else if (int8(r2) == HL) { store(LD_xNN_HL); }
				else if (int8(r2) == IX) { store(PFX_IX, LD_xNN_HL); }
				else if (int8(r2) == IY) { store(PFX_IY, LD_xNN_HL); }
				else if (int8(r2) == BC) { storeEDopcode(LD_xNN_BC); }
				else if (int8(r2) == DE) { storeEDopcode(LD_xNN_DE); }
				else if (int8(r2) == SP) { storeEDopcode(LD_xNN_SP); }
				else
					goto ill_source;
				storeWord(n);
				if (r2 <= 255) return;
				// quad register:		// 1st loop stored low register
				n.value += 2; // 2nd loop for high word:
				r2 = r2 >> 8; // increment address and fetch high register id
			}

		case XBC:
			// ld (bc),a
			if (r2 == RA) return store(LD_xBC_A);
			goto ill_source;

		case XDE:
			// ld (de),a
			if (r2 == RA) return store(LD_xDE_A);
			goto ill_source;

		case XMMBC:
			// ld (--bc),a
			if (r2 == RA) return store(DEC_BC, LD_xBC_A);
			goto ill_source;

		case XMMDE:
			// ld (--de),a
			if (r2 == RA) return store(DEC_DE, LD_xDE_A);
			goto ill_source;

		case XMMHL:
			// ld (--hl),r
			// ld (--hl),rr
			// ld (--hl),N
			if (r2 <= RA && r2 != XHL)
			{
				store(DEC_HL, LD_xHL_B + (r2 - RB));
				return;
			}
			if (r2 == BC)
			{
				store(DEC_HL, LD_xHL_B, DEC_HL, LD_xHL_C);
				return;
			}
			if (r2 == DE)
			{
				store(DEC_HL, LD_xHL_D, DEC_HL, LD_xHL_E);
				return;
			}
			if (r2 == NN)
			{
				store(DEC_HL, LD_xHL_N);
				storeByte(n2);
				return;
			}
			goto ill_source;

		case XBCPP:
			// ld (bc++),a
			if (r2 == RA) return store(LD_xBC_A, INC_BC);
			goto ill_source;

		case XDEPP:
			// ld (de++),a
			if (r2 == RA) return store(LD_xDE_A, INC_DE);
			goto ill_source;

		case XHLPP:
			// ld (hl++),r
			// ld (hl++),rr
			// ld (hl++),N
			if (r2 <= RA && r2 != XHL)
			{
				store(LD_xHL_B + (r2 - RB), INC_HL);
				return;
			}
			if (r2 == BC)
			{
				store(LD_xHL_C, INC_HL, LD_xHL_B, INC_HL);
				return;
			}
			if (r2 == DE)
			{
				store(LD_xHL_E, INC_HL, LD_xHL_D, INC_HL);
				return;
			}
			if (r2 == NN)
			{
				store(LD_xHL_N);
				storeByte(n2);
				store(INC_HL);
				return;
			}
			goto ill_source;

		case XH:
		case XL:
			// ld xh,r		a b c d e xh xl N
			// ld xl,r		a b c d e xh xl N
			r += RH - XH;
			if (r2 <= RE || r2 == RA || r2 == NN)
			{
				store(PFX_IX);
				goto ld_r;
			}
			if (r2 == XH || r2 == XL)
			{
				r2 += RH - XH;
				store(PFX_IX);
				goto ld_r;
			}
			goto ill_source;

		case YH:
		case YL:
			// ld yh,r		a b c d e yh yl N
			// ld yl,r		a b c d e yh yl N
			r += RH - YH;
			if (r2 <= RE || r2 == RA || r2 == NN)
			{
				store(PFX_IY);
				goto ld_r;
			}
			if (r2 == YH || r2 == YL)
			{
				r2 += RH - YH;
				store(PFX_IY);
				goto ld_r;
			}
			goto ill_source;

		case RA:
			// ld a,i
			// ld i,a
			// ld a,(rr)	bc de
			// ld a,(NN)
			if (r2 == XBC)
			{
				store(LD_A_xBC);
				return;
			}
			if (r2 == XDE)
			{
				store(LD_A_xDE);
				return;
			}
			if (r2 == XNN)
			{
				store(LD_A_xNN);
				storeWord(n2);
				return;
			}
			if (r2 == RI)
			{
				storeEDopcode(LD_A_I);
				return;
			}
			if (r2 == RR)
			{
				storeEDopcode(LD_A_R);
				return;
			}
			if (r2 == XBCPP)
			{
				store(LD_A_xBC, INC_BC);
				return;
			}
			if (r2 == XDEPP)
			{
				store(LD_A_xDE, INC_DE);
				return;
			}
			if (r2 == XMMBC)
			{
				store(DEC_BC, LD_A_xBC);
				return;
			}
			if (r2 == XMMDE)
			{
				store(DEC_DE, LD_A_xDE);
				return;
			}
			goto ld_r;

		case RH:
		case RL:
			if (r2 >= XH && r2 <= YL) goto ill_source;
			goto ld_r;

		case RB:
		case RC:
		case RD:
		case RE:
			// ld r,r		a b c d e h l (hl)
			// ld r,(ix+d)
			// ld r,N
			// ld r,xh		a b c d e xh xl
			// ld r,yh		a b c d e yh yl
		ld_r:
			assert(r <= RA && r != XHL);
			if (r2 <= RA)
			{
				store(LD_B_B + (r - RB) * 8 + (r2 - RB));
				return;
			}
			if (r2 == NN)
			{
				store(LD_B_N + (r - RB) * 8);
				storeByte(n2);
				return;
			}
			if (r2 == XIX)
			{
				store(PFX_IX, LD_B_xHL + (r - RB) * 8, n2.value);
				return;
			}
			if (r2 == XIY)
			{
				store(PFX_IY, LD_B_xHL + (r - RB) * 8, n2.value);
				return;
			}
			if (r2 == XH || r2 == XL)
			{
				store(PFX_IX, LD_B_H + (r2 - XH) + (r - RB) * 8);
				return;
			}
			if (r2 == YH || r2 == YL)
			{
				store(PFX_IY, LD_B_H + (r2 - YH) + (r - RB) * 8);
				return;
			}
			if (r2 == XHLPP)
			{
				store(LD_B_xHL + (r - RB) * 8, INC_HL);
				return;
			}
			if (r2 == XMMHL)
			{
				store(DEC_HL, LD_B_xHL + (r - RB) * 8);
				return;
			}
			goto ill_source;

		case NN: goto ill_dest;

		default:
			if (r >= 256) // goodie:  ld rrrr,NNNN  or  ld rrrr,(NN)
			{
				if (r2 == XNN)
				{
					do {
						// loop 1: load lo word
						// loop 2: load hi word
						if (int8(r) == HL) { store(LD_HL_xNN); }
						else if (int8(r) == BC) { storeEDopcode(LD_BC_xNN); }
						else if (int8(r) == DE) { storeEDopcode(LD_DE_xNN); }
						else if (int8(r) == IX) { storeIXopcode(LD_HL_xNN); }
						else if (int8(r) == IY) { storeIYopcode(LD_HL_xNN); }
						else if (int8(r) == SP) { storeEDopcode(LD_SP_xNN); }
						else
							goto ill_dest;
						storeWord(n2); // store address
						n2.value += 2; // incr address for high registers
						r = r >> 8;	   // move spec for high registers into low byte
					}
					while (r != 0);
					return;
				}
				if (r2 == NN)
				{
					do {
						// loop 1: load lo word
						// loop 2: load hi word
						if (int8(r) == HL) { store(LD_HL_NN); }
						else if (int8(r) == BC) { store(LD_BC_NN); }
						else if (int8(r) == DE) { store(LD_DE_NN); }
						else if (int8(r) == IX) { storeIXopcode(LD_HL_NN); }
						else if (int8(r) == IY) { storeIYopcode(LD_HL_NN); }
						else if (int8(r) == SP) { store(LD_SP_NN); }
						else
							goto ill_dest;
						storeWord(n2 & 0xffff); // store value
						n2 = n2 >> 16;			// move high part of value into low word
						r  = r >> 8;			// move spec for high registers into low byte
					}
					while (r != 0);
					return;
				}
			}
			goto ill_dest;
		}

		// ---- 0xED opcodes ----

	case ' neg': return storeEDopcode(NEG);
	case ' rrd': return storeEDopcode(RRD);
	case ' rld': return storeEDopcode(RLD);
	case ' ldi': return storeEDopcode(LDI);
	case ' cpi': return storeEDopcode(CPI);
	case ' ini': return storeEDopcode(INI);
	case ' ldd': return storeEDopcode(LDD);
	case ' cpd': return storeEDopcode(CPD);
	case ' ind': return storeEDopcode(IND);
	case 'outi': return storeEDopcode(OUTI);
	case 'outd': return storeEDopcode(OUTD);
	case 'ldir': return storeEDopcode(LDIR);
	case 'cpir': return storeEDopcode(CPIR);
	case 'inir': return storeEDopcode(INIR);
	case 'otir': return storeEDopcode(OTIR);
	case 'lddr': return storeEDopcode(LDDR);
	case 'cpdr': return storeEDopcode(CPDR);
	case 'indr': return storeEDopcode(INDR);
	case 'otdr': return storeEDopcode(OTDR);
	case 'reti': return storeEDopcode(RETI);
	case 'retn': return storeEDopcode(RETN);

	case '  im':
		// im n		0 1 2
		r = getRegister(q, n);
		if (r == NN && uint(n) <= 2) return storeEDopcode(n.value == 0 ? IM_0 : n.value == 1 ? IM_1 : IM_2);
		throw SyntaxError("illegal interrupt mode");

	case '  in':
		// in a,(N)
		// in a,N		(seen in sources)
		// in r,(c)		a f b c d e h l
		// in r,(bc)	a f b c d e h l
		// in (c)		same as "in f,(c)"

		if (q.testWord("f"))
			r = XHL;
		else
		{
			r = getRegister(q, n);
			if (r == XHL) goto ill_dest;
		}
		depp = q.p;

		if ((r == XC || r == XBC) && q.peekChar() != ',') return storeEDopcode(IN_F_xC);

		q.expectComma();
		r2 = getRegister(q, n2);

		if (r2 == XC || r2 == XBC)
		{
			if (r <= RA) return storeEDopcode(IN_B_xC + (r - RB) * 8);
			goto ill_dest;
		}
		if (r2 == XNN || r2 == NN)
		{
			if (r == RA)
			{
				store(INA);
				storeByte(n2);
				return;
			}
			goto ill_dest;
		}
		goto ill_source;

	case ' out':
		// out (c),r	a b c d e h l
		// out (c),0	NMOS
		// out (c),255	CMOS
		// out (bc),r	--> out (c),r
		// out (bc),0	--> out (c),0
		// out (bc),255	--> out (c),255
		// out (n),a	--> outa n
		// out n,a      --> outa n		(seen in sources)

		r	 = getRegister(q, n);
		depp = q.p;
		q.expectComma();
		r2 = getRegister(q, n2);

		if (r == XC || r == XBC)
		{
			if (r2 <= RA && r2 != XHL) return storeEDopcode(OUT_xC_B + (r2 - RB) * 8);
			if (r2 == NN && (n2.value == 0 || n2.value == 255 || n2.is_invalid())) return storeEDopcode(OUT_xC_0);
			goto ill_source;
		}
		if (r == XNN || r == NN)
		{
			if (r2 != RA) goto ill_source;
			if ((n.value < -128 || n.value > 255) && n.is_valid()) q.p = depp; // storeByte() will throw
			store(OUTA);
			storeByte(n);
			return;
		}
		goto ill_dest;

		// ---- 0xCB opcodes ----

	case ' res': instr = RES0_B; goto bit;
	case ' set': instr = SET0_B; goto bit; // note: M80 pseudo instruction SET is handled by asmLabel()
	case ' bit':
		instr = BIT0_B;
		goto bit;

	bit:
		n = value(q);
		if (uint(n) > 7) throw SyntaxError("illegal bit number");
		instr += 8 * n.value;
		q.expectComma();
		goto rr;

	case ' rlc': instr = RLC_B; goto rr;
	case ' rrc': instr = RRC_B; goto rr;
	case ' sla': instr = SLA_B; goto rr;
	case ' sra': instr = SRA_B; goto rr;
	case ' sll':
		if (target_z180) { goto ill_opcode; }
		instr = SLL_B;
		goto rr;
	case ' srl': instr = SRL_B; goto rr;
	case '  rl': instr = RL_B; goto rr;
	case '  rr':
		instr = RR_B;
		goto rr;

		// bit n,r			0..7  a b c d e h l (hl)
		// bit n,(ix+d)
		// bit n,xh			ILLEGAL ***NOT ALL Z80 CPUs!***
		// bit n,(ix+d),r	ILLEGAL ***NOT ALL Z80 CPUs!***

		// common handler for:
		// bit, set, res

		// rr r			a b c d e h l (hl)
		// rr xh		xh xl yh yl		// ILLEGAL: ***NOT ALL Z80 CPUs!***
		// rr (ix+n)	ix iy
		// rr (ix+n),r	a b c d e h l	// ILLEGAL: ***NOT ALL Z80 CPUs!***

		// common handler for:
		// rr rrc rl rlc sla sra sll srl

	rr:
		if (target_8080) goto ill_8080;
		r2 = getRegister(q, n2);

		if (r2 <= RA) return store(PFX_CB, instr + r2 - RB);

		if (r2 <= YL)
		{
			if (!ixcbxh_enabled) throw SyntaxError("illegal instruction (use --ixcbxh)");
			if (r2 >= YH)
				return store(PFX_IY, PFX_CB, 0, instr + r2 + RH - YH - RB);
			else
				return store(PFX_IX, PFX_CB, 0, instr + r2 + RH - XH - RB);
		}

		if (r2 <= HL && r2 >= BC) // goodie: sla, sll, rl, sra, srl, rr with bc, de, hl
		{
			if (instr == SLA_B || instr == SLL_B || instr == RL_B)
			{
				r2 = (r2 - BC) * 2;
				store(PFX_CB, instr + r2 + 1);
				store(PFX_CB, RL_B + r2 + 0);
				return;
			}
			if (instr == SRA_B || instr == SRL_B || instr == RR_B)
			{
				r2 = (r2 - BC) * 2;
				store(PFX_CB, instr + r2 + 0);
				store(PFX_CB, RR_B + r2 + 1);
				return;
			}
		}

		if (r2 == XIX || r2 == XIY)
		{
			r = XHL;
			if (q.testComma())
			{
				if (!ixcbr2_enabled) throw SyntaxError("illegal instruction (use --ixcbr2)");
				r = getRegister(q, n);
				if (r > RA || r == XHL) throw SyntaxError("illegal secondary destination");
			}
			return store(r2 == XIX ? PFX_IX : PFX_IY, PFX_CB, n2.value, instr + r - RB);
		}

		if (r2 == XHLPP) return store(PFX_CB, instr + XHL - RB, INC_HL);
		if (r2 == XMMHL) return store(DEC_HL, PFX_CB, instr + XHL - RB);

		if ((instr & 0xc0) == BIT0_B)
			goto ill_source;
		else
			goto ill_target;

		// ---- Z180 opcodes: ----

	case ' slp':
		if (target_z180) return store(PFX_ED, 0x76);
		goto ill_z180;
	case 'otim':
		if (target_z180) return store(PFX_ED, 0x83);
		goto ill_z180;
	case 'otdm':
		if (target_z180) return store(PFX_ED, 0x8b);
		goto ill_z180;

	case ' in0':
		// in0 r,(n)		a b c d e h l f
		if (!target_z180) goto ill_z180;
		if (q.testWord("f"))
			r = XHL;
		else
		{
			r = getRegister(q, n);
			if (r > RA || r == XHL) goto ill_dest;
		}
		q.expectComma();
		r2 = getRegister(q, n2);
		if (r2 == XNN)
		{
			storeEDopcode(0x00 + 8 * (r - RB));
			storeByte(n2);
			return;
		}
		goto ill_source;

	case ' tst':
		// tst r		b c d e h l (hl) a
		// tst n
		if (!target_z180) goto ill_z180;
		r = getRegister(q, n);
		if (r == NN)
		{
			storeEDopcode(0x64);
			storeByte(n);
			return;
		}
		if (r <= RA)
		{
			storeEDopcode(0x04 + 8 * (r - RB));
			return;
		}
		goto ill_source;

	case 'mult': // <-- TODO: remove?
	case ' mlt': // Zilog manual: operation name = MULT, mnemonic = MLT
		// mlt rr		bc de hl sp
		if (!target_z180) goto ill_z180;
		r = getRegister(q, n);
		if (r >= BC && r <= SP) return store(PFX_ED, 0x4c + 16 * (r - BC));
		goto ill_source;

	case 'out0':
		// out0 (n),r		b c d e h l a
		if (!target_z180) goto ill_z180;
		r = getRegister(q, n);
		if (r != XNN) goto ill_dest;
		depp = q.p;
		q.expectComma();
		r2 = getRegister(q, n2);
		if (r2 <= RA && r2 != XHL)
		{
			if ((n.value < -128 || n.value > 255) && n.is_valid()) q.p = depp; // storeByte() will throw
			store(PFX_ED, 0x01 + 8 * (r2 - RB));
			storeByte(n);
			return;
		}
		goto ill_source;

	default: goto misc;
	}

wlen5:
	if ((*w | 0x20) == 'o')
	{
		if (lceq(w, "otimr"))
		{
			if (target_z180) return store(PFX_ED, 0x93);
			goto ill_z180;
		}
		if (lceq(w, "otdmr"))
		{
			if (target_z180) return store(PFX_ED, 0x9b);
			goto ill_z180;
		}
		// try macro and pseudo instructions
		goto misc;
	}
	else if ((*w | 0x20) == 't' && lceq(w, "tstio"))
	{
		// tstio n
		if (!target_z180) goto ill_z180;
		r = getRegister(q, n);
		if (r == NN)
		{
			store(PFX_ED, 0x74);
			storeByte(n);
			return;
		}
		goto ill_source;
	}
	else
	{
		// try macro and pseudo instructions
		goto misc;
	}

// generate error
ill_target:
	if (depp) q.p = depp;
	throw SyntaxError("illegal target"); // 1st arg
ill_source:
	throw SyntaxError("illegal source"); // 2nd arg
ill_dest:
	if (depp) q.p = depp;
	throw SyntaxError("illegal destination"); // jp etc., ld, in, out: destination
ill_z180:
	throw SyntaxError("z180 opcode (use option --z180)");
ill_8080:
	throw SyntaxError("no 8080 opcode (option --8080)");
ill_opcode:
	throw SyntaxError("illegal opcode (option --z180)");

// try macro and pseudo instructions
misc:
	asmPseudoInstr(q, w);
}

repository: Megatokio/zasm

repo_name: Megatokio/zasm

gha_language: Assembly


text:
package encoding

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand-sdk/encoding/msgpack"
	sdk_types "github.com/algorand/go-algorand-sdk/types"

	"github.com/algorand/indexer/types"
)

func TestEncodeSignedTxnWithAD(t *testing.T) {
	type txnMsgpackJSON struct {
		msgpack []byte
		json    string
	}

	var testTxns = []txnMsgpackJSON{
		{
			[]uint8{0x83, 0xa2, 0x64, 0x74, 0x81, 0xa2, 0x67, 0x64, 0x81, 0xa9, 0xfe, 0xfe, 0xff, 0xef, 0x0, 0x0, 0x11, 0x22, 0x33, 0x82, 0xa2, 0x61, 0x74, 0x1, 0xa2, 0x62, 0x73, 0xc4, 0x3, 0x78, 0x78, 0x78, 0xa3, 0x73, 0x69, 0x67, 0xc4, 0x40, 0x51, 0xca, 0x9f, 0x32, 0xca, 0x9d, 0x66, 0x4b, 0xde, 0xa0, 0x98, 0xd9, 0x1b, 0xd, 0xe, 0x4d, 0x39, 0xca, 0x2, 0x4c, 0x4e, 0xc4, 0xba, 0x88, 0x1a, 0xb6, 0xa, 0x63, 0xff, 0xb0, 0x95, 0xc6, 0xb6, 0x7d, 0x0, 0xb4, 0xdc, 0xef, 0x41, 0xe6, 0x3b, 0xc3, 0x43, 0x3e, 0xb5, 0xa2, 0xa0, 0x27, 0xad, 0x9c, 0xc0, 0x57, 0x93, 0x5c, 0x4e, 0xcd, 0x18, 0xea, 0xb0, 0x6b, 0xe3, 0x97, 0x17, 0x3, 0xa3, 0x74, 0x78, 0x6e, 0x8b, 0xa4, 0x61, 0x70, 0x61, 0x61, 0x91, 0xc4, 0x3, 0x78, 0x78, 0x78, 0xa4, 0x61, 0x70, 0x61, 0x70, 0xc4, 0x17, 0x2, 0x20, 0x1, 0x1, 0x26, 0x1, 0x9, 0xfe, 0xfe, 0xff, 0xef, 0x0, 0x0, 0x11, 0x22, 0x33, 0x28, 0x36, 0x1a, 0x0, 0x67, 0x22, 0x43, 0xa4, 0x61, 0x70, 0x67, 0x73, 0x81, 0xa3, 0x6e, 0x62, 0x73, 0x1, 0xa4, 0x61, 0x70, 0x73, 0x75, 0xc4, 0x5, 0x2, 0x20, 0x1, 0x1, 0x22, 0xa3, 0x66, 0x65, 0x65, 0xcd, 0x3, 0xe8, 0xa2, 0x66, 0x76, 0x4, 0xa2, 0x67, 0x68, 0xc4, 0x20, 0x8a, 0xae, 0xf2, 0xee, 0x8f, 0x3, 0x93, 0xb9, 0xa5, 0x47, 0x41, 0x35, 0x3b, 0x97, 0x96, 0xf3, 0xd, 0xcc, 0x52, 0x10, 0x9d, 0x21, 0x15, 0x9a, 0x64, 0xe8, 0x47, 0x52, 0xb2, 0xcc, 0x90, 0x6a, 0xa2, 0x6c, 0x76, 0xcd, 0x3, 0xec, 0xa4, 0x6e, 0x6f, 0x74, 0x65, 0xc4, 0x8, 0x13, 0xfa, 0x3c, 0x55, 0xe8, 0x7b, 0x23, 0xea, 0xa3, 0x73, 0x6e, 0x64, 0xc4, 0x20, 0x4a, 0x82, 0x63, 0xeb, 0xc0, 0xd2, 0xee, 0xed, 0xac, 0x73, 0xdb, 0xb9, 0xd0, 0x27, 0xa1, 0xb2, 0x32, 0x99, 0x7a, 0xed, 0xc5, 0xde, 0xa2, 0x25, 0x7f, 0x7f, 0x2c, 0x8b, 0xcd, 0x42, 0x5f, 0x1a, 0xa4, 0x74, 0x79, 0x70, 0x65, 0xa4, 0x61, 0x70, 0x70, 0x6c},
			"{\"dt\":{\"gd\":{\"/v7/7wAAESIz\":{\"at\":1,\"bs\":\"eHh4\"}}},\"sig\":\"UcqfMsqdZkveoJjZGw0OTTnKAkxOxLqIGrYKY/+wlca2fQC03O9B5jvDQz61oqAnrZzAV5NcTs0Y6rBr45cXAw==\",\"txn\":{\"apaa\":[\"eHh4\"],\"apap\":\"AiABASYBCf7+/+8AABEiMyg2GgBnIkM=\",\"apgs\":{\"nbs\":1},\"apsu\":\"AiABASI=\",\"fee\":1000,\"fv\":4,\"gh\":\"iq7y7o8Dk7mlR0E1O5eW8w3MUhCdIRWaZOhHUrLMkGo=\",\"lv\":1004,\"note\":\"E/o8Veh7I+o=\",\"snd\":\"SoJj68DS7u2sc9u50CehsjKZeu3F3qIlf38si81CXxo=\",\"type\":\"appl\"}}",
		},
		{
			[]byte{0x83, 0xa2, 0x64, 0x74, 0x82, 0xa2, 0x67, 0x64, 0x82, 0xa3, 0x67, 0x6b, 0x62, 0x82, 0xa2, 0x61, 0x74, 0x1, 0xa2, 0x62, 0x73, 0xc4, 0x4, 0x74, 0x65, 0x73, 0x74, 0xa3, 0x67, 0x6b, 0x69, 0x82, 0xa2, 0x61, 0x74, 0x2, 0xa2, 0x75, 0x69, 0x64, 0xa2, 0x6c, 0x64, 0x81, 0x0, 0x82, 0xa3, 0x6c, 0x6b, 0x62, 0x82, 0xa2, 0x61, 0x74, 0x1, 0xa2, 0x62, 0x73, 0xc4, 0xb, 0x61, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x74, 0x65, 0x73, 0x74, 0xa3, 0x6c, 0x6b, 0x69, 0x82, 0xa2, 0x61, 0x74, 0x2, 0xa2, 0x75, 0x69, 0xcc, 0xc8, 0xa3, 0x73, 0x69, 0x67, 0xc4, 0x40, 0xc9, 0x25, 0xb2, 0xa, 0x42, 0xda, 0x15, 0xbe, 0x74, 0x16, 0x1d, 0x45, 0xc9, 0x3b, 0xf, 0xa4, 0xcc, 0xdd, 0x86, 0xbd, 0xa, 0x53, 0x1e, 0x43, 0xb3, 0x7e, 0xf9, 0xcc, 0xaf, 0x44, 0x38, 0xce, 0x35, 0xa5, 0xaa, 0xb, 0x96, 0x28, 0x79, 0x6, 0xf8, 0xe1, 0xfb, 0x96, 0xe3, 0x79, 0x9b, 0x27, 0xfa, 0xa4, 0x51, 0x10, 0xc7, 0xb1, 0x84, 0x79, 0x46, 0xf8, 0xd8, 0x6a, 0x6c, 0x96, 0x93, 0x6, 0xa3, 0x74, 0x78, 0x6e, 0x8a, 0xa4, 0x61, 0x70, 0x61, 0x61, 0x91, 0xc4, 0x5, 0x66, 0x69, 0x72, 0x73, 0x74, 0xa4, 0x61, 0x70, 0x61, 0x6e, 0x1, 0xa4, 0x61, 0x70, 0x69, 0x64, 0x23, 0xa3, 0x66, 0x65, 0x65, 0xcd, 0x3, 0xe8, 0xa2, 0x66, 0x76, 0x7, 0xa2, 0x67, 0x68, 0xc4, 0x20, 0x8a, 0xae, 0xf2, 0xee, 0x8f, 0x3, 0x93, 0xb9, 0xa5, 0x47, 0x41, 0x35, 0x3b, 0x97, 0x96, 0xf3, 0xd, 0xcc, 0x52, 0x10, 0x9d, 0x21, 0x15, 0x9a, 0x64, 0xe8, 0x47, 0x52, 0xb2, 0xcc, 0x90, 0x6a, 0xa2, 0x6c, 0x76, 0xcd, 0x3, 0xef, 0xa4, 0x6e, 0x6f, 0x74, 0x65, 0xc4, 0x8, 0xc9, 0x83, 0x5, 0x5f, 0x20, 0x45, 0x8f, 0x98, 0xa3, 0x73, 0x6e, 0x64, 0xc4, 0x20, 0x32, 0xf8, 0xa1, 0x14, 0x66, 0x60, 0x7, 0xb7, 0xfe, 0x8, 0xd2, 0x48, 0x83, 0xdf, 0x28, 0x86, 0x16, 0x74, 0xa3, 0xb2, 0x5, 0x48, 0x1d, 0x4a, 0x45, 0x8e, 0x50, 0xb4, 0xba, 0x2f, 0x34, 0xde, 0xa4, 0x74, 0x79, 0x70, 0x65, 0xa4, 0x61, 0x70, 0x70, 0x6c},
			"{\"dt\":{\"gd\":{\"/v7/7wAAESIz\":{\"at\":1,\"bs\":\"eHh4\"},\"Z2ti\":{\"at\":1,\"bs\":\"dGVzdA==\"},\"Z2tp\":{\"at\":2,\"ui\":100}},\"ld\":{\"0\":{\"bGti\":{\"at\":1,\"bs\":\"YW5vdGhlcnRlc3Q=\"},\"bGtp\":{\"at\":2,\"ui\":200}}}},\"sig\":\"ySWyCkLaFb50Fh1FyTsPpMzdhr0KUx5Ds375zK9EOM41paoLlih5Bvjh+5bjeZsn+qRREMexhHlG+NhqbJaTBg==\",\"txn\":{\"apaa\":[\"Zmlyc3Q=\"],\"apan\":1,\"apap\":\"AiABASYBCf7+/+8AABEiMyg2GgBnIkM=\",\"apgs\":{\"nbs\":1},\"apid\":35,\"apsu\":\"AiABASI=\",\"fee\":1000,\"fv\":7,\"gh\":\"iq7y7o8Dk7mlR0E1O5eW8w3MUhCdIRWaZOhHUrLMkGo=\",\"lv\":1007,\"note\":\"yYMFXyBFj5g=\",\"snd\":\"MvihFGZgB7f+CNJIg98ohhZ0o7IFSB1KRY5QtLovNN4=\",\"type\":\"appl\"}}",
		},
	}

	var stxn types.SignedTxnWithAD
	for i, mt := range testTxns {
		t.Run(fmt.Sprintf("i=%d", i), func(t *testing.T) {
			msgpack.Decode(mt.msgpack, &stxn)
			js := EncodeSignedTxnWithAD(stxn)
			require.Equal(t, mt.json, string(js))
		})
	}
}

func TestEncodeSignedTxnWithADSynthetic(t *testing.T) {
	nonutf8b := []byte{254, 254, 255, 239, 0, 0, 17, 34, 51}
	nonutf8 := string(nonutf8b)
	var stxn types.SignedTxnWithAD
	stxn.EvalDelta.GlobalDelta = make(map[string]types.ValueDelta)
	stxn.EvalDelta.GlobalDelta[nonutf8] = types.ValueDelta{
		Action: types.SetBytesAction,
		Bytes:  nonutf8b,
	}
	stxn.EvalDelta.LocalDeltas = make(map[uint64]types.StateDelta, 1)
	ld := make(map[string]types.ValueDelta)
	ld[nonutf8] = types.ValueDelta{
		Action: types.SetBytesAction,
		Bytes:  nonutf8b,
	}
	stxn.EvalDelta.LocalDeltas[1] = ld
	js := EncodeSignedTxnWithAD(stxn)
	require.Equal(t, "{\"dt\":{\"gd\":{\"/v7/7wAAESIz\":{\"at\":1,\"bs\":\"/v7/7wAAESIz\"}},\"ld\":{\"1\":{\"/v7/7wAAESIz\":{\"at\":1,\"bs\":\"/v7/7wAAESIz\"}}}}}", string(js))
}

// Test that encoding to JSON and decoding results in the same object.
func TestJSONEncoding(t *testing.T) {
	type Y struct {
		Num int
	}
	type T struct {
		Num    uint64
		Str    string
		Bytes  []byte
		Object Y
	}

	x := T{
		Num:    1,
		Str:    "abc",
		Bytes:  []byte{4, 5, 6},
		Object: Y{Num: 7},
	}
	buf := EncodeJSON(x)

	var xx T
	err := DecodeJSON(buf, &xx)
	require.NoError(t, err)

	assert.Equal(t, x, xx)
}

// Test that encoding of Transaction is as expected and that decoding results in the same object.
func TestTransactionEncoding(t *testing.T) {
	i := byte(0)
	newaddr := func() types.Address {
		i++
		var address types.Address
		address[0] = i
		return address
	}

	tests := []struct {
		name     string
		params   types.SignedTxnWithAD
		expected string
	}{
		{
			name: "simple",
			params: types.SignedTxnWithAD{
				SignedTxn: sdk_types.SignedTxn{
					Txn: types.Transaction{
						AssetConfigTxnFields: sdk_types.AssetConfigTxnFields{
							AssetParams: sdk_types.AssetParams{
								Total:     99999,
								AssetName: "\r",
								UnitName:  "💰",
								URL:       "https://my.\000asset",
								Manager:   newaddr(),
								Reserve:   newaddr(),
								Freeze:    newaddr(),
								Clawback:  newaddr(),
							},
						},
					},
				},
			},
			expected: `{"txn":{"apar":{"an64":"DQ==","au64":"aHR0cHM6Ly9teS4AYXNzZXQ=","c":"BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","f":"AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","m":"AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","r":"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","t":99999,"un":"💰"}}}`,
		},
	}

	for _, testcase := range tests {
		testcase := testcase
		t.Run(testcase.name, func(t *testing.T) {
			t.Parallel()
			buf := EncodeSignedTxnWithAD(testcase.params)
			assert.Equal(t, testcase.expected, string(buf))

			paramsNew, err := DecodeSignedTxnWithAD(buf)
			require.NoError(t, err)
			assert.Equal(t, testcase.params, paramsNew)
		})
	}
}

// Test that encoding of AssetParams is as expected and that decoding results in the
// same object.
func TestAssetParamsEncoding(t *testing.T) {
	i := byte(0)
	newaddr := func() types.Address {
		i++
		var address types.Address
		address[0] = i
		return address
	}

	tests := []struct {
		name     string
		params   sdk_types.AssetParams
		expected string
	}{
		{
			name: "simple",
			params: sdk_types.AssetParams{
				Total:    99999,
				URL:      "https://my.asset",
				Manager:  newaddr(),
				Reserve:  newaddr(),
				Freeze:   newaddr(),
				Clawback: newaddr(),
			},
			expected: `{"au":"https://my.asset","c":"BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","f":"AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","m":"AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","r":"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","t":99999}`,
		},
		{
			name: "embedded null / non-printable / emoji char",
			params: sdk_types.AssetParams{
				Total:     99999,
				AssetName: "\r",
				UnitName:  "💰",
				URL:       "https://my.\000asset",
				Manager:   newaddr(),
				Reserve:   newaddr(),
				Freeze:    newaddr(),
				Clawback:  newaddr(),
			},
			expected: `{"an64":"DQ==","au64":"aHR0cHM6Ly9teS4AYXNzZXQ=","c":"CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","f":"BwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","m":"BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","r":"BgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","t":99999,"un":"💰"}`,
		},
	}

	for _, testcase := range tests {
		testcase := testcase
		t.Run(testcase.name, func(t *testing.T) {
			t.Parallel()
			buf := EncodeAssetParams(testcase.params)
			assert.Equal(t, testcase.expected, string(buf))

			paramsNew, err := DecodeAssetParams(buf)
			require.NoError(t, err)
			assert.Equal(t, testcase.params, paramsNew)
		})
	}
}

repository: spintrade/indexer

repo_name: spintrade/indexer

branch_name: refs/heads/develop

gha_license_id: MIT

extension: go


text:
package service

import (
	"encoding/base64"
	"github.com/labstack/gommon/log"
	"io/ioutil"
	"os"
)

func ReadFile (f *string, data chan string, base64Enc bool) {
	raw,err:= ioutil.ReadFile(*f)
	if err!=nil {
		log.Error("读取文件失败, 文件->", *f)
	}
	var str string
	if base64Enc {
		str = base64.StdEncoding.EncodeToString(raw)
	} else {
		str= string(raw[:])
	}
	data <- str
}

func WriteFile (f *string, content string ,data chan string, base64Enc bool) {
	if base64Enc {
		content = base64.StdEncoding.EncodeToString([]byte(content))
	}
	ioutil.WriteFile(*f, []byte(content), os.ModeDevice)
	data <- ""
}

repository: KierenEinar/live

repo_name: KierenEinar/live


text:
package ts

import (
	"fmt"
	"log"

	"github.com/jackc/pgx"
	"github.com/timescale/outflux/internal/connections"
	"github.com/timescale/outflux/internal/idrf"
	"github.com/timescale/outflux/internal/ingestion/config"
	"github.com/timescale/outflux/internal/utils"
)

type ingestDataArgs struct {
	// id of the ingestor used to subscribe and unsubscribe to errors from other goroutines
	ingestorID string
	// channel delivering errors that happened in other routines
	errChan chan error
	// the channel notified when the ingestor has completed
	ackChannel chan bool
	// the input channel that delivers the data to be inserted
	dataChannel chan idrf.Row
	// on each ${batchSize} rows inserted the ingestor checks if there is an error in some of the other goroutines
	batchSize uint16
	// if an error occurred in another goroutine should a rollback be done
	rollbackOnExternalError bool
	// the database connection
	dbConn connections.PgxWrap
	// column names
	colNames []string
	// name of table where inserts happen
	tableName string
	// name of schema where the table is
	schemaName string
	// commit strategy
	commitStrategy config.CommitStrategy
}

// Routine defines an interface that consumes a channel of idrf.Rows and
// and writes them to a TimescaleDB
type Routine interface {
	ingest(args *ingestDataArgs) error
}

// NewRoutine creates a new
func NewRoutine() Routine {
	return &defaultRoutine{}
}

type defaultRoutine struct{}

func (routine *defaultRoutine) ingest(args *ingestDataArgs) error {
	log.Printf("Starting data ingestor '%s'", args.ingestorID)

	err := utils.CheckError(args.errChan)
	if err != nil {
		log.Printf("%s: received external error before starting data insertion. Quitting\n", args.ingestorID)
		return nil
	}

	tx, err := openTx(args)
	if err != nil {
		return err
	}

	numInserts := uint(0)
	batchInserts := uint16(0)
	log.Printf("Will batch insert %d rows at once. With commit strategy: %v", args.batchSize, args.commitStrategy)
	batch := make([][]interface{}, args.batchSize)
	var tableIdentifier *pgx.Identifier
	if args.schemaName != "" {
		tableIdentifier = &pgx.Identifier{args.schemaName, args.tableName}
	} else {
		tableIdentifier = &pgx.Identifier{args.tableName}
	}

	for row := range args.dataChannel {
		batch[batchInserts] = row
		batchInserts++
		if batchInserts < args.batchSize {
			continue
		}

		if args.rollbackOnExternalError && utils.CheckError(args.errChan) != nil {
			log.Printf("%s: Error received from outside of ingestor. Rolling back\n", args.ingestorID)
			_ = tx.Rollback()
			return nil
		}

		numInserts += uint(batchInserts)
		batchInserts = 0
		if err = copyToDb(args, tableIdentifier, tx, batch); err != nil {
			return err
		}
		if args.commitStrategy != config.CommitOnEachBatch {
			continue
		}
		if err = commitTx(args, tx); err != nil {
			return err
		}
		if tx, err = openTx(args); err != nil {
			return err
		}
	}

	if batchInserts > 0 {
		batch = batch[:batchInserts]
		if err = copyToDb(args, tableIdentifier, tx, batch); err != nil {
			return err
		}
		numInserts += uint(batchInserts)
	}

	if err = commitTx(args, tx); err != nil {
		return err
	}

	log.Printf("%s: Complete. Inserted %d rows.\n", args.ingestorID, numInserts)
	return nil
}

func commitTx(args *ingestDataArgs, tx *pgx.Tx) error {
	err := tx.Commit()
	if err != nil {
		log.Printf("%s could not commit transaction in output db\n%v", args.ingestorID, err)
	}

	return err
}

func copyToDb(args *ingestDataArgs, identifier *pgx.Identifier, tx *pgx.Tx, batch [][]interface{}) error {
	source := pgx.CopyFromRows(batch)
	_, err := args.dbConn.CopyFrom(*identifier, args.colNames, source)
	if err != nil {
		log.Printf("%s could not insert batch of rows in output db\n%v", args.ingestorID, err)
		_ = tx.Rollback()
	}

	return err
}

func openTx(args *ingestDataArgs) (*pgx.Tx, error) {
	tx, err := args.dbConn.Begin()
	if err != nil {
		return nil, fmt.Errorf("%s: could not create transaction\n%v", args.ingestorID, err)
	}

	return tx, err
}

repository: timescale/outflux

repo_name: timescale/outflux

gha_language: Go


text:
/*
Copyright 2019 Cisco Systems

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: bgp_updgen_filtergrp_bag.proto

package cisco_ios_xr_ipv4_bgp_oper_bgp_instances_instance_instance_standby_default_vrf_afs_af_update_generation_filter_groups_update_generation_filter_group

import (
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package

type BgpUpdgenFiltergrpBag_KEYS struct {
	InstanceName         string   `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3" json:"instance_name,omitempty"`
	AfName               string   `protobuf:"bytes,2,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
	UpdateGroupIndex     uint32   `protobuf:"varint,3,opt,name=update_group_index,json=updateGroupIndex,proto3" json:"update_group_index,omitempty"`
	SubGroupIndex        uint32   `protobuf:"varint,4,opt,name=sub_group_index,json=subGroupIndex,proto3" json:"sub_group_index,omitempty"`
	SubGroupId           uint32   `protobuf:"varint,5,opt,name=sub_group_id,json=subGroupId,proto3" json:"sub_group_id,omitempty"`
	FilterGroupIndex     uint32   `protobuf:"varint,6,opt,name=filter_group_index,json=filterGroupIndex,proto3" json:"filter_group_index,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *BgpUpdgenFiltergrpBag_KEYS) Reset()         { *m = BgpUpdgenFiltergrpBag_KEYS{} }
func (m *BgpUpdgenFiltergrpBag_KEYS) String() string { return proto.CompactTextString(m) }
func (*BgpUpdgenFiltergrpBag_KEYS) ProtoMessage()    {}
func (*BgpUpdgenFiltergrpBag_KEYS) Descriptor() ([]byte, []int) {
	return fileDescriptor_4fa3c43310a60340, []int{0}
}

func (m *BgpUpdgenFiltergrpBag_KEYS) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS.Unmarshal(m, b)
}
func (m *BgpUpdgenFiltergrpBag_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS.Marshal(b, m, deterministic)
}
func (m *BgpUpdgenFiltergrpBag_KEYS) XXX_Merge(src proto.Message) {
	xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS.Merge(m, src)
}
func (m *BgpUpdgenFiltergrpBag_KEYS) XXX_Size() int {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS.Size(m)
}
func (m *BgpUpdgenFiltergrpBag_KEYS) XXX_DiscardUnknown() {
	xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS.DiscardUnknown(m)
}

var xxx_messageInfo_BgpUpdgenFiltergrpBag_KEYS proto.InternalMessageInfo

func (m *BgpUpdgenFiltergrpBag_KEYS) GetInstanceName() string {
	if m != nil {
		return m.InstanceName
	}
	return ""
}

func (m *BgpUpdgenFiltergrpBag_KEYS) GetAfName() string {
	if m != nil {
		return m.AfName
	}
	return ""
}

func (m *BgpUpdgenFiltergrpBag_KEYS) GetUpdateGroupIndex() uint32 {
	if m != nil {
		return m.UpdateGroupIndex
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag_KEYS) GetSubGroupIndex() uint32 {
	if m != nil {
		return m.SubGroupIndex
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag_KEYS) GetSubGroupId() uint32 {
	if m != nil {
		return m.SubGroupId
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag_KEYS) GetFilterGroupIndex() uint32 {
	if m != nil {
		return m.FilterGroupIndex
	}
	return 0
}

type BgpUpdgenFiltergrpBag struct {
	ProcessId              uint32   `protobuf:"varint,50,opt,name=process_id,json=processId,proto3" json:"process_id,omitempty"`
	UpdateVrfName          string   `protobuf:"bytes,51,opt,name=update_vrf_name,json=updateVrfName,proto3" json:"update_vrf_name,omitempty"`
	UpdateGroupAfName      string   `protobuf:"bytes,52,opt,name=update_group_af_name,json=updateGroupAfName,proto3" json:"update_group_af_name,omitempty"`
	UpdateFilterGroupIndex uint32   `protobuf:"varint,53,opt,name=update_filter_group_index,json=updateFilterGroupIndex,proto3" json:"update_filter_group_index,omitempty"`
	ParentFilterGroupIndex uint32   `protobuf:"varint,54,opt,name=parent_filter_group_index,json=parentFilterGroupIndex,proto3" json:"parent_filter_group_index,omitempty"`
	SubGroupIndexXr        uint32   `protobuf:"varint,55,opt,name=sub_group_index_xr,json=subGroupIndexXr,proto3" json:"sub_group_index_xr,omitempty"`
	SubGroupIdXr           uint32   `protobuf:"varint,56,opt,name=sub_group_id_xr,json=subGroupIdXr,proto3" json:"sub_group_id_xr,omitempty"`
	ParentSubGroupIndex    uint32   `protobuf:"varint,57,opt,name=parent_sub_group_index,json=parentSubGroupIndex,proto3" json:"parent_sub_group_index,omitempty"`
	ParentSubGroupId       uint32   `protobuf:"varint,58,opt,name=parent_sub_group_id,json=parentSubGroupId,proto3" json:"parent_sub_group_id,omitempty"`
	UpdateGroupIndexXr     uint32   `protobuf:"varint,59,opt,name=update_group_index_xr,json=updateGroupIndexXr,proto3" json:"update_group_index_xr,omitempty"`
	NeighborCount          uint32   `protobuf:"varint,60,opt,name=neighbor_count,json=neighborCount,proto3" json:"neighbor_count,omitempty"`
	XXX_NoUnkeyedLiteral   struct{} `json:"-"`
	XXX_unrecognized       []byte   `json:"-"`
	XXX_sizecache          int32    `json:"-"`
}

func (m *BgpUpdgenFiltergrpBag) Reset()         { *m = BgpUpdgenFiltergrpBag{} }
func (m *BgpUpdgenFiltergrpBag) String() string { return proto.CompactTextString(m) }
func (*BgpUpdgenFiltergrpBag) ProtoMessage()    {}
func (*BgpUpdgenFiltergrpBag) Descriptor() ([]byte, []int) {
	return fileDescriptor_4fa3c43310a60340, []int{1}
}

func (m *BgpUpdgenFiltergrpBag) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag.Unmarshal(m, b)
}
func (m *BgpUpdgenFiltergrpBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag.Marshal(b, m, deterministic)
}
func (m *BgpUpdgenFiltergrpBag) XXX_Merge(src proto.Message) {
	xxx_messageInfo_BgpUpdgenFiltergrpBag.Merge(m, src)
}
func (m *BgpUpdgenFiltergrpBag) XXX_Size() int {
	return xxx_messageInfo_BgpUpdgenFiltergrpBag.Size(m)
}
func (m *BgpUpdgenFiltergrpBag) XXX_DiscardUnknown() {
	xxx_messageInfo_BgpUpdgenFiltergrpBag.DiscardUnknown(m)
}

var xxx_messageInfo_BgpUpdgenFiltergrpBag proto.InternalMessageInfo

func (m *BgpUpdgenFiltergrpBag) GetProcessId() uint32 {
	if m != nil {
		return m.ProcessId
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetUpdateVrfName() string {
	if m != nil {
		return m.UpdateVrfName
	}
	return ""
}

func (m *BgpUpdgenFiltergrpBag) GetUpdateGroupAfName() string {
	if m != nil {
		return m.UpdateGroupAfName
	}
	return ""
}

func (m *BgpUpdgenFiltergrpBag) GetUpdateFilterGroupIndex() uint32 {
	if m != nil {
		return m.UpdateFilterGroupIndex
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetParentFilterGroupIndex() uint32 {
	if m != nil {
		return m.ParentFilterGroupIndex
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetSubGroupIndexXr() uint32 {
	if m != nil {
		return m.SubGroupIndexXr
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetSubGroupIdXr() uint32 {
	if m != nil {
		return m.SubGroupIdXr
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetParentSubGroupIndex() uint32 {
	if m != nil {
		return m.ParentSubGroupIndex
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetParentSubGroupId() uint32 {
	if m != nil {
		return m.ParentSubGroupId
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetUpdateGroupIndexXr() uint32 {
	if m != nil {
		return m.UpdateGroupIndexXr
	}
	return 0
}

func (m *BgpUpdgenFiltergrpBag) GetNeighborCount() uint32 {
	if m != nil {
		return m.NeighborCount
	}
	return 0
}

func init() {
	proto.RegisterType((*BgpUpdgenFiltergrpBag_KEYS)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.update_generation_filter_groups.update_generation_filter_group.bgp_updgen_filtergrp_bag_KEYS")
	proto.RegisterType((*BgpUpdgenFiltergrpBag)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.update_generation_filter_groups.update_generation_filter_group.bgp_updgen_filtergrp_bag")
}

func init() { proto.RegisterFile("bgp_updgen_filtergrp_bag.proto", fileDescriptor_4fa3c43310a60340) }

var fileDescriptor_4fa3c43310a60340 = []byte{
	// 464 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x53, 0x4d, 0x6f, 0xd4, 0x30,
	0x10, 0xd5, 0x96, 0xb2, 0xa8, 0xa3, 0x5d, 0x0a, 0x2e, 0x1f, 0xe1, 0x50, 0xb4, 0x2a, 0x02, 0x55,
	0x02, 0x82, 0x60, 0xcb, 0x47, 0x81, 0x0b, 0x42, 0x80, 0x2a, 0x24, 0x0e, 0xad, 0x84, 0xca, 0x69,
	0xe4, 0xc4, 0x4e, 0x88, 0xd4, 0xda, 0xd6, 0xd8, 0x59, 0x2d, 0x67, 0xfe, 0x02, 0x27, 0x7e, 0x2d,
	0xb2, 0x9d, 0x6c, 0x37, 0xd9, 0xae, 0x38, 0xc5, 0x9a, 0xf7, 0x9e, 0x67, 0xe6, 0x3d, 0x07, 0xee,
	0x67, 0xa5, 0xc1, 0xda, 0x88, 0x52, 0x2a, 0x2c, 0xaa, 0x33, 0x27, 0xa9, 0x24, 0x83, 0x19, 0x2f,
	0x53, 0x43, 0xda, 0x69, 0xf6, 0x67, 0x90, 0x57, 0x36, 0xd7, 0x58, 0x69, 0x8b, 0x73, 0xc2, 0xca,
	0xcc, 0x0e, 0xd0, 0x4b, 0xb4, 0x91, 0x94, 0x66, 0xa5, 0x49, 0x2b, 0x65, 0x1d, 0x57, 0xb9, 0xb4,
	0x8b, 0xd3, 0xe2, 0x80, 0xfe, 0x23, 0xb2, 0x5f, 0xa9, 0x90, 0x05, 0xaf, 0xcf, 0x1c, 0xce, 0xa8,
	0x48, 0x79, 0x61, 0x53, 0x5e, 0xa4, 0xb5, 0x11, 0xdc, 0x49, 0x2c, 0xa5, 0x92, 0xc4, 0x5d, 0xa5,
	0xdb, 0xee, 0x58, 0x92, 0xae, 0x8d, 0xfd, 0x0f, 0xbe, 0xf7, 0x7b, 0x03, 0x76, 0xd7, 0x4d, 0x8e,
	0x5f, 0x3f, 0xfd, 0x38, 0x61, 0x0f, 0x60, 0xbc, 0x98, 0x43, 0xf1, 0x73, 0x99, 0x0c, 0x26, 0x83,
	0xfd, 0xad, 0xe3, 0x51, 0x5b, 0xfc, 0xc6, 0xcf, 0x25, 0xbb, 0x0b, 0xd7, 0x78, 0x11, 0xe1, 0x8d,
	0x00, 0x0f, 0x79, 0x11, 0x80, 0x27, 0xc0, 0xda, 0x09, 0x7c, 0x3f, 0xac, 0x94, 0x90, 0xf3, 0xe4,
	0xca, 0x64, 0xb0, 0x3f, 0x3e, 0xbe, 0x11, 0x91, 0x2f, 0x1e, 0x38, 0xf2, 0x75, 0xf6, 0x08, 0xb6,
	0x6d, 0x9d, 0x75, 0xa8, 0x9b, 0x81, 0x3a, 0xb6, 0x75, 0xb6, 0xc4, 0x9b, 0xc0, 0x68, 0x89, 0x27,
	0x92, 0xab, 0x81, 0x04, 0x0b, 0x92, 0xf0, 0x7d, 0x97, 0xf7, 0x6c, 0x2e, 0x1b, 0xc6, 0xbe, 0x11,
	0xb9, 0xb8, 0x6f, 0xef, 0xef, 0x26, 0x24, 0xeb, 0x5c, 0x60, 0xbb, 0x00, 0x86, 0x74, 0x2e, 0xad,
	0xf5, 0xad, 0x5e, 0x84, 0x2b, 0xb6, 0x9a, 0xca, 0x91, 0xf0, 0x33, 0x37, 0x1b, 0xce, 0xa8, 0xb1,
	0x60, 0x1a, 0x2c, 0x18, 0xc7, 0xf2, 0x77, 0x8a, 0x4e, 0x3c, 0x83, 0x5b, 0x1d, 0x27, 0x5a, 0xbf,
	0x0e, 0x02, 0xf9, 0xe6, 0x92, 0x17, 0x1f, 0xa2, 0xe0, 0x10, 0xee, 0x35, 0x82, 0x4b, 0x36, 0x79,
	0x19, 0xc6, 0xb8, 0x13, 0x09, 0x9f, 0x7b, 0xfb, 0x78, 0xa9, 0xe1, 0x24, 0x95, 0xbb, 0x4c, 0xfa,
	0x2a, 0x4a, 0x23, 0x61, 0x45, 0xfa, 0x18, 0x58, 0x2f, 0x02, 0x9c, 0x53, 0xf2, 0x3a, 0x68, 0xb6,
	0x3b, 0x29, 0x9c, 0x12, 0x7b, 0xd8, 0xc9, 0x4b, 0x78, 0xe6, 0x9b, 0xc0, 0x1c, 0x5d, 0x44, 0x71,
	0x4a, 0x6c, 0x0a, 0x4d, 0x37, 0xec, 0xa7, 0x7b, 0x18, 0xd8, 0x3b, 0x11, 0x3d, 0xe9, 0x64, 0xfc,
	0x14, 0x76, 0x56, 0x45, 0x22, 0x79, 0x1b, 0x23, 0xec, 0x29, 0x04, 0x7b, 0x0e, 0xb7, 0x57, 0x1f,
	0x9a, 0x1f, 0xe8, 0x5d, 0x10, 0xb0, 0xfe, 0x5b, 0x0b, 0xd3, 0x5f, 0x57, 0xb2, 0x2a, 0x7f, 0x66,
	0x9a, 0x30, 0xd7, 0xb5, 0x72, 0xc9, 0xfb, 0xf8, 0xd8, 0xda, 0xea, 0x47, 0x5f, 0xcc, 0x86, 0xe1,
	0x07, 0x9e, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0xdd, 0x25, 0xf2, 0xb5, 0xe2, 0x03, 0x00, 0x00,
}

repository: cisco-ie/cisco-proto

repo_name: cisco-ie/cisco-proto


text:
package main

import (
	. "fmt"
	"math/rand"
)

type Fullname struct {
	firstname string
	lastname  string
}

type Person struct {
	fullname Fullname
	age      int8
}

func main() {
	Println("Loops")

	Println("Standard For Loop")
	for i := 0; i <= 10; i++ {
		Printf("Square of %d is %d\n", i, i*i)
	}

	Println("\n\nDefacto While Loop")
	j := 1
	for j <= 100 {
		Printf("Current Value is %d and will be aborted when its greater than '100'\n", j)
		j *= 2
	}

	Println("\n\nIterate over string")
	someString := "some random string"
	for i, v := range someString {
		Printf("Index of string iteration: %d with character: %c\n", i, v)
		j *= 2
	}

	Println("\n\nFunction returns")
	re, im := complexType(2.3, -2.3)
	Printf("Complextype (%.3f, %.3f)\n", re, im)

	Println("\n\nIf Statement with variable assigning")
	if x := getRandomNumber(); x < 100 {
		Printf("Random number is smaller than 100. Random number: %d\n", x)
	} else {
		Printf("Random number is greater than 100. Random number: %d", x)
	}

	Println("\n\nSwitch cases")
	res := getRandomNumber() * getRandomNumber()
	switch {
	case res%2 == 0:
		Printf("Random multiplication is even: %d\n", res)
	case res%3 == 0:
		Printf("Random multiplication is a factor of 3: %d\n", res)
	default:
		Printf("Random multiplication is odd: %d\n", res)
	}

	Println("\n\nGenerate struct Person")
	newPerson := generateNewPerson("Test Name", "Test Lastname", int8(rand.Intn(90)))
	Printf("Firstname '%s', Lastname '%s', Age %d\n", newPerson.fullname.firstname, newPerson.fullname.lastname, newPerson.age)
}

func complexType(input1 float64, input2 float64) (re float64, im float64) {
	re = -1.0 * input1
	im = 2.3 * input2
	return
}

func getRandomNumber() int {
	return rand.Intn(200)
}

func generateNewPerson(firstname string, lastname string, age int8) Person {
	fullname := Fullname{firstname: firstname, lastname: lastname}
	return Person{fullname: fullname, age: age}
}

branch_name: refs/heads/main


text:
#include "OsuDbParser.h"

OsuDbParser::OsuDbParser(string fullPathToOsuDb)
{
	(this)->processData(fullPathToOsuDb);
}

OsuDbParser::~OsuDbParser()
{
}

void OsuDbParser::processData(string fullPathToOsuDb) {
	ifstream osuDbHandle;
	osuDbHandle.open(fullPathToOsuDb, ios::binary | ios::in);
	if (osuDbHandle) {
		(this)->osuVersion = (this)->readInt(osuDbHandle);
		(this)->folderCount = (this)->readInt(osuDbHandle);
		(this)->accountUnlocked = (this)->readBool(osuDbHandle);
		// skip through weird dateUnlock field which has 8 bytes
		osuDbHandle.seekg(8, ios::cur);
		(this)->playerName = (this)->readString(osuDbHandle);
		(this)->numberOfBeatmaps = (this)->readInt(osuDbHandle);

		// start parsing beatmapdata
		for (int b = 0; b < (this)->numberOfBeatmaps; b++) {
			OsuDbBeatmapDataS beatmap;
			beatmap.bytesOfBeatmapEntry = (this)->readInt(osuDbHandle);
			beatmap.artistName = (this)->readString(osuDbHandle);
			beatmap.artistNameUnicode = (this)->readString(osuDbHandle);
			beatmap.songTitle = (this)->readString(osuDbHandle);
			beatmap.songTitleUnicode = (this)->readString(osuDbHandle);
			beatmap.creatorName = (this)->readString(osuDbHandle);
			beatmap.difficulty = (this)->readString(osuDbHandle);
			beatmap.audioFileName = (this)->readString(osuDbHandle);
			beatmap.MD5Hash = (this)->readString(osuDbHandle);
			beatmap.nameOfOsuFile = (this)->readString(osuDbHandle);
			beatmap.rankedStatus = (this)->readChar(osuDbHandle);
			beatmap.numOfHitcircles = (this)->readByteToInt(osuDbHandle, 2);
			beatmap.numOfSliders = (this)->readByteToInt(osuDbHandle, 2);
			beatmap.numOfSpinners = (this)->readByteToInt(osuDbHandle, 2);
			beatmap.lastModificationTime = (this)->readLong(osuDbHandle);
			beatmap.AR = (this)->readFloat(osuDbHandle);
			beatmap.CS = (this)->readFloat(osuDbHandle);
			beatmap.HP = (this)->readFloat(osuDbHandle);
			beatmap.OD = (this)->readFloat(osuDbHandle);
			beatmap.sliderVelocity = (this)->readDouble(osuDbHandle);

			// starting of Int-Double Pairs
			// loop for 4 times: standard, taiko, CTB, and mania
			for (int i = 0; i < 4; i++) {
				unsigned int numberOfPairs = (this)->readInt(osuDbHandle);
				for (int j = 0; j < numberOfPairs; j++) {
					unsigned int modCombination;
					double starRating;
					unsigned char intPresent = (this)->readChar(osuDbHandle);
					if (intPresent == 0x08) { // if present. No use for now as this is the only value, but may change in future
						modCombination = (this)->readInt(osuDbHandle);
					}
					unsigned char doublePresent = (this)->readChar(osuDbHandle);
					if (doublePresent == 0x0d) {
						starRating = (this)->readDouble(osuDbHandle);
					}

					// it is assumed that all int and double are present
					switch (i) {
					case 0: {
						beatmap.standardModStarPair.insert({ modCombination, starRating });
						break;
					}
					case 1: {
						beatmap.taikoModStarPair.insert({ modCombination, starRating });
						break;
					}
					case 2: {
						beatmap.CTBModStarPair.insert({ modCombination, starRating });
						break;
					}
					case 3: {
						beatmap.maniaModStarPair.insert({ modCombination, starRating });
						break;
					}
					}
				}
			}
			// ending of Int-Double pairs

			beatmap.drainTime = (this)->readInt(osuDbHandle);
			beatmap.totalTime = (this)->readInt(osuDbHandle);
			beatmap.previewTime = (this)->readInt(osuDbHandle);

			// starting of timing points
			unsigned int numberOfTimingPoints = (this)->readInt(osuDbHandle);
			for (int i = 0; i < numberOfTimingPoints; i++) {
				OsuDbTimingPointDataS timingPoint;
				timingPoint.BPM = (this)->readDouble(osuDbHandle);
				timingPoint.offset = (this)->readDouble(osuDbHandle);
				timingPoint.inherited = (this)->readBool(osuDbHandle);
				beatmap.timingPoints.push_back(timingPoint);
			}
			// ending of timing points

			beatmap.beatmapID = (this)->readInt(osuDbHandle);
			beatmap.beatmapSetID = (this)->readInt(osuDbHandle);
			beatmap.threadID = (this)->readInt(osuDbHandle);
			beatmap.gradeStandard = (this)->readChar(osuDbHandle);
			beatmap.gradeTaiko = (this)->readChar(osuDbHandle);
			beatmap.gradeCTB = (this)->readChar(osuDbHandle);
			beatmap.gradeMania = (this)->readChar(osuDbHandle);
			beatmap.localOffset = (this)->readShort(osuDbHandle);
			beatmap.stackLeniency = (this)->readFloat(osuDbHandle);
			beatmap.gameplayMode = (this)->readChar(osuDbHandle);
			beatmap.songSource = (this)->readString(osuDbHandle);
			beatmap.songTags = (this)->readString(osuDbHandle);
			beatmap.onlineOffset = (this)->readShort(osuDbHandle);
			beatmap.fontUsed = (this)->readString(osuDbHandle);
			beatmap.isUnplayed = (this)->readBool(osuDbHandle);
			beatmap.lastPlayedTime = (this)->readLong(osuDbHandle);
			beatmap.isOsz2 = (this)->readBool(osuDbHandle);
			beatmap.folderName = (this)->readString(osuDbHandle);
			beatmap.lastCheckedTime = (this)->readLong(osuDbHandle);
			beatmap.ignoreBeatmapSound = (this)->readBool(osuDbHandle);
			beatmap.ignoreBeatmapSkin = (this)->readBool(osuDbHandle);
			beatmap.disableStoryboard = (this)->readBool(osuDbHandle);
			beatmap.disableVideo = (this)->readBool(osuDbHandle);
			beatmap.visualOverride = (this)->readBool(osuDbHandle);
			// skip through unknown int (last modification time?)
			osuDbHandle.seekg(sizeof(int), ios::cur);
			beatmap.maniaScrollSpeed = (this)->readChar(osuDbHandle);
			// finish parsing beatmap data
			// storing into member dict
			(this)->beatmaps.insert({ beatmap.nameOfOsuFile, beatmap });
		}
		// end parsing beatmaps

		// skip last unknown int
	}
	osuDbHandle.close();
}

bool OsuDbParser::readBool(ifstream &osuDbHandle) {
	bool output;
	osuDbHandle.read((char*)&output, sizeof(bool));
	return output;
}

unsigned char OsuDbParser::readChar(ifstream &osuDbHandle) {
	unsigned char output;
	osuDbHandle.read((char*)&output, sizeof(char));
	return output;
}

unsigned short OsuDbParser::readShort(ifstream &osuDbHandle) {
	unsigned short output;
	osuDbHandle.read((char*)&output, sizeof(short));
	return output;
}

unsigned int OsuDbParser::readInt(ifstream &osuDbHandle) {
	unsigned int output;
	osuDbHandle.read((char*)&output, sizeof(int));
	return output;
}

unsigned long long OsuDbParser::readLong(ifstream &osuDbHandle) {
	unsigned long long output;
	osuDbHandle.read((char*)&output, sizeof(long long));
	return output;
}

unsigned int OsuDbParser::readByteToInt(ifstream &osuDbHandle, int size) {
	unsigned int output = 0; // initialize to prevent junk value
	osuDbHandle.read((char*)&output, size);
	return output;
}

float OsuDbParser::readFloat(ifstream &osuDbHandle) {
	float output;
	osuDbHandle.read((char*)&output, sizeof(float));
	return output;
}

double OsuDbParser::readDouble(ifstream &osuDbHandle) {
	double output;
	osuDbHandle.read((char*)&output, sizeof(double));
	return output;
}

string OsuDbParser::readString(ifstream &osuDbHandle) {
	string output = ""; // return empty string if string is not found
	unsigned char stringPresent = (this)->readChar(osuDbHandle);
	if (stringPresent == 0x0b) { // if string is present
		unsigned int byteLengthOfString = 0;
		int shift = 0;
		while (true) {
			unsigned char bufferByte = (this)->readChar(osuDbHandle);
			// & 127 gets last 7 bits
			byteLengthOfString |= (bufferByte & 127) << shift;
			// & 128 gets 1st bit
			// if 1st bit == 0, the decode process ends
			if (!(bufferByte & (unsigned int)128)) {
				break;
			}
			shift += 7;
		}
		char* tempOutput = new char[byteLengthOfString + 1];
		osuDbHandle.read(tempOutput, byteLengthOfString);
		tempOutput[byteLengthOfString] = '\0';
		output = string(tempOutput);
		delete[] tempOutput;  // When done, free memory pointed to by a
	}
	return output;
}

repository: CookieHoodie/OsuDbParser

repo_name: CookieHoodie/OsuDbParser


text:
file(REMOVE_RECURSE
  "CMakeFiles/kheperaCalibration.dir/kheperaCalibration.cpp.o"
  "kheperaCalibration.pdb"
  "kheperaCalibration"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/kheperaCalibration.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: Chukwuemeka-Ike/kheperaIVPoseEstimation

repo_name: Chukwuemeka-Ike/kheperaIVPoseEstimation

extension: cmake


text:
SUMMARY = "NTK is a fork of FLTK"
SECTION = "libs"
LICENSE = "LGPL-2.0-only & FLTK"
LIC_FILES_CHKSUM = "file://COPYING;md5=f6b26344a24a941a01a5b0826e80b5ca"

SRC_URI = " \
    git://github.com/falkTX/ntk.git;branch=master;protocol=https \
    file://0001-wscript-check-compile-instead-of-tun-check-datatype-.patch \
    file://0002-Fix-build-for-python3-only-environments.patch \
"
SRCREV = "720d8d33200ebd030df700c6c7a5a9cdf4581c03"
S = "${WORKDIR}/git"
PV = "1.3.1001"

inherit waf pkgconfig

DEPENDS = " \
    cairo \
    libpng \
    jpeg \
    zlib \
    libxft \
"

WAF_EXTRA_CONF = " \
    --libdir=${libdir} \
"

do_install:append() {
    rm ${D}${libdir}/libntk.a
    rm ${D}${libdir}/libntk.a.1
    mv ${D}${libdir}/libntk.a.${PV} ${D}${libdir}/libntk.a

    rm ${D}${libdir}/libntk_images.a
    rm ${D}${libdir}/libntk_images.a.1
    mv ${D}${libdir}/libntk_images.a.${PV} ${D}${libdir}/libntk_images.a
}

BBCLASSEXTEND = "native"

repository: schnitzeltony/meta-musicians

repo_name: schnitzeltony/meta-musicians

gha_language: BitBake


text:
require pcmciautils.inc

PR = "r3"

CFLAGS =+ '-DPCMCIAUTILS_VERSION=010'

SRC_URI[md5sum] = "ff3cb012fd1a8801e912054b45420ac2"
SRC_URI[sha256sum] = "9ed7fe56197b4e1328a94842b602aef0a3a2e3380dacc95b4366661582e05661"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
DESCRIPTION = "Hello kernel module out of the kernel tree"
SECTION = "examples"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=12f884d2ae1ff87c09e5b7ccc2c4ca7e"
PR = "r0"

inherit module

SRC_URI =   "file://krev.c \
			file://Makefile \
			file://COPYING \
			"

S = "${WORKDIR}"

repository: robvogelaar/meta-rev

repo_name: robvogelaar/meta-rev


text:
//  Copyright (c) 2019 Cisco and/or its affiliates.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at:
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

package kvscheduler

import (
	"encoding/json"
	"expvar"
	"sync"
	"time"

	"go.ligato.io/vpp-agent/v3/pkg/metrics"
	kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
	"go.ligato.io/vpp-agent/v3/proto/ligato/kvscheduler"
)

var (
	stats   Stats
	statsMu sync.RWMutex
)

func init() {
	stats.GraphMethods.Methods = make(metrics.Calls)
	stats.AllDescriptors.Methods = make(metrics.Calls)
	stats.Descriptors = make(map[string]*StructStats)
	stats.TxnStats.Methods = make(metrics.Calls)
	stats.TxnStats.OperationCount = make(map[string]uint64)
	stats.TxnStats.ValueStateCount = make(map[string]uint64)
	for state := range kvscheduler.ValueState_value {
		stats.TxnStats.ValueStateCount[state] = 0
	}
	for op, opVal := range kvscheduler.TxnOperation_name {
		if op == int32(kvscheduler.TxnOperation_UNDEFINED) ||
			op == int32(kvscheduler.TxnOperation_VALIDATE) {
			continue
		}
		stats.TxnStats.OperationCount[opVal] = 0
	}
}

func GetStats() *Stats {
	s := new(Stats)
	statsMu.RLock()
	*s = stats
	statsMu.RUnlock()
	return s
}

type Stats struct {
	TxnStats       TxnStats
	GraphMethods   StructStats
	AllDescriptors StructStats
	Descriptors    map[string]*StructStats
}

func (s *Stats) addDescriptor(name string) {
	s.Descriptors[name] = &StructStats{
		Methods: make(metrics.Calls),
	}
}

type TxnStats struct {
	TotalProcessed  uint64
	OperationCount  map[string]uint64
	ValueStateCount map[string]uint64
	ErrorCount      uint64
	Methods         metrics.Calls
}

type StructStats struct {
	Methods metrics.Calls `json:"-,omitempty"`
}

func (s *StructStats) MarshalJSON() ([]byte, error) {
	return json.Marshal(s.Methods)
}

func (s *StructStats) getOrCreateMethod(method string) *metrics.CallStats {
	statsMu.RLock()
	ms, ok := s.Methods[method]
	statsMu.RUnlock()
	if !ok {
		ms = &metrics.CallStats{Name: method}
		statsMu.Lock()
		s.Methods[method] = ms
		statsMu.Unlock()
	}
	return ms
}

func trackDescMethod(d, m string) func() {
	t := time.Now()
	method := stats.Descriptors[d].getOrCreateMethod(m)
	methodall := stats.AllDescriptors.getOrCreateMethod(m)
	return func() {
		took := time.Since(t)
		statsMu.Lock()
		method.Increment(took)
		methodall.Increment(took)
		statsMu.Unlock()
	}
}

func trackGraphMethod(m string) func() {
	t := time.Now()
	method := stats.GraphMethods.getOrCreateMethod(m)
	return func() {
		took := time.Since(t)
		statsMu.Lock()
		method.Increment(took)
		statsMu.Unlock()
	}
}

func trackTransactionMethod(m string) func() {
	t := time.Now()
	s := stats.TxnStats
	return func() {
		took := time.Since(t)
		reportTxnProcessDuration(m, took.Seconds())
		statsMu.Lock()
		ms, tracked := s.Methods[m]
		if !tracked {
			ms = &metrics.CallStats{Name: m}
			s.Methods[m] = ms
		}
		ms.Increment(took)
		statsMu.Unlock()
	}
}

func updateTransactionStats(execOps kvs.RecordedTxnOps) {
	statsMu.Lock()
	defer statsMu.Unlock()
	stats.TxnStats.TotalProcessed++
	for _, op := range execOps {
		if op.NewErr != nil {
			stats.TxnStats.ErrorCount++
		}
		stats.TxnStats.OperationCount[op.Operation.String()]++
		stats.TxnStats.ValueStateCount[op.NewState.String()]++
	}
}

func init() {
	expvar.Publish("kvscheduler", expvar.Func(func() interface{} {
		return GetStats()
	}))
}

repository: ligato/vpp-agent

repo_name: ligato/vpp-agent